trtc-sdk-v5 5.5.0-beta.8 → 5.5.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/trtc.esm.js +21 -19
  3. package/trtc.js +1 -1
package/trtc.js CHANGED
@@ -1 +1 @@
1
- !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).TRTC=t()}(this,(function(){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:{},i=function(e){try{return!!e()}catch(t){return!0}},n=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=n,o=Function.prototype,s=o.call,a=r&&o.bind.bind(s,s),c=r?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,S=TypeError,I=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,y=I,A=function(e){return v(y(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},N=C,D=Object.defineProperty,O=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0})}catch(i){N[e]=t}return t},w=O,P="__core-js_shared__",L=C[P]||w(P,{}),M=L;(k.exports=function(e,t){return M[e]||(M[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=I,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),G=Object.hasOwn||function(e,t){return j(H(e),t)},W=c,J=0,K=Math.random(),z=W(1..toString),Y=function(e){return"Symbol("+(void 0===e?"":e)+")_"+z(++J+K,36)},q="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=q,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=G,le=Y,de=oe,ue=se,he=C.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,_e=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===Ie}:function(e){return"object"==typeof e?null!==e:Se(e)},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Le=function(e){return Pe?we.createElement(e):{}},Me=Le,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Me("div"),"a",{get:function(){return 7}}).a})),Ve=n,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,ze=Object,Ye=se?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&Ke(t.prototype,ze(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=Ye,ut=nt,ht=function(e,t){var i,n;if("string"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if("string"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,mt);if(n){if(void 0===t&&(t="default"),i=ct(n,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=Ye,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,St=xe,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Nt="writable";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Nt in i&&!i[Nt]){var n=Ct(e,t);n&&n[Nt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i)}catch(n){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Dt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Dt)(t)},Pt=wt,Lt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Mt=Lt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Mt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Lt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Gt=function(e){return jt(e.length)},Wt=A,Jt=Ut,Kt=Gt,zt=function(e){return function(t,i,n){var r,o=Wt(t),s=Kt(o),a=Jt(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}},Yt={includes:zt(!0),indexOf:zt(!1)},qt={},Qt=G,Xt=A,$t=Yt.indexOf,Zt=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt(Zt,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri)},si=ke,ai=Ne,ci=De,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e};var hi,pi=je("document","documentElement"),mi=Y,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,Si=qt,Ii=pi,vi=Le,yi="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ni=function(){try{hi=new ActiveXObject("htmlfile")}catch(r){}var e,t,i;Ni="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Ni[yi][Ei[n]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},Oi=_e,wi=Di,Pi=De.f,Li=Oi("unscopables"),Mi=Array.prototype;null==Mi[Li]&&Pi(Mi,Li,{configurable:!0,value:wi(null)});var xi,Vi,Ui,Fi=function(e){Mi[Li][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=De,Ki=Wi,zi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},Yi=Gi,qi=C,Qi=ve,Xi=zi,$i=G,Zi=L,en=fi,tn=qt,nn="Object already initialized",rn=qi.TypeError,on=qi.WeakMap;if(Yi||Zi.state){var sn=Zi.state||(Zi.state=new on);sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,xi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t},Vi=function(e){return sn.get(e)||{}},Ui=function(e){return sn.has(e)}}else{var an=en("state");tn[an]=!0,xi=function(e,t){if($i(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t},Vi=function(e){return $i(e,an)?e[an]:{}},Ui=function(e){return $i(e,an)}}var cn={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rn("Incompatible receiver, "+e+" required");return i}}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable}:un;var mn=ke,_n=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=xe,vn=Object.getOwnPropertyDescriptor;ln.f=mn?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t)}catch(i){}if(Sn(e,t))return gn(!_n(fn.f,e,t),e[t])};var yn={},An={get exports(){return yn},set exports(e){yn=e}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Nn=Cn(bn,"name"),Dn={EXISTS:Nn,PROPER:Nn&&"something"===function(){}.name,CONFIGURABLE:Nn&&(!Rn||Rn&&kn(bn,"name").configurable)},On=Ee,wn=L,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e)});var Ln=wn.inspectSource,Mn=c,xn=i,Vn=Ee,Un=G,Fn=ke,Bn=Dn.CONFIGURABLE,Hn=Ln,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,Kn=Mn("".slice),zn=Mn("".replace),Yn=Mn([].join),qn=Fn&&!xn((function(){return 8!==Jn((function(){}),"length",{value:8}).length})),Qn=String(String).split("String"),Xn=An.exports=function(e,t,i){"Symbol("===Kn(Wn(t),0,7)&&(t="["+zn(Wn(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Un(e,"name")||Bn&&e.name!==t)&&(Fn?Jn(e,"name",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,"arity")&&e.length!==i.arity&&Jn(e,"length",{value:i.arity});try{i&&Un(i,"constructor")&&i.constructor?Fn&&Jn(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(r){}var n=jn(e);return Un(n,"source")||(n.source=Yn(Qn,"string"==typeof t?t:"")),e};Function.prototype.toString=Xn((function(){return Vn(this)&&Gn(this).source||Hn(this)}),"toString");var $n=Ee,Zn=De,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if($n(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t]}catch(s){}r?e[t]=i:Zn.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},nr={},rr=ti,or=ii.concat("length","prototype");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or)};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,mr=c([].concat),_r=dr("Reflect","ownKeys")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?mr(t,i(e)):t},fr=G,gr=_r,Tr=ln,Er=De,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s<n.length;s++){var a=n[s];fr(e,a)||i&&fr(i,a)||r(e,a,o(t,a))}},Ir=i,vr=Ee,yr=/#|\.prototype\./,Ar=function(e,t){var i=Cr[Rr(e)];return i==kr||i!=br&&(vr(t)?Ir(t):!!t)},Rr=Ar.normalize=function(e){return String(e).replace(yr,".").toLowerCase()},Cr=Ar.data={},br=Ar.NATIVE="N",kr=Ar.POLYFILL="P",Nr=Ar,Dr=C,Or=ln.f,wr=zi,Pr=ir,Lr=O,Mr=Sr,xr=Nr,Vr=function(e,t){var i,n,r,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Dr:l?Dr[a]||Lr(a,{}):(Dr[a]||{}).prototype)for(n in t){if(o=t[n],r=e.dontCallGetSet?(s=Or(i,n))&&s.value:i[n],!xr(c?n:a+(l?".":"#")+n,e.forced)&&void 0!==r){if(typeof o==typeof r)continue;Mr(o,r)}(e.sham||r&&r.sham)&&wr(o,"sham",!0),Pr(i,n,o,e)}},Ur=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fr=G,Br=Ee,Hr=B,jr=Ur,Gr=fi("IE_PROTO"),Wr=Object,Jr=Wr.prototype,Kr=jr?Wr.getPrototypeOf:function(e){var t=Hr(e);if(Fr(t,Gr))return t[Gr];var i=t.constructor;return Br(i)&&t instanceof i?i.prototype:t instanceof Wr?Jr:null},zr=i,Yr=Ee,qr=ve,Qr=Kr,Xr=ir,$r=_e("iterator"),Zr=!1;[].keys&&("next"in(lr=[].keys())?(cr=Qr(Qr(lr)))!==Object.prototype&&(ar=cr):Zr=!0);var eo=!qr(ar)||zr((function(){var e={};return ar[$r].call(e)!==e}));eo&&(ar={}),Yr(ar[$r])||Xr(ar,$r,(function(){return this}));var to={IteratorPrototype:ar,BUGGY_SAFARI_ITERATORS:Zr},io=De.f,no=G,ro=_e("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!no(e,ro)&&io(e,ro,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Di,co=Wi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ao(so,{next:co(+!n,i)}),lo(e,r,!1),uo[r]=ho,e},mo=c,_o=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return mo(_o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(n){}},So=Ce,Io=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(n){}return function(i,n){return So(i),Io(n),t?e(i,n):i.__proto__=n,i}}():void 0),yo=Vr,Ao=Fe,Ro=Ee,Co=po,bo=Kr,ko=vo,No=oo,Do=zi,Oo=ir,wo=Bi,Po=Dn.PROPER,Lo=Dn.CONFIGURABLE,Mo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=_e("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,n,r,o,s){Co(i,t,n);var a,c,l,d=function(e){if(e===r&&_)return _;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||r&&p[r],_=!xo&&m||d(r),f="Array"==t&&p.entries||m;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Mo&&(ko?ko(a,Mo):Ro(a[Vo])||Oo(a,Vo,Ho)),No(a,u,!0)),Po&&r==Fo&&m&&m.name!==Fo&&(Lo?Do(p,"name",Fo):(h=!0,_=function(){return Ao(m,this)})),r)if(c={values:d(Fo),keys:o?_:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&Oo(p,l,c[l]);else yo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&Oo(p,Vo,_,{name:r}),wo[t]=_,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,Ko=Bi,zo=cn,Yo=De.f,qo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=zo.set,es=zo.getterFor($o),ts=qo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),is=Ko.Arguments=Ko.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{Yo(is,"name",{value:"values"})}catch($U){}var ns={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},rs=Le("span").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=zi,hs=_e,ps=hs("iterator"),ms=hs("toStringTag"),_s=ds.values,fs=function(e,t){if(e){if(e[ps]!==_s)try{us(e,ps,_s)}catch($U){e[ps]=_s}if(e[ms]||us(e,ms,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i])}catch($U){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=yn,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,ys=Is,As=ke,Rs=_e("species"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&ys(t,Rs,{configurable:!0,get:function(){return this}})},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ds={};Ds[_e("toStringTag")]="z";var Os="[object z]"===String(Ds),ws=Ee,Ps=h,Ls=_e("toStringTag"),Ms=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=Os?Ps: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($U){}}(t=Ms(e),Ls))?i:xs?Ps(t):"Object"==(n=Ps(t))&&ws(t.callee)?"Arguments":n},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Ln,Gs=function(){},Ws=[],Js=je("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,zs=Us(Ks.exec),Ys=!Ks.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch($U){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ys||!!zs(Ks,js(e))}catch($U){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return qs(qs.call)||!qs(Object)||!qs((function(){e=!0}))||e}))?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=_e("species"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i)},ua=n,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(q),ba=C,ka=_a,Na=va,Da=Ee,Oa=G,wa=i,Pa=pi,La=ya,Ma=Le,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Ga=ba.Function,Wa=ba.MessageChannel,Ja=ba.String,Ka=0,za={},Ya="onreadystatechange";wa((function(){Xs=ba.location}));var qa=function(e){if(Oa(za,e)){var t=za[e];delete za[e],t()}},Qa=function(e){return function(){qa(e)}},Xa=function(e){qa(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Da(e)?e:Ga(e),i=La(arguments,1);return za[++Ka]=function(){ka(t,void 0,i)},$s(Ka),Ka},Ba=function(e){delete za[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Wa&&!Va?(ea=(Zs=new Wa).port2,Zs.port1.onmessage=Xa,$s=Na(ea.postMessage,ea)):ba.addEventListener&&Da(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!wa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=Ya in Ma("script")?function(e){Pa.appendChild(Ma("script"))[Ya]=function(){Pa.removeChild(this),qa(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,nc,rc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(q)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(q),lc=C,dc=va,uc=ln.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,Ic=lc.Promise,vc=uc(lc,"queueMicrotask"),yc=vc&&vc.value;if(!yc){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch($U){throw Ac.head&&tc(),$U}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&Ic&&Ic.resolve?((rc=Ic.resolve(void 0)).constructor=Ic,oc=dc(rc.then,rc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,nc=Ec.createTextNode(""),new Tc(Rc).observe(nc,{characterData:!0}),tc=function(){nc.data=ic=!ic}),yc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=yc,bc=function(e){try{return{error:!1,value:e()}}catch($U){return{error:!0,value:$U}}},kc=C.Promise,Nc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!Nc&&!Ts&&"object"==typeof window&&"object"==typeof document,Oc=C,wc=kc,Pc=Ee,Lc=Nr,Mc=Ln,xc=_e,Vc=Dc,Uc=Nc,Fc=ie;wc&&wc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(Oc.PromiseRejectionEvent),Gc=Lc("Promise",(function(){var e=Mc(wc),t=e!==String(wc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new wc((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=n,!(Hc=i.then((function(){}))instanceof n))return!0}return!t&&(Vc||Uc)&&!jc})),Wc={CONSTRUCTOR:Gc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},Kc=et,zc=TypeError,Yc=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw zc("Bad Promise constructor");t=e,i=n})),this.resolve=Kc(t),this.reject=Kc(i)};Jc.f=function(e){return new Yc(e)};var qc,Qc,Xc,$c=Vr,Zc=Ts,el=C,tl=Fe,il=ir,nl=vo,rl=oo,ol=Cs,sl=et,al=Ee,cl=ve,ll=Ns,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch($U){}},ml=bc,_l=sc,fl=cn,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,Il=Wc.REJECTION_EVENT,vl=Wc.SUBCLASSING,yl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Nl=el.document,Dl=el.process,Ol=Tl.f,wl=Ol,Pl=!!(Nl&&Nl.createEvent&&el.dispatchEvent),Ll="unhandledrejection",Ml=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),r=!0)),i===e.promise?l(kl("Promise-chain cycle")):(n=Ml(i))?tl(n,i,c,l):c(i)):l(o)}catch($U){d&&!r&&d.exit(),l($U)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,n=e.reactions;i=n.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var n,r;Pl?((n=Nl.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),el.dispatchEvent(n)):n={promise:t,reason:i},!Il&&(r=el["on"+e])?r(n):e===Ll&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,n=e.value;if(Bl(e)&&(t=ml((function(){Zc?Dl.emit("unhandledRejection",n,i):Ul(Ll,i,n)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(n){e(t,n,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var n=Ml(t);n?hl((function(){var i={done:!1};try{tl(n,t,jl(Wl,i,e),jl(Gl,i,e))}catch($U){Gl(i,$U,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch($U){Gl({done:!1},$U,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(qc,this);var t=yl(this);try{e(jl(Wl,t),jl(Gl,t))}catch($U){Gl(t,$U)}}).prototype,(qc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=yl(this),n=Ol(dl(this,Cl));return i.parent=!0,n.ok=!al(e)||e,n.fail=al(t)&&t,n.domain=Zc?Dl.domain:void 0,0==i.state?i.reactions.add(n):hl((function(){xl(n,i)})),n.promise})),Qc=function(){var e=new qc,t=yl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=Ol=function(e){return e===Cl||undefined===e?new Qc(e):wl(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,vl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch($U){}nl&&nl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),rl(Cl,El,!1),ol(El);var Jl=Bi,Kl=_e("iterator"),zl=Array.prototype,Yl=function(e){return void 0!==e&&(Jl.Array===e||zl[Kl]===e)},ql=Vs,Ql=nt,Xl=T,$l=Bi,Zl=_e("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[ql(e)]},td=Fe,id=et,nd=Ce,rd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return nd(td(i,e));throw sd(rd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=nt,ud=function(e,t,i){var n,r;ld(e);try{if(!(n=dd(e,"return"))){if("throw"===t)throw i;return i}n=cd(n,e)}catch($U){r=!0,n=$U}if("throw"===t)throw i;if(r)throw n;return ld(n),i},hd=va,pd=Fe,md=Ce,_d=Qe,fd=Yl,gd=Gt,Td=Ge,Ed=ad,Sd=ed,Id=ud,vd=TypeError,yd=function(e,t){this.stopped=e,this.result=t},Ad=yd.prototype,Rd=function(e,t,i){var n,r,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return n&&Id(n,"normal",e),new yd(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=Sd(e)))throw vd(_d(e)+" is not iterable");if(fd(r)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1)}n=Ed(e,r)}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value)}catch($U){Id(n,"throw",$U)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Nd[Cd]=function(){return this},Array.from(Nd,(function(){throw 2}))}catch($U){}var Dd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch($U){}return i},Od=kc,wd=Wc.CONSTRUCTOR||!Dd((function(e){Od.all(e).then(void 0,(function(){}))})),Pd=Fe,Ld=et,Md=Jc,xd=bc,Vd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Md.f(t),n=i.resolve,r=i.reject,o=xd((function(){var i=Ld(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ud=Vr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var Kd=Fe,zd=et,Yd=Jc,qd=bc,Qd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{race:function(e){var t=this,i=Yd.f(t),n=i.reject,r=qd((function(){var r=zd(t.resolve);Qd(e,(function(e){Kd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Xd=Fe,$d=Jc;Vr({target:"Promise",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},nu=Vr,ru=Wc.CONSTRUCTOR,ou=iu;je("Promise"),nu({target:"Promise",stat:!0,forced:ru},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e},du=ve,uu=h,hu=_e("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},mu=Vs,_u=String,fu=function(e){if("Symbol"===mu(e))throw TypeError("Cannot convert a Symbol value to a string");return _u(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in yu||Su(e,"flags")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Nu=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=De.f,wu=i,Pu=C.RegExp,Lu=wu((function(){var e=Pu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Mu=i,xu=C.RegExp,Vu=Mu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Uu=ke,Fu=C,Bu=c,Hu=Nr,ju=lu,Gu=zi,Wu=nr.f,Ju=Ge,Ku=pu,zu=fu,Yu=Au,qu=Du,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=ir,$u=i,Zu=G,eh=cn.enforce,th=Cs,ih=Lu,nh=Vu,rh=_e("match"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu("".charAt),dh=Bu("".replace),uh=Bu("".indexOf),hh=Bu("".slice),ph=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,mh=/a/g,_h=/a/g,fh=new oh(mh)!==mh,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||$u((function(){return _h[rh]=!1,oh(mh)!=mh||oh(_h)==_h||"/a/i"!=oh(mh,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=Yu(h))),e=void 0===e?"":zu(e),t=void 0===t?"":zu(t),h=e,ih&&"dotAll"in mh&&(n=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in mh&&(r=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),nh&&(o=function(e){for(var t,i=e.length,n=0,r="",o=[],s={},a=!1,c=!1,l=0,d="";n<=i;n++){if("\\"===(t=lh(e,n)))t+=lh(e,++n);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:r+=t}return[r,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r="",o=!1;n<=i;n++)"\\"!==(t=lh(e,n))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),r+=t):r+="[\\s\\S]":r+=t+lh(e,++n);return r}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch($U){}return s},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,"RegExp",Sh,{constructor:!0})}th("RegExp");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=cn.get,Dh=Lu,Oh=Vu,wh=b("native-string-replace",String.prototype.replace),Ph=RegExp.prototype.exec,Lh=Ph,Mh=Ah("".charAt),xh=Ah("".indexOf),Vh=Ah("".replace),Uh=Ah("".slice),Fh=function(){var e=/a/,t=/b*/g;return yh(Ph,e,"a"),yh(Ph,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec("")[1];(Fh||Hh||Bh||Dh||Oh)&&(Lh=function(e){var t,i,n,r,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Lh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,m=yh(Ch,c),_=c.source,f=0,g=d;if(p&&(m=Vh(m,"y",""),-1===xh(m,"g")&&(m+="g"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Mh(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Hh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Fh&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(r[o]=void 0)})),r&&h)for(r.groups=s=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=r[a[1]];return r});var jh=Lh;Vr({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,Kh=ta,zh=ve,Yh=_e("species"),qh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(Kh(t)&&(t===qh||Jh(t.prototype))||zh(t)&&null===(t=t[Yh]))&&(t=void 0)),void 0===t?qh:t},Xh=va,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),np=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Zh(c),_=$h(m),f=Xh(l,d),g=ep(_),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:n||r?r:S}},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=rp.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=ns,up=ss,hp=cp,pp=zi,mp=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch($U){e.forEach=hp}};for(var _p in dp)dp[_p]&&mp(lp[_p]&&lp[_p].prototype);mp(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Sp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r}},vp={left:Ip(!1),right:Ip(!0)}.left;Vr({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=_e,kp=zi,Np=bp("species"),Dp=RegExp.prototype,Op=c,wp=Lt,Pp=fu,Lp=I,Mp=Op("".charAt),xp=Op("".charCodeAt),Vp=Op("".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Lp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=xp(o,s))<55296||n>56319||s+1===a||(r=xp(o,s+1))<56320||r>57343?e?Mp(o,s):n:e?Vp(o,s,s+2):r-56320+(n-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),Kp=Hp("".slice),zp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Yp=/\$([$&'`]|\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=Yp;return void 0!==r&&(r=jp(r),c=zp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return Kp(t,0,i);case"'":return Kp(t,s);case"<":l=r[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o}l=n[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,em=jh,tm=TypeError,im=_a,nm=Fe,rm=c,om=function(e,t,i,n){var r=bp(e),o=!Cp((function(){var t={};return t[r]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags="",i[r]=/./[r]),i.exec=function(){return t=!0,null},i[r](""),!t}));if(!o||!s||i){var a=yp(/./[r]),c=t(r,""[e],(function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,r,c[1])}n&&kp(Dp[r],"sham",!0)},sm=i,am=Ce,cm=Ee,lm=T,dm=Lt,um=Ht,hm=fu,pm=I,mm=function(e,t,i){return t+(i?Bp(e,t).length:1)},_m=nt,fm=qp,gm=function(e,t){var i=e.exec;if($p(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n}if("RegExp"===Zp(e))return Qp(em,e,t);throw tm("RegExp#exec called on incompatible receiver")},Tm=_e("replace"),Em=Math.max,Sm=Math.min,Im=rm([].concat),vm=rm([].push),ym=rm("".indexOf),Am=rm("".slice),Rm=function(e){return void 0===e?e:String(e)},Cm="$0"==="a".replace(/./,"$0"),bm=!!/./[Tm]&&""===/./[Tm]("a","$0"),km=!sm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));om("replace",(function(e,t,i){var n=bm?"$":"$0";return[function(e,i){var n=pm(this),r=lm(e)?void 0:_m(e,Tm);return r?nm(r,e,n,i):nm(t,hm(n),e,i)},function(e,r){var o=am(this),s=hm(e);if("string"==typeof r&&-1===ym(r,n)&&-1===ym(r,"$<")){var a=i(t,o,s,r);if(a.done)return a.value}var c=cm(r);c||(r=hm(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=gm(o,s);if(null===h)break;if(vm(u,h),!l)break;""===hm(h[0])&&(o.lastIndex=mm(s,um(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=hm((h=u[_])[0]),g=Em(Sm(dm(h.index),s.length),0),T=[],E=1;E<h.length;E++)vm(T,Rm(h[E]));var S=h.groups;if(c){var I=Im([f],T,g,s);void 0!==S&&vm(I,S);var v=hm(im(r,void 0,I))}else v=fm(f,s,g,T,S,r);g>=m&&(p+=Am(s,m,g)+v,m=g+f.length)}return p+Am(s,m)}]}),!km||!Cm||bm);var Nm=Yt.includes,Dm=Fi;Vr({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Nm(this,e,arguments.length>1?arguments[1]:void 0)}}),Dm("includes");var Om=Lt,wm=fu,Pm=I,Lm=RangeError,Mm=c,xm=Ht,Vm=fu,Um=I,Fm=Mm((function(e){var t=wm(Pm(this)),i="",n=Om(e);if(n<0||Infinity==n)throw Lm("Wrong number of repetitions");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i})),Bm=Mm("".slice),Hm=Math.ceil,jm=function(e){return function(t,i,n){var r,o,s=Vm(Um(t)),a=xm(i),c=s.length,l=void 0===n?" ":Vm(n);return a<=c||""==l?s:((o=Fm(l,Hm((r=a-c)/l.length))).length>r&&(o=Bm(o,0,r)),e?s+o:o+s)}},Gm={start:jm(!1),end:jm(!0)},Wm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),Jm=Gm.start;Vr({target:"String",proto:!0,forced:Wm},{padStart:function(e){return Jm(this,e,arguments.length>1?arguments[1]:void 0)}});var Km=i,zm=ke,Ym=_e("iterator"),qm=!Km((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),!t.size&&!zm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Ym]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),Qm=ir,Xm=function(e,t,i){for(var n in t)Qm(e,n,t[n],i);return e},$m=Tt,Zm=De,e_=Wi,t_=function(e,t,i){var n=$m(t);n in e?Zm.f(e,n,e_(0,i)):e[n]=i},i_=Ut,n_=Gt,r_=t_,o_=Array,s_=Math.max,a_=function(e,t,i){for(var n=n_(e),r=i_(t,n),o=i_(void 0===i?n:i,n),s=o_(s_(o-r,0)),a=0;r<o;r++,a++)r_(s,a,e[r]);return s.length=a,s},c_=a_,l_=Math.floor,d_=function(e,t){var i=e.length,n=l_(i/2);return i<8?u_(e,t):h_(e,d_(c_(e,0,n),t),d_(c_(e,n),t),t)},u_=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},h_=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},p_=d_,m_=Vr,__=C,f_=Fe,g_=c,T_=ke,E_=qm,S_=ir,I_=Is,v_=Xm,y_=oo,A_=po,R_=cn,C_=Ns,b_=Ee,k_=G,N_=va,D_=Vs,O_=Ce,w_=ve,P_=fu,L_=Di,M_=Wi,x_=ad,V_=ed,U_=Ra,F_=p_,B_=_e("iterator"),H_="URLSearchParams",j_=H_+"Iterator",G_=R_.set,W_=R_.getterFor(H_),J_=R_.getterFor(j_),K_=Object.getOwnPropertyDescriptor,z_=function(e){if(!T_)return __[e];var t=K_(__,e);return t&&t.value},Y_=z_("fetch"),q_=z_("Request"),Q_=z_("Headers"),X_=q_&&q_.prototype,$_=Q_&&Q_.prototype,Z_=__.RegExp,ef=__.TypeError,tf=__.decodeURIComponent,nf=__.encodeURIComponent,rf=g_("".charAt),of=g_([].join),sf=g_([].push),af=g_("".replace),cf=g_([].shift),lf=g_([].splice),df=g_("".split),uf=g_("".slice),hf=/\+/g,pf=Array(4),mf=function(e){return pf[e-1]||(pf[e-1]=Z_("((?:%[\\da-f]{2}){"+e+"})","gi"))},_f=function(e){try{return tf(e)}catch($U){return e}},ff=function(e){var t=af(e,hf," "),i=4;try{return tf(t)}catch($U){for(;i;)t=af(t,mf(i--),_f);return t}},gf=/[!'()~]|%20/g,Tf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Ef=function(e){return Tf[e]},Sf=function(e){return af(nf(e),gf,Ef)},If=A_((function(e,t){G_(this,{type:j_,iterator:x_(W_(e).entries),kind:t})}),"Iterator",(function(){var e=J_(this),t=e.kind,i=e.iterator.next(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.value]),i}),!0),vf=function(e){this.entries=[],this.url=null,void 0!==e&&(w_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rf(e,0)?uf(e,1):e:P_(e)))};vf.prototype={type:H_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,n,r,o,s,a,c=V_(e);if(c)for(i=(t=x_(e,c)).next;!(n=f_(i,t)).done;){if(o=(r=x_(O_(n.value))).next,(s=f_(o,r)).done||(a=f_(o,r)).done||!f_(o,r).done)throw ef("Expected sequence with length 2");sf(this.entries,{key:P_(s.value),value:P_(a.value)})}else for(var l in e)k_(e,l)&&sf(this.entries,{key:l,value:P_(e[l])})},parseQuery:function(e){if(e)for(var t,i,n=df(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=df(t,"="),sf(this.entries,{key:ff(cf(i)),value:ff(of(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],sf(i,Sf(e.key)+"="+Sf(e.value));return of(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yf=function(){C_(this,Af);var e=G_(this,new vf(arguments.length>0?arguments[0]:void 0));T_||(this.length=e.entries.length)},Af=yf.prototype;if(v_(Af,{append:function(e,t){U_(arguments.length,2);var i=W_(this);sf(i.entries,{key:P_(e),value:P_(t)}),T_||this.length++,i.updateURL()},delete:function(e){U_(arguments.length,1);for(var t=W_(this),i=t.entries,n=P_(e),r=0;r<i.length;)i[r].key===n?lf(i,r,1):r++;T_||(this.length=i.length),t.updateURL()},get:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=[],r=0;r<t.length;r++)t[r].key===i&&sf(n,t[r].value);return n},has:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=0;n<t.length;)if(t[n++].key===i)return!0;return!1},set:function(e,t){U_(arguments.length,1);for(var i,n=W_(this),r=n.entries,o=!1,s=P_(e),a=P_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?lf(r,c--,1):(o=!0,i.value=a));o||sf(r,{key:s,value:a}),T_||(this.length=r.length),n.updateURL()},sort:function(){var e=W_(this);F_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=W_(this).entries,n=N_(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new If(this,"keys")},values:function(){return new If(this,"values")},entries:function(){return new If(this,"entries")}},{enumerable:!0}),S_(Af,B_,Af.entries,{name:"entries"}),S_(Af,"toString",(function(){return W_(this).serialize()}),{enumerable:!0}),T_&&I_(Af,"size",{get:function(){return W_(this).entries.length},configurable:!0,enumerable:!0}),y_(yf,H_),m_({global:!0,constructor:!0,forced:!E_},{URLSearchParams:yf}),!E_&&b_(Q_)){var Rf=g_($_.has),Cf=g_($_.set),bf=function(e){if(w_(e)){var t,i=e.body;if(D_(i)===H_)return t=e.headers?new Q_(e.headers):new Q_,Rf(t,"content-type")||Cf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),L_(e,{body:M_(0,P_(i)),headers:M_(0,t)})}return e};if(b_(Y_)&&m_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Y_(e,arguments.length>1?bf(arguments[1]):{})}}),b_(q_)){var kf=function(e){return C_(this,X_),new q_(e,arguments.length>1?bf(arguments[1]):{})};X_.constructor=kf,kf.prototype=X_,m_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:kf})}}var Nf={URLSearchParams:yf,getState:W_},Df="\t\n\v\f\r                 \u2028\u2029\ufeff",Of=I,wf=fu,Pf=Df,Lf=c("".replace),Mf=RegExp("^["+Pf+"]+"),xf=RegExp("(^|[^"+Pf+"])["+Pf+"]+$"),Vf=function(e){return function(t){var i=wf(Of(t));return 1&e&&(i=Lf(i,Mf,"")),2&e&&(i=Lf(i,xf,"$1")),i}},Uf={start:Vf(1),end:Vf(2),trim:Vf(3)},Ff=Dn.PROPER,Bf=i,Hf=Df,jf=Uf.trim;Vr({target:"String",proto:!0,forced:function(e){return Bf((function(){return!!Hf[e]()||"​…᠎"!=="​…᠎"[e]()||Ff&&Hf[e].name!==e}))}("trim")},{trim:function(){return jf(this)}});var Gf=Vr,Wf=ke,Jf=c,Kf=G,zf=Ee,Yf=Ge,qf=fu,Qf=Is,Xf=Sr,$f=C.Symbol,Zf=$f&&$f.prototype;if(Wf&&zf($f)&&(!("description"in Zf)||void 0!==$f().description)){var eg={},tg=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:qf(arguments[0]),t=Yf(Zf,this)?new $f(e):void 0===e?$f():$f(e);return""===e&&(eg[t]=!0),t};Xf(tg,$f),tg.prototype=Zf,Zf.constructor=tg;var ig="Symbol(test)"==String($f("test")),ng=Jf(Zf.valueOf),rg=Jf(Zf.toString),og=/^Symbol\((.*)\)[^)]+$/,sg=Jf("".replace),ag=Jf("".slice);Qf(Zf,"description",{configurable:!0,get:function(){var e=ng(this);if(Kf(eg,e))return"";var t=rg(e),i=ig?ag(t,7,-1):sg(t,og,"$1");return""===i?void 0:i}}),Gf({global:!0,constructor:!0,forced:!0},{Symbol:tg})}var cg=Fp.charAt,lg=fu,dg=cn,ug=jo,hg=Go,pg="String Iterator",mg=dg.set,_g=dg.getterFor(pg);ug(String,"String",(function(e){mg(this,{type:pg,string:lg(e),index:0})}),(function(){var e,t=_g(this),i=t.string,n=t.index;return n>=i.length?hg(void 0,!0):(e=cg(i,n),t.index+=e.length,hg(e,!1))}));var fg,gg=ke,Tg=c,Eg=Fe,Sg=i,Ig=oi,vg=sr,yg=dn,Ag=B,Rg=g,Cg=Object.assign,bg=Object.defineProperty,kg=Tg([].concat),Ng=!Cg||Sg((function(){if(gg&&1!==Cg({b:1},Cg(bg({},"a",{enumerable:!0,get:function(){bg(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!=Cg({},e)[i]||Ig(Cg({},t)).join("")!=n}))?function(e,t){for(var i=Ag(e),n=arguments.length,r=1,o=vg.f,s=yg.f;n>r;)for(var a,c=Rg(arguments[r++]),l=o?kg(Ig(c),o(c)):Ig(c),d=l.length,u=0;d>u;)a=l[u++],gg&&!Eg(s,c,a)||(i[a]=c[a]);return i}:Cg,Dg=Ce,Og=ud,wg=va,Pg=Fe,Lg=B,Mg=function(e,t,i,n){try{return n?t(Dg(i)[0],i[1]):t(i)}catch($U){Og(e,"throw",$U)}},xg=Yl,Vg=ta,Ug=Gt,Fg=t_,Bg=ad,Hg=ed,jg=Array,Gg=c,Wg=2147483647,Jg=/[^\0-\u007E]/,Kg=/[.\u3002\uFF0E\uFF61]/g,zg="Overflow: input needs wider integers to process",Yg=RangeError,qg=Gg(Kg.exec),Qg=Math.floor,Xg=String.fromCharCode,$g=Gg("".charCodeAt),Zg=Gg([].join),eT=Gg([].push),tT=Gg("".replace),iT=Gg("".split),nT=Gg("".toLowerCase),rT=function(e){return e+22+75*(e<26)},oT=function(e,t,i){var n=0;for(e=i?Qg(e/700):e>>1,e+=Qg(e/t);e>455;)e=Qg(e/35),n+=36;return Qg(n+36*e/(e+38))},sT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=$g(e,i++);if(r>=55296&&r<=56319&&i<n){var o=$g(e,i++);56320==(64512&o)?eT(t,((1023&r)<<10)+(1023&o)+65536):(eT(t,r),i--)}else eT(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&eT(t,Xg(n));var c=t.length,l=c;for(c&&eT(t,"-");l<r;){var d=Wg;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<d&&(d=n);var u=l+1;if(d-o>Qg((Wg-s)/u))throw Yg(zg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((n=e[i])<o&&++s>Wg)throw Yg(zg);if(n==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;eT(t,Xg(rT(m+_%f))),h=Qg(_/f),p+=36}eT(t,Xg(rT(h))),a=oT(s,u,l==c),s=0,l++}}s++,o++}return Zg(t,"")},aT=Vr,cT=ke,lT=qm,dT=C,uT=va,hT=c,pT=ir,mT=Is,_T=Ns,fT=G,gT=Ng,TT=function(e){var t=Lg(e),i=Vg(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=wg(r,n>2?arguments[2]:void 0));var s,a,c,l,d,u,h=Hg(t),p=0;if(!h||this===jg&&xg(h))for(s=Ug(t),a=i?new this(s):jg(s);s>p;p++)u=o?r(t[p],p):t[p],Fg(a,p,u);else for(d=(l=Bg(t,h)).next,a=i?new this:[];!(c=Pg(d,l)).done;p++)u=o?Mg(l,r,[c.value,p],!0):c.value,Fg(a,p,u);return a.length=p,a},ET=a_,ST=Fp.codeAt,IT=function(e){var t,i,n=[],r=iT(tT(nT(e),Kg,"."),".");for(t=0;t<r.length;t++)i=r[t],eT(n,qg(Jg,i)?"xn--"+sT(i):i);return Zg(n,".")},vT=fu,yT=oo,AT=Ra,RT=Nf,CT=cn,bT=CT.set,kT=CT.getterFor("URL"),NT=RT.URLSearchParams,DT=RT.getState,OT=dT.URL,wT=dT.TypeError,PT=dT.parseInt,LT=Math.floor,MT=Math.pow,xT=hT("".charAt),VT=hT(/./.exec),UT=hT([].join),FT=hT(1..toString),BT=hT([].pop),HT=hT([].push),jT=hT("".replace),GT=hT([].shift),WT=hT("".split),JT=hT("".slice),KT=hT("".toLowerCase),zT=hT([].unshift),YT="Invalid scheme",qT="Invalid host",QT="Invalid port",XT=/[a-z]/i,$T=/[\d+-.a-z]/i,ZT=/\d/,eE=/^0x/i,tE=/^[0-7]+$/,iE=/^\d+$/,nE=/^[\da-f]+$/i,rE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,oE=/[\0\t\n\r #/:<>?@[\\\]^|]/,sE=/^[\u0000-\u0020]+/,aE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,cE=/[\t\n\r]/g,lE=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)zT(t,e%256),e=LT(e/256);return UT(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+=FT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},dE={},uE=gT({},dE,{" ":1,'"':1,"<":1,">":1,"`":1}),hE=gT({},uE,{"#":1,"?":1,"{":1,"}":1}),pE=gT({},hE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),mE=function(e,t){var i=ST(e,0);return i>32&&i<127&&!fT(t,e)?e:encodeURIComponent(e)},_E={ftp:21,file:null,http:80,https:443,ws:80,wss:443},fE=function(e,t){var i;return 2==e.length&&VT(XT,xT(e,0))&&(":"==(i=xT(e,1))||!t&&"|"==i)},gE=function(e){var t;return e.length>1&&fE(JT(e,0,2))&&(2==e.length||"/"===(t=xT(e,2))||"\\"===t||"?"===t||"#"===t)},TE=function(e){return"."===e||"%2e"===KT(e)},EE={},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},OE={},wE={},PE={},LE={},ME={},xE={},VE={},UE={},FE={},BE=function(e,t,i){var n,r,o,s=vT(e);if(t){if(r=this.parse(s))throw wT(r);this.searchParams=null}else{if(void 0!==i&&(n=new BE(i,!0)),r=this.parse(s,null,n))throw wT(r);(o=DT(new NT)).bindURL(this),this.searchParams=o}};BE.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,l=t||EE,d=0,u="",h=!1,p=!1,m=!1;for(e=vT(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=jT(e,sE,""),e=jT(e,aE,"$1")),e=jT(e,cE,""),n=TT(e);d<=n.length;){switch(r=n[d],l){case EE:if(!r||!VT(XT,r)){if(t)return YT;l=IE;continue}u+=KT(r),l=SE;break;case SE:if(r&&(VT($T,r)||"+"==r||"-"==r||"."==r))u+=KT(r);else{if(":"!=r){if(t)return YT;u="",l=IE,d=0;continue}if(t&&(c.isSpecial()!=fT(_E,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&_E[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=wE:c.isSpecial()&&i&&i.scheme==c.scheme?l=vE:c.isSpecial()?l=CE:"/"==n[d+1]?(l=yE,d++):(c.cannotBeABaseURL=!0,HT(c.path,""),l=VE)}break;case IE:if(!i||i.cannotBeABaseURL&&"#"!=r)return YT;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=ET(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=FE;break}l="file"==i.scheme?wE:AE;continue;case vE:if("/"!=r||"/"!=n[d+1]){l=AE;continue}l=bE,d++;break;case yE:if("/"==r){l=kE;break}l=xE;continue;case AE:if(c.scheme=i.scheme,r==fg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())l=RE;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.path.length--,l=xE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}break;case RE:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=xE;continue}l=kE}else l=bE;break;case CE:if(l=bE,"/"!=r||"/"!=xT(u,d+1))continue;d++;break;case bE:if("/"!=r&&"\\"!=r){l=kE;continue}break;case kE:if("@"==r){h&&(u="%40"+u),h=!0,o=TT(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=mE(f,pE);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=TT(u).length+1,u="",l=NE}else u+=r;break;case NE:case DE:if(t&&"file"==c.scheme){l=LE;continue}if(":"!=r||p){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return qT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=ME,t)return;continue}"["==r?p=!0:"]"==r&&(p=!1),u+=r}else{if(""==u)return qT;if(s=c.parseHost(u))return s;if(u="",l=OE,t==DE)return}break;case OE:if(!VT(ZT,r)){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var T=PT(u,10);if(T>65535)return QT;c.port=c.isSpecial()&&T===_E[c.scheme]?null:T,u=""}if(t)return;l=ME;continue}return QT}u+=r;break;case wE:if(c.scheme="file","/"==r||"\\"==r)l=PE;else{if(!i||"file"!=i.scheme){l=xE;continue}if(r==fg)c.host=i.host,c.path=ET(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){gE(UT(ET(n,d),""))||(c.host=i.host,c.path=ET(i.path),c.shortenPath()),l=xE;continue}c.host=i.host,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}}break;case PE:if("/"==r||"\\"==r){l=LE;break}i&&"file"==i.scheme&&!gE(UT(ET(n,d),""))&&(fE(i.path[0],!0)?HT(c.path,i.path[0]):c.host=i.host),l=xE;continue;case LE:if(r==fg||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&fE(u))l=xE;else if(""==u){if(c.host="",t)return;l=ME}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=ME}continue}u+=r;break;case ME:if(c.isSpecial()){if(l=xE,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=fg&&(l=xE,"/"!=r))continue}else c.fragment="",l=FE;else c.query="",l=UE;break;case xE:if(r==fg||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=KT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,"")):TE(u)?"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,""):("file"==c.scheme&&!c.path.length&&fE(u)&&(c.host&&(c.host=""),u=xT(u,0)+":"),HT(c.path,u)),u="","file"==c.scheme&&(r==fg||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)GT(c.path);"?"==r?(c.query="",l=UE):"#"==r&&(c.fragment="",l=FE)}else u+=mE(r,hE);break;case VE:"?"==r?(c.query="",l=UE):"#"==r?(c.fragment="",l=FE):r!=fg&&(c.path[0]+=mE(r,dE));break;case UE:t||"#"!=r?r!=fg&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":mE(r,dE)):(c.fragment="",l=FE);break;case FE:r!=fg&&(c.fragment+=mE(r,uE))}d++}},parseHost:function(e){var t,i,n;if("["==xT(e,0)){if("]"!=xT(e,e.length-1))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return xT(e,u)};if(":"==h()){if(":"!=xT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&VT(nE,h());)t=16*t+PT(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++}if(!VT(ZT,h()))return;for(;VT(ZT,h());){if(o=PT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[l]=256*c[l]+r,2!=++n&&4!=n||l++}if(4!=n)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(JT(e,1,-1)),!t)return qT;this.host=t}else if(this.isSpecial()){if(e=IT(e),VT(rE,e))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=WT(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(o=10,r.length>1&&"0"==xT(r,0)&&(o=VT(eE,r)?16:8,r=JT(r,8==o?1:2)),""===r)s=0;else{if(!VT(10==o?iE:8==o?tE:nE,r))return e;s=PT(r,o)}HT(i,s)}for(n=0;n<t;n++)if(s=i[n],n==t-1){if(s>=MT(256,5-t))return null}else if(s>255)return null;for(a=BT(i),n=0;n<i.length;n++)a+=i[n]*MT(256,3-n);return a}(e),null===t)return qT;this.host=t}else{if(VT(oE,e))return qT;for(t="",i=TT(e),n=0;n<i.length;n++)t+=mE(i[n],dE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return fT(_E,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&fE(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==r?(l+="//",e.includesCredentials()&&(l+=i+(n?":"+n:"")+"@"),l+=lE(r),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+UT(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw wT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new HE(e.path[0]).origin}catch($U){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+lE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(vT(e)+":",EE)},getUsername:function(){return this.username},setUsername:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=mE(t[i],pE)}},getPassword:function(){return this.password},setPassword:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=mE(t[i],pE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?lE(e):lE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,NE)},getHostname:function(){var e=this.host;return null===e?"":lE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,DE)},getPort:function(){var e=this.port;return null===e?"":vT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=vT(e))?this.port=null:this.parse(e,OE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+UT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,ME))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=vT(e))?this.query=null:("?"==xT(e,0)&&(e=JT(e,1)),this.query="",this.parse(e,UE)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=vT(e))?("#"==xT(e,0)&&(e=JT(e,1)),this.fragment="",this.parse(e,FE)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var HE=function(e){var t=_T(this,jE),i=AT(arguments.length,1)>1?arguments[1]:void 0,n=bT(t,new BE(e,!1,i));cT||(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())},jE=HE.prototype,GE=function(e,t){return{get:function(){return kT(this)[e]()},set:t&&function(e){return kT(this)[t](e)},configurable:!0,enumerable:!0}};if(cT&&(mT(jE,"href",GE("serialize","setHref")),mT(jE,"origin",GE("getOrigin")),mT(jE,"protocol",GE("getProtocol","setProtocol")),mT(jE,"username",GE("getUsername","setUsername")),mT(jE,"password",GE("getPassword","setPassword")),mT(jE,"host",GE("getHost","setHost")),mT(jE,"hostname",GE("getHostname","setHostname")),mT(jE,"port",GE("getPort","setPort")),mT(jE,"pathname",GE("getPathname","setPathname")),mT(jE,"search",GE("getSearch","setSearch")),mT(jE,"searchParams",GE("getSearchParams")),mT(jE,"hash",GE("getHash","setHash"))),pT(jE,"toJSON",(function(){return kT(this).serialize()}),{enumerable:!0}),pT(jE,"toString",(function(){return kT(this).serialize()}),{enumerable:!0}),OT){var WE=OT.createObjectURL,JE=OT.revokeObjectURL;WE&&pT(HE,"createObjectURL",uT(WE,OT)),JE&&pT(HE,"revokeObjectURL",uT(JE,OT))}yT(HE,"URL"),aT({global:!0,constructor:!0,forced:!lT,sham:!cT},{URL:HE});var KE="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,zE=Lt,YE=Ht,qE=RangeError,QE=function(e){if(void 0===e)return 0;var t=zE(e),i=YE(t);if(t!==i)throw qE("Wrong length or index");return i},XE=Array,$E=Math.abs,ZE=Math.pow,eS=Math.floor,tS=Math.log,iS=Math.LN2,nS={pack:function(e,t,i){var n,r,o,s=XE(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?ZE(2,-24)-ZE(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=$E(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=eS(tS(e)/iS),e*(o=ZE(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*ZE(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*ZE(2,t),n+=l):(r=e*ZE(2,l-1)*ZE(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<<t|r,a+=t;a>0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<<r)-1,s=o>>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=ZE(2,t),d-=s}return(l?-1:1)*i*ZE(2,d-t)}},rS=B,oS=Ut,sS=Gt,aS=function(e){for(var t=rS(this),i=sS(t),n=arguments.length,r=oS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:oS(o,i);s>r;)t[r++]=e;return t},cS=C,lS=c,dS=ke,uS=KE,hS=Dn,pS=zi,mS=Is,_S=Xm,fS=i,gS=Ns,TS=Lt,ES=Ht,SS=QE,IS=nS,vS=Kr,yS=vo,AS=nr.f,RS=aS,CS=a_,bS=oo,kS=cn,NS=hS.PROPER,DS=hS.CONFIGURABLE,OS="ArrayBuffer",wS="DataView",PS="prototype",LS="Wrong index",MS=kS.getterFor(OS),xS=kS.getterFor(wS),VS=kS.set,US=cS[OS],FS=US,BS=FS&&FS[PS],HS=cS[wS],jS=HS&&HS[PS],GS=Object.prototype,WS=cS.Array,JS=cS.RangeError,KS=lS(RS),zS=lS([].reverse),YS=IS.pack,qS=IS.unpack,QS=function(e){return[255&e]},XS=function(e){return[255&e,e>>8&255]},$S=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},ZS=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},eI=function(e){return YS(e,23,4)},tI=function(e){return YS(e,52,8)},iI=function(e,t,i){mS(e[PS],t,{configurable:!0,get:function(){return i(this)[t]}})},nI=function(e,t,i,n){var r=SS(i),o=xS(e);if(r+t>o.byteLength)throw JS(LS);var s=o.bytes,a=r+o.byteOffset,c=CS(s,a,a+t);return n?c:zS(c)},rI=function(e,t,i,n,r,o){var s=SS(i),a=xS(e);if(s+t>a.byteLength)throw JS(LS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(uS){var oI=NS&&US.name!==OS;if(fS((function(){US(1)}))&&fS((function(){new US(-1)}))&&!fS((function(){return new US,new US(1.5),new US(NaN),1!=US.length||oI&&!DS})))oI&&DS&&pS(US,"name",OS);else{(FS=function(e){return gS(this,BS),new US(SS(e))})[PS]=BS;for(var sI,aI=AS(US),cI=0;aI.length>cI;)(sI=aI[cI++])in FS||pS(FS,sI,US[sI]);BS.constructor=FS}yS&&vS(jS)!==GS&&yS(jS,GS);var lI=new HS(new FS(2)),dI=lS(jS.setInt8);lI.setInt8(0,2147483648),lI.setInt8(1,2147483649),!lI.getInt8(0)&&lI.getInt8(1)||_S(jS,{setInt8:function(e,t){dI(this,e,t<<24>>24)},setUint8:function(e,t){dI(this,e,t<<24>>24)}},{unsafe:!0})}else BS=(FS=function(e){gS(this,BS);var t=SS(e);VS(this,{type:OS,bytes:KS(WS(t),0),byteLength:t}),dS||(this.byteLength=t,this.detached=!1)})[PS],jS=(HS=function(e,t,i){gS(this,jS),gS(e,BS);var n=MS(e),r=n.byteLength,o=TS(t);if(o<0||o>r)throw JS("Wrong offset");if(o+(i=void 0===i?r-o:ES(i))>r)throw JS("Wrong length");VS(this,{type:wS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),dS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[PS],dS&&(iI(FS,"byteLength",MS),iI(HS,"buffer",xS),iI(HS,"byteLength",xS),iI(HS,"byteOffset",xS)),_S(jS,{getInt8:function(e){return nI(this,1,e)[0]<<24>>24},getUint8:function(e){return nI(this,1,e)[0]},getInt16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return ZS(nI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return ZS(nI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return qS(nI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return qS(nI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){rI(this,1,e,QS,t)},setUint8:function(e,t){rI(this,1,e,QS,t)},setInt16:function(e,t){rI(this,2,e,XS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){rI(this,2,e,XS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){rI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){rI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){rI(this,4,e,eI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){rI(this,8,e,tI,t,arguments.length>2?arguments[2]:void 0)}});bS(FS,OS),bS(HS,wS);var uI={ArrayBuffer:FS,DataView:HS},hI=Vr,pI=Ta,mI=i,_I=Ce,fI=Ut,gI=Ht,TI=da,EI=uI.ArrayBuffer,SI=uI.DataView,II=SI.prototype,vI=pI(EI.prototype.slice),yI=pI(II.getUint8),AI=pI(II.setUint8);hI({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:mI((function(){return!new EI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(vI&&void 0===t)return vI(_I(this),e);for(var i=_I(this).byteLength,n=fI(e,i),r=fI(void 0===t?i:t,i),o=new(TI(this,EI))(gI(r-n)),s=new SI(this),a=new SI(o),c=0;n<r;)AI(a,c++,yI(s,n++));return o}});var RI,CI,bI,kI={},NI={get exports(){return kI},set exports(e){kI=e}},DI=KE,OI=ke,wI=C,PI=Ee,LI=ve,MI=G,xI=Vs,VI=Qe,UI=zi,FI=ir,BI=Is,HI=Ge,jI=Kr,GI=vo,WI=_e,JI=Y,KI=cn.enforce,zI=cn.get,YI=wI.Int8Array,qI=YI&&YI.prototype,QI=wI.Uint8ClampedArray,XI=QI&&QI.prototype,$I=YI&&jI(YI),ZI=qI&&jI(qI),ev=Object.prototype,tv=wI.TypeError,iv=WI("toStringTag"),nv=JI("TYPED_ARRAY_TAG"),rv="TypedArrayConstructor",ov=DI&&!!GI&&"Opera"!==xI(wI.opera),sv=!1,av={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},cv={BigInt64Array:8,BigUint64Array:8},lv=function(e){var t=jI(e);if(LI(t)){var i=zI(t);return i&&MI(i,rv)?i[rv]:lv(t)}},dv=function(e){if(!LI(e))return!1;var t=xI(e);return MI(av,t)||MI(cv,t)};for(RI in av)(bI=(CI=wI[RI])&&CI.prototype)?KI(bI)[rv]=CI:ov=!1;for(RI in cv)(bI=(CI=wI[RI])&&CI.prototype)&&(KI(bI)[rv]=CI);if((!ov||!PI($I)||$I===Function.prototype)&&($I=function(){throw tv("Incorrect invocation")},ov))for(RI in av)wI[RI]&&GI(wI[RI],$I);if((!ov||!ZI||ZI===ev)&&(ZI=$I.prototype,ov))for(RI in av)wI[RI]&&GI(wI[RI].prototype,ZI);if(ov&&jI(XI)!==ZI&&GI(XI,ZI),OI&&!MI(ZI,iv))for(RI in sv=!0,BI(ZI,iv,{configurable:!0,get:function(){return LI(this)?this[nv]:void 0}}),av)wI[RI]&&UI(wI[RI],nv,RI);var uv={NATIVE_ARRAY_BUFFER_VIEWS:ov,TYPED_ARRAY_TAG:sv&&nv,aTypedArray:function(e){if(dv(e))return e;throw tv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(PI(e)&&(!GI||HI($I,e)))return e;throw tv(VI(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,n){if(OI){if(i)for(var r in av){var o=wI[r];if(o&&MI(o.prototype,e))try{delete o.prototype[e]}catch($U){try{o.prototype[e]=t}catch(s){}}}ZI[e]&&!i||FI(ZI,e,i?t:ov&&qI[e]||t,n)}},exportTypedArrayStaticMethod:function(e,t,i){var n,r;if(OI){if(GI){if(i)for(n in av)if((r=wI[n])&&MI(r,e))try{delete r[e]}catch($U){}if($I[e]&&!i)return;try{return FI($I,e,i?t:ov&&$I[e]||t)}catch($U){}}for(n in av)!(r=wI[n])||r[e]&&!i||FI(r,e,t)}},getTypedArrayConstructor:lv,isView:function(e){if(!LI(e))return!1;var t=xI(e);return"DataView"===t||MI(av,t)||MI(cv,t)},isTypedArray:dv,TypedArray:$I,TypedArrayPrototype:ZI},hv=C,pv=i,mv=Dd,_v=uv.NATIVE_ARRAY_BUFFER_VIEWS,fv=hv.ArrayBuffer,gv=hv.Int8Array,Tv=!_v||!pv((function(){gv(1)}))||!pv((function(){new gv(-1)}))||!mv((function(e){new gv,new gv(null),new gv(1.5),new gv(e)}),!0)||pv((function(){return 1!==new gv(new fv(2),1,void 0).length})),Ev=ve,Sv=Math.floor,Iv=Number.isInteger||function(e){return!Ev(e)&&isFinite(e)&&Sv(e)===e},vv=Lt,yv=RangeError,Av=function(e){var t=vv(e);if(t<0)throw yv("The argument can't be less than 0");return t},Rv=RangeError,Cv=function(e,t){var i=Av(e);if(i%t)throw Rv("Wrong offset");return i},bv=Vs,kv=_t,Nv=TypeError,Dv=function(e){var t=kv(e,"number");if("number"==typeof t)throw Nv("Can't convert number to bigint");return BigInt(t)},Ov=va,wv=Fe,Pv=oa,Lv=B,Mv=Gt,xv=ad,Vv=ed,Uv=Yl,Fv=function(e){var t=bv(e);return"BigInt64Array"==t||"BigUint64Array"==t},Bv=uv.aTypedArrayConstructor,Hv=Dv,jv=Vr,Gv=C,Wv=Fe,Jv=ke,Kv=Tv,zv=uv,Yv=uI,qv=Ns,Qv=Wi,Xv=zi,$v=Iv,Zv=Ht,ey=QE,ty=Cv,iy=Tt,ny=G,ry=Vs,oy=ve,sy=Ye,ay=Di,cy=Ge,ly=vo,dy=nr.f,uy=function(e){var t,i,n,r,o,s,a,c,l=Pv(this),d=Lv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Vv(d);if(m&&!Uv(m))for(c=(a=xv(d,m)).next,d=[];!(s=wv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Ov(h,arguments[2])),i=Mv(d),n=new(Bv(l))(i),r=Fv(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?Hv(o):+o;return n},hy=rp.forEach,py=Cs,my=Is,_y=De,fy=ln,gy=lu,Ty=cn.get,Ey=cn.set,Sy=cn.enforce,Iy=_y.f,vy=fy.f,yy=Math.round,Ay=Gv.RangeError,Ry=Yv.ArrayBuffer,Cy=Ry.prototype,by=Yv.DataView,ky=zv.NATIVE_ARRAY_BUFFER_VIEWS,Ny=zv.TYPED_ARRAY_TAG,Dy=zv.TypedArray,Oy=zv.TypedArrayPrototype,wy=zv.aTypedArrayConstructor,Py=zv.isTypedArray,Ly="BYTES_PER_ELEMENT",My="Wrong length",xy=function(e,t){wy(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r},Vy=function(e,t){my(e,t,{configurable:!0,get:function(){return Ty(this)[t]}})},Uy=function(e){var t;return cy(Cy,e)||"ArrayBuffer"==(t=ry(e))||"SharedArrayBuffer"==t},Fy=function(e,t){return Py(e)&&!sy(t)&&t in e&&$v(+t)&&t>=0},By=function(e,t){return t=iy(t),Fy(e,t)?Qv(2,e[t]):vy(e,t)},Hy=function(e,t,i){return t=iy(t),!(Fy(e,t)&&oy(i)&&ny(i,"value"))||ny(i,"get")||ny(i,"set")||i.configurable||ny(i,"writable")&&!i.writable||ny(i,"enumerable")&&!i.enumerable?Iy(e,t,i):(e[t]=i.value,e)};Jv?(ky||(fy.f=By,_y.f=Hy,Vy(Oy,"buffer"),Vy(Oy,"byteOffset"),Vy(Oy,"byteLength"),Vy(Oy,"length")),jv({target:"Object",stat:!0,forced:!ky},{getOwnPropertyDescriptor:By,defineProperty:Hy}),NI.exports=function(e,t,i){var n=e.match(/\d+/)[0]/8,r=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=Gv[r],c=a,l=c&&c.prototype,d={},u=function(e,t){Iy(e,t,{get:function(){return function(e,t){var i=Ty(e);return i.view[o](t*n+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,r){var o=Ty(e);i&&(r=(r=yy(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0)}(this,t,e)},enumerable:!0})};ky?Kv&&(c=t((function(e,t,i,r){return qv(e,l),gy(oy(t)?Uy(t)?void 0!==r?new a(t,ty(i,n),r):void 0!==i?new a(t,ty(i,n)):new a(t):Py(t)?xy(c,t):Wv(uy,c,t):new a(ey(t)),e,c)})),ly&&ly(c,Dy),hy(dy(a),(function(e){e in c||Xv(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,r){qv(e,l);var o,s,a,d=0,h=0;if(oy(t)){if(!Uy(t))return Py(t)?xy(c,t):Wv(uy,c,t);o=t,h=ty(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw Ay(My);if((s=p-h)<0)throw Ay(My)}else if((s=Zv(r)*n)+h>p)throw Ay(My);a=s/n}else a=ey(t),o=new Ry(s=a*n);for(Ey(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new by(o)});d<a;)u(e,d++)})),ly&&ly(c,Dy),l=c.prototype=ay(Oy)),l.constructor!==c&&Xv(l,"constructor",c),Sy(l).TypedArrayConstructor=c,Ny&&Xv(l,Ny,r);var h=c!=a;d[r]=c,jv({global:!0,constructor:!0,forced:h,sham:!ky},d),Ly in c||Xv(c,Ly,n),Ly in l||Xv(l,Ly,n),py(r)}):NI.exports=function(){},kI("Uint8",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var jy=aS,Gy=Dv,Wy=Vs,Jy=Fe,Ky=i,zy=uv.aTypedArray,Yy=uv.exportTypedArrayMethod,qy=c("".slice);Yy("fill",(function(e){var t=arguments.length;zy(this);var i="Big"===qy(Wy(this),0,3)?Gy(e):+e;return Jy(jy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),Ky((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var Qy=C,Xy=Fe,$y=uv,Zy=Gt,eA=Cv,tA=B,iA=i,nA=Qy.RangeError,rA=Qy.Int8Array,oA=rA&&rA.prototype,sA=oA&&oA.set,aA=$y.aTypedArray,cA=$y.exportTypedArrayMethod,lA=!iA((function(){var e=new Uint8ClampedArray(2);return Xy(sA,e,{length:1,0:3},1),3!==e[1]})),dA=lA&&$y.NATIVE_ARRAY_BUFFER_VIEWS&&iA((function(){var e=new rA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));cA("set",(function(e){aA(this);var t=eA(arguments.length>1?arguments[1]:void 0,1),i=tA(e);if(lA)return Xy(sA,this,i,t);var n=this.length,r=Zy(i),o=0;if(r+t>n)throw nA("Wrong length");for(;o<r;)this[t+o]=i[o++]}),!lA||dA);var uA=q.match(/firefox\/(\d+)/i),hA=!!uA&&+uA[1],pA=/MSIE|Trident/.test(q),mA=q.match(/AppleWebKit\/(\d+)\./),_A=!!mA&&+mA[1],fA=Ta,gA=i,TA=et,EA=p_,SA=hA,IA=pA,vA=ie,yA=_A,AA=uv.aTypedArray,RA=uv.exportTypedArrayMethod,CA=C.Uint16Array,bA=CA&&fA(CA.prototype.sort),kA=!(!bA||gA((function(){bA(new CA(2),null)}))&&gA((function(){bA(new CA(2),{})}))),NA=!!bA&&!gA((function(){if(vA)return vA<74;if(SA)return SA<67;if(IA)return!0;if(yA)return yA<602;var e,t,i=new CA(516),n=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,n[e]=e-2*t+3;for(bA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==n[e])return!0}));RA("sort",(function(e){return void 0!==e&&TA(e),NA?bA(this,e):EA(AA(this),function(e){return function(t,i){return void 0!==e?+e(t,i)||0:i!=i?-1:t!=t?1:0===t&&0===i?1/t>0&&1/i<0?1:-1:t>i}}(e))}),!NA||kA);var DA=Vr,OA=kc,wA=i,PA=je,LA=Ee,MA=da,xA=iu,VA=ir,UA=OA&&OA.prototype;if(DA({target:"Promise",proto:!0,real:!0,forced:!!OA&&wA((function(){UA.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=MA(this,PA("Promise")),i=LA(e);return this.then(i?function(i){return xA(t,e()).then((function(){return i}))}:e,i?function(i){return xA(t,e()).then((function(){throw i}))}:e)}}),LA(OA)){var FA=PA("Promise").prototype.finally;UA.finally!==FA&&VA(UA,"finally",FA,{unsafe:!0})}var BA=Cs,HA="ArrayBuffer",jA=uI[HA];Vr({global:!0,constructor:!0,forced:C[HA]!==jA},{ArrayBuffer:jA}),BA(HA);var GA=Qe,WA=TypeError,JA=Vr,KA=c,zA=et,YA=B,qA=Gt,QA=function(e,t){if(!delete e[t])throw WA("Cannot delete property "+GA(t)+" of "+GA(e))},XA=fu,$A=i,ZA=p_,eR=sp,tR=hA,iR=pA,nR=ie,rR=_A,oR=[],sR=KA(oR.sort),aR=KA(oR.push),cR=$A((function(){oR.sort(void 0)})),lR=$A((function(){oR.sort(null)})),dR=eR("sort"),uR=!$A((function(){if(nR)return nR<70;if(!(tR&&tR>3)){if(iR)return!0;if(rR)return rR<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++)oR.push({k:t+n,v:i})}for(oR.sort((function(e,t){return t.v-e.v})),n=0;n<oR.length;n++)t=oR[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));JA({target:"Array",proto:!0,forced:cR||!lR||!dR||!uR},{sort:function(e){void 0!==e&&zA(e);var t=YA(this);if(uR)return void 0===e?sR(t):sR(t,e);var i,n,r=[],o=qA(t);for(n=0;n<o;n++)n in t&&aR(r,t[n]);for(ZA(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:XA(t)>XA(i)?1:-1}}(e)),i=qA(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)QA(t,n++);return t}});var hR=Vr,pR=Wh,mR=c([].reverse),_R=[1,2];hR({target:"Array",proto:!0,forced:String(_R)===String(_R.reverse())},{reverse:function(){return pR(this)&&(this.length=this.length),mR(this)}}),kI("Float32",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var fR=Vr,gR=Fe,TR=c,ER=I,SR=Ee,IR=T,vR=pu,yR=fu,AR=nt,RR=Au,CR=qp,bR=_e("replace"),kR=TypeError,NR=TR("".indexOf);TR("".replace);var DR=TR("".slice),OR=Math.max,wR=function(e,t,i){return i>e.length?-1:""===t?i:NR(e,t,i)};fR({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=ER(this),u=0,h=0,p="";if(!IR(e)){if(vR(e)&&(i=yR(ER(RR(e))),!~NR(i,"g")))throw kR("`.replaceAll` does not allow non-global regexes");if(n=AR(e,bR))return gR(n,e,d,t)}for(r=yR(d),o=yR(e),(s=SR(t))||(t=yR(t)),a=o.length,c=OR(1,a),u=wR(r,o,0);-1!==u;)l=s?yR(t(o,u,r)):CR(o,r,u,[],void 0,t),p+=DR(r,h,u)+l,h=u+a,u=wR(r,o,u+c);return h<r.length&&(p+=DR(r,h)),p}});let PR=!0,LR=!0;function MR(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function xR(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 VR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(PR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function UR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(LR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function FR(){if("object"==typeof window){if(PR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function BR(e,t){LR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function HR(e){return"[object Object]"===Object.prototype.toString.call(e)}function jR(e){return HR(e)?Object.keys(e).reduce((function(t,i){const n=HR(e[i]),r=n?jR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function GR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?GR(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{GR(e,e.get(t),i)}))})))}function WR(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&&GR(e,i,r)}))})),r}const JR=FR;function KR(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=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),JR("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return JR("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=>Promise.reject(o(e))))))}}}function zR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function YR(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 xR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qR(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 QR(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 Promise(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function XR(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=>WR(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}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>WR(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?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function $R(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=>{if(this.getSenders().find((t=>t.track===e)))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 ZR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return $R(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=>{if(this.getSenders().find((t=>t.track===e)))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");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.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 eC(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 tC(e,t){xR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var iC=Object.freeze({__proto__:null,shimMediaStream:zR,shimOnTrack:YR,shimGetSendersWithDtmf:qR,shimGetStats:QR,shimSenderReceiverGetStats:XR,shimAddTrackRemoveTrackWithNative:$R,shimAddTrackRemoveTrack:ZR,shimPeerConnection:eC,fixNegotiationNeeded:tC,shimGetUserMedia:KR,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"))}});function nC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){BR("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 rC(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 oC(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(oN){if("TypeError"!==oN.name)throw oN;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function sC(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):Promise.resolve(new Map)}}function aC(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}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function cC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){BR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function lC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function dC(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 uC(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 hC(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?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function pC(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?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var mC=Object.freeze({__proto__:null,shimOnTrack:rC,shimPeerConnection:oC,shimSenderGetStats:sC,shimReceiverGetStats:aC,shimRemoveStream:cC,shimRTCDataChannel:lC,shimAddTransceiver:dC,shimGetParameters:uC,shimCreateOffer:hC,shimCreateAnswer:pC,shimGetUserMedia:nC,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,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function _C(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){this._localStreams||(this._localStreams=[]),this._localStreams.includes(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,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(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=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function fC(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=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});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 gC(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),Promise.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),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function TC(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(EC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function EC(e){return e&&void 0!==e.video?Object.assign({},e,{video:jR(e.video)}):e}function SC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(BR("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function IC(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 vC(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 yC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var AC=Object.freeze({__proto__:null,shimLocalStreamsAPI:_C,shimRemoteStreamsAPI:fC,shimCallbacksAPI:gC,shimGetUserMedia:TC,shimConstraints:EC,shimRTCIceServerUrls:SC,shimTrackEventTransceiver:IC,shimCreateOfferLegacy:vC,shimAudioContext:yC}),RC={},CC={get exports(){return RC},set exports(e){RC=e}};!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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<n.length;r++)i=n[r].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const r=n[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const n=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=o.length?t.parseFmtp(o[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[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 d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),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 t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(CC);var bC=RC,kC=e({__proto__:null,default:bC},[RC]);function NC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=bC.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,xR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function DC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xR(e,"icecandidate",(e=>{if(e.candidate){const t=bC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function OC(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=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(function(e){if(!e||!e.sdp)return!1;const t=bC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=bC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=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}(arguments[0]),i=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}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=bC.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>r}),this._sctp=o}return i.apply(this,arguments)}}function wC(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},xR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function PC(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 LC(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"!==e.trim())).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 MC(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?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xC(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 VC=Object.freeze({__proto__:null,shimRTCIceCandidate:NC,shimRTCIceCandidateRelayProtocol:DC,shimMaxMessageSize:OC,shimSendThrowTypeError:wC,shimConnectionState:PC,removeExtmapAllowMixed:LC,shimAddIceCandidateNullOrEmpty:MC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=FR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=MR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=MR(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=MR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:VC,extractVersion:MR,disableLog:VR,disableWarnings:UR,sdp:kC};switch(n.browser){case"chrome":if(!iC||!eC||!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=iC,MC(e,n),xC(e),KR(e,n),zR(e),eC(e,n),YR(e),ZR(e,n),qR(e),QR(e),XR(e),tC(e,n),NC(e),DC(e),PC(e),OC(e,n),wC(e),LC(e,n);break;case"firefox":if(!mC||!oC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=mC,MC(e,n),xC(e),nC(e,n),oC(e,n),rC(e),cC(e),sC(e),aC(e),lC(e),dC(e),uC(e),hC(e),pC(e),NC(e),PC(e),OC(e,n),wC(e);break;case"safari":if(!AC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=AC,MC(e,n),xC(e),SC(e),vC(e),gC(e),_C(e),fC(e),IC(e),TC(e),yC(e),NC(e),DC(e),OC(e,n),wC(e),LC(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var UC,FC=Object.create,BC=Object.defineProperty,HC=Object.defineProperties,jC=Object.getOwnPropertyDescriptor,GC=Object.getOwnPropertyDescriptors,WC=Object.getOwnPropertyNames,JC=Object.getOwnPropertySymbols,KC=Object.getPrototypeOf,zC=Object.prototype.hasOwnProperty,YC=Object.prototype.propertyIsEnumerable,qC=Reflect.get,QC=Math.pow,XC=(e,t,i)=>t in e?BC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,$C=(e,t)=>{for(var i in t||(t={}))zC.call(t,i)&&XC(e,i,t[i]);if(JC)for(var i of JC(t))YC.call(t,i)&&XC(e,i,t[i]);return e},ZC=(e,t)=>HC(e,GC(t)),eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tb=(e,t)=>{for(var i in t)BC(e,i,{get:t[i],enumerable:!0})},ib=(e,t,i)=>(i=null!=e?FC(KC(e)):{},((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of WC(t))!zC.call(e,r)&&r!==i&&BC(e,r,{get:()=>t[r],enumerable:!(n=jC(t,r))||n.enumerable});return e})(!t&&e&&e.__esModule?i:BC(i,"default",{value:e,enumerable:!0}),e)),nb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?jC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&BC(t,i,o),o},rb=(e,t,i)=>(XC(e,"symbol"!=typeof t?t+"":t,i),i),ob=(e,t,i)=>qC(KC(e),i,t),sb=(e,t,i)=>new Promise(((n,r)=>{var o=e=>{try{a(i.next(e))}catch(t){r(t)}},s=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),ab=eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,r,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},c.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,o),!0;case 6:return d.fn.call(d.context,t,i,r,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,r);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||r&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),cb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),lb=eb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))})(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=cb(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,s,r)}})),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}})),db=eb(((e,t)=>{var i=cb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?n.push(i[t.name][s]):n.push(i[t.names[o]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,r=t.innerOrder||a,c=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ub=eb((e=>{var t=lb(),i=db();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),hb=ib(ab()),pb=((UC=pb||{})[UC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",UC[UC.INVALID_OPERATION=4097]="INVALID_OPERATION",UC[UC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",UC[UC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",UC[UC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",UC[UC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",UC[UC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",UC[UC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",UC[UC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",UC[UC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",UC[UC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",UC[UC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",UC[UC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",UC[UC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",UC[UC.CLIENT_BANNED=16448]="CLIENT_BANNED",UC[UC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",UC[UC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",UC[UC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",UC[UC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",UC[UC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",UC[UC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",UC[UC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",UC[UC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",UC[UC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",UC[UC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",UC[UC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",UC[UC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",UC[UC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",UC[UC.UNKNOWN=65535]="UNKNOWN",UC),mb=pb,_b=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:n=mb.UNKNOWN,extraCode:r=0,constraint:o}=e,s="<".concat(function(e){for(let t in mb)if(mb[t]===e)return t;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),rb(this,"code"),rb(this,"extraCode"),rb(this,"message"),rb(this,"originMessage"),rb(this,"name"),rb(this,"constraint"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},fb=_b,gb=((new Date).getTime(),0),Tb=function(){return(new Date).getTime()+gb},Eb=function(){let e=new Date;return e.setTime(Tb()),e.toLocaleString()},Sb={};tb(Sb,{bytes2ms:()=>qD,convertObjectNumberToInt:()=>HO,copyProperties:()=>YD,deepClone:()=>NO,deepMerge:()=>kO,env:()=>Ib,fibonacci:()=>iO,formatedTime:()=>PO,getConstructorName:()=>fO,getContainerFromElement:()=>OO,getEnv:()=>VD,getInternalVersion:()=>IO,getLoggerUrl:()=>FD,getMuteStateFromFlag:()=>AO,getNetworkQuality:()=>RO,getNetworkType:()=>GD,getNumNetworkType:()=>KD,getOSType:()=>HD,getReconnectionTimeout:()=>nO,getStringByteLength:()=>xO,getSysInfo:()=>zD,getTerminalType:()=>BD,getTurnServer:()=>CO,getUint32Version:()=>BO,getValueType:()=>rO,getViewListFromView:()=>DO,glog:()=>ZD,ipv4ToUint32:()=>bO,isArray:()=>uO,isAudioWorkletSupported:()=>gO,isBoolean:()=>lO,isConstructor:()=>_O,isEmpty:()=>yO,isFunction:()=>oO,isLangChinese:()=>eO,isMediaStreamTrack:()=>hO,isNumber:()=>cO,isObject:()=>dO,isOverseaSdkAppId:()=>UD,isPlainObject:()=>tO,isPortrait:()=>UO,isPromise:()=>mO,isRemoteTrack:()=>pO,isString:()=>aO,isUndefined:()=>sO,loadImage:()=>FO,logVisibilityState:()=>VO,ms2bytes:()=>XD,ms2samples:()=>$D,performanceNow:()=>EO,promiseAny:()=>TO,samples2ms:()=>QD,setNetworkType:()=>JD,stringify:()=>LO,stringifyIncludeValue:()=>MO});var Ib={};tb(Ib,{ANDROID_VERSION:()=>Lb,CHROME_MAJOR_VERSION:()=>Mk,CHROME_VERSION:()=>xk,EDGE_VERSION:()=>Hb,EDG_MAJOR_VERSION:()=>Wb,EDG_VERSION:()=>Gb,FIREFOX_MAJOR_VERSION:()=>Fb,FIREFOX_VERSION:()=>Ub,HUAWEI_VERSION:()=>Ak,IE_VERSION:()=>tk,IOS_MAIN_VERSION:()=>jk,IOS_VERSION:()=>Hk,IPADQQB_VERSION:()=>hk,IS_ANDROID:()=>Pb,IS_ANDROID_WEBVIEW:()=>Bk,IS_ANY_SAFARI:()=>Uk,IS_CHROME:()=>Pk,IS_CHROME_OS:()=>fk,IS_CHROMIUM_BASE:()=>wk,IS_EDG:()=>jb,IS_EDGE:()=>Bb,IS_ELECTRON:()=>Ek,IS_FIREFOX:()=>Vb,IS_HEADLESS_CHROME:()=>Lk,IS_HUAWEI:()=>yk,IS_HUAWEIBROWSER:()=>vk,IS_IE:()=>ek,IS_IE8:()=>Zb,IS_IOS:()=>wb,IS_IOS_13_OR_14:()=>Jk,IS_IOS_15_1:()=>Wk,IS_IPAD:()=>kb,IS_IPADQQB:()=>uk,IS_IPAD_PRO:()=>Nb,IS_IPHONE:()=>Db,IS_IPOD:()=>Ob,IS_LINUX:()=>_k,IS_LOCAL:()=>Kk,IS_MAC:()=>mk,IS_MACQQB:()=>lk,IS_MIBROWSER:()=>Sk,IS_MQQB:()=>ok,IS_NATIVE_ANDROID:()=>xb,IS_OLD_ANDROID:()=>Mb,IS_OPPOBROWSER:()=>bk,IS_SAFARI:()=>Vk,IS_SAFARI_15_1:()=>Gk,IS_SAMSUNGBROWSER:()=>Rk,IS_SOGOU:()=>zb,IS_SOGOUM:()=>Jb,IS_TBS:()=>qb,IS_UCBROWSER:()=>Tk,IS_VIVOBROWSER:()=>Nk,IS_WECHAT:()=>ik,IS_WIN:()=>pk,IS_WQQB:()=>ak,IS_WX:()=>gk,IS_X5MQQB:()=>rk,IS_XWEB:()=>Xb,MACQQB_VERSION:()=>dk,MI_VERSION:()=>Ik,MQQB_VERSION:()=>sk,OPPO_VERSION:()=>kk,SAFARI_VERSION:()=>Fk,SAMSUNG_VERSION:()=>Ck,SOGOUM_VERSION:()=>Kb,SOGOU_VERSION:()=>Yb,TBS_VERSION:()=>Qb,USER_AGENT:()=>vb,VIVO_VERSION:()=>Dk,WECHAT_VERSION:()=>nk,WQQB_VERSION:()=>ck,XWEB_VERSION:()=>$b,browserInfo:()=>Yk,getBrowserInfo:()=>qk,getChromeMajorVersion:()=>Ok,getOSName:()=>Zk,getOSString:()=>eN,getUserAgentData:()=>Xk,isLocalStorageEnabled:()=>zk});var vb="undefined"==typeof navigator?"":navigator.userAgent,yb=e=>new RegExp(e,"i").test(vb),Ab=e=>{if(yb(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=vb.match(t);if(i&&i[1])return i[1]}return""},Rb=e=>{if(yb(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=vb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},Cb=/AppleWebKit\/([\d.]+)/i.exec(vb),bb=Cb?parseFloat(Cb[1]):NaN,kb=yb("iPad"),Nb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&yb("Macintosh"),Db=yb("iPhone")&&!kb,Ob=yb("iPod"),wb=Db||kb||Ob||Nb,Pb=yb("Android"),Lb=function(){if(Pb){let e=vb.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),Mb=Pb&&yb("webkit")&&Lb<2.3,xb=Pb&&Lb<5&&bb<537,Vb=yb("Firefox"),Ub=Ab("Firefox"),Fb=Rb("Firefox"),Bb=yb("Edge"),Hb=Ab("Edge"),jb=yb("Edg"),Gb=Ab("Edg"),Wb=Rb("Edg"),Jb=yb("SogouMobileBrowser"),Kb=Ab("SogouMobileBrowser"),zb=yb("MetaSr\\s"),Yb=Ab("MetaSr\\s"),qb=yb("TBS"),Qb=Ab("TBS"),Xb=yb("XWEB"),$b=Ab("XWEB"),Zb=yb("MSIE\\s8\\.0"),ek=yb("MSIE\\/\\d+"),tk=function(){if(ek){let e=/MSIE\s(\d+)\.\d/.exec(vb),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(vb)&&/rv:11.0/.test(vb)&&(t=11),t}return NaN}(),ik=yb("(micromessenger|webbrowser)"),nk=Ab("MicroMessenger"),rk=!qb&&yb("MQQBrowser")&&yb("COVC"),ok=!qb&&yb("MQQBrowser")&&!yb("COVC"),sk=ok||rk?Ab("MQQBrowser"):"",ak=!qb&&yb(" QQBrowser"),ck=Ab(" QQBrowser"),lk=!qb&&yb("QQBrowserLite"),dk=Ab("QQBrowserLite"),uk=!qb&&yb("MQBHD"),hk=Ab("MQBHD"),pk=yb("Windows"),mk=!wb&&yb("MAC OS X"),_k=!Pb&&yb("Linux"),fk=yb("CrOS"),gk=yb("MicroMessenger"),Tk=yb("UCBrowser"),Ek=yb("Electron"),Sk=yb("MiuiBrowser"),Ik=Ab("MiuiBrowser"),vk=yb("HuaweiBrowser"),yk=yb("Huawei"),Ak=Ab("HuaweiBrowser"),Rk=yb("SamsungBrowser"),Ck=Ab("SamsungBrowser"),bk=yb("HeyTapBrowser"),kk=Ab("HeyTapBrowser"),Nk=yb("VivoBrowser"),Dk=Ab("VivoBrowser"),Ok=()=>Rb("Chrome"),wk=yb("Chrome"),Pk=!Bb&&!zb&&!Jb&&!qb&&!Xb&&!jb&&!ak&&!Sk&&!vk&&!Rk&&!bk&&!Nk&&wk,Lk=yb("HeadlessChrome"),Mk=Ok(),xk=Ab("Chrome"),Vk=!wk&&!ok&&!rk&&!lk&&!uk&&yb("Safari"),Uk=Vk||wb,Fk=Ab("Version"),Bk=/Android.*(wv|.0.0.0)/.test(vb),Hk=(()=>{if(Nb)return Fk;if(wb){let e=vb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),jk=Number(Hk.split(".")[0]),Gk="15.1"===Fk,Wk="15.1"===Hk,Jk=(()=>{let e=Number(Hk.split(".")[0]);return 14===e||13===e})(),Kk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),zk=(()=>{let e;return()=>{if(sO(e))try{e=!!window.localStorage}catch(UP){e=!1}return e}})(),Yk=qk();function qk(){let e=new Map([[Vb,["Firefox",Ub]],[jb,["Edg",Gb]],[Pk,["Chrome",xk]],[Vk,["Safari",Fk]],[qb,["TBS",Qb]],[Xb,["XWEB",$b]],[ik&&Db,["WeChat",nk]],[ak,["QQ(Win)",ck]],[ok,["QQ(Mobile)",sk]],[rk,["QQ(Mobile X5)",sk]],[lk,["QQ(Mac)",dk]],[uk,["QQ(iPad)",hk]],[Sk,["MI",Ik]],[vk,["HW",Ak]],[Rk,["Samsung",Ck]],[bk,["OPPO",kk]],[Nk,["VIVO",Dk]],[Bb,["EDGE",Hb]],[Jb,["SogouMobile",Kb]],[zb,["Sogou",Yb]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Qk=null;function Xk(){return sb(this,null,(function*(){if(Qk)return Qk;if(!navigator.userAgentData||!oO(navigator.userAgentData.getHighEntropyValues))return null;try{return Qk=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(WU){return null}}))}var $k=new Map([[Pb,"Android"],[wb,"iOS"],[pk,"Windows"],[mk,"MacOS"],[_k,"Linux"],[fk,"ChromeOS"]]),Zk=function(){return $k.get(!0)?$k.get(!0):Qk?Qk.platform:"unknown"},eN=()=>{let e=Zk();return e+="/".concat(Yk.name,"/").concat(Vk?Yk.version:Yk.version.split(".")[0]),null!=Qk&&Qk.platformVersion&&(e+="/".concat(Qk.platformVersion)),null!=Qk&&Qk.architecture&&(e+="/".concat(Qk.architecture)),e},tN={};tb(tN,{AUDIO_MUTE_BIT:()=>HN,AUDIO_STAT_BIT:()=>BN,AUX_STAT_BIT:()=>FN,AUX_STREAM_MSID:()=>WN,BACKEND_ENV:()=>MN,BASE_DOC_URL:()=>gN,BASE_HOST:()=>pN,CAPABILITIES_KEYS:()=>MD,CLASS_NAME:()=>vD,CLOUD_CONSOLE_URL:()=>fN,DATA_FREEZE_TIMING:()=>_D,DOC_URL:()=>TN,DTLS_STATE_UNKNOWN:()=>eD,ENV_NAME:()=>yN,EXCHANGE_SDP_TIMEOUT:()=>dD,INTERVAL:()=>PD,IS_WORKER:()=>cN,IS_WORKLET:()=>lN,KIBANA_EVENT:()=>aD,LOCAL_STREAM_PUBLISH_STATE:()=>mD,LOGGER_CMD_TYPE:()=>vN,LOGGER_DOMAIN:()=>EN,LOGGER_DOMAIN_OVERSEA:()=>SN,LOG_LEVEL:()=>AN,LOG_LEVEL_NAME:()=>bD,MAIN_STREAM_MSID:()=>GN,MICROPHONE_COMMUNICATIONS:()=>CD,MICROPHONE_DEFAULT:()=>AD,NAME:()=>PN,NETWORK_TYPE:()=>bN,NOT_SUPPORTED_H264:()=>pD,PAUSED_RETRY_COUNT:()=>yD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>ED,PEER_CONNECTION_STATE:()=>tD,PEER_LEAVE_REASON:()=>kD,RAF:()=>wD,RECOVER_CAPTURE_INTERVAL:()=>DD,REMOTE_STREAM_TYPE_AUX:()=>KN,REMOTE_STREAM_TYPE_MAIN:()=>JN,RENDER_FREEZE_TIMING:()=>fD,RIC:()=>OD,SCHEDULE_DOMAIN:()=>SD,SCHEDULE_TIMEOUT:()=>ID,SDP_SEMANTICS_PLAN_B:()=>hD,SDP_SEMANTICS_UNIFIED_PLAN:()=>uD,SECOND_HOST:()=>mN,SIGNAL_PING_PONG_INTERVAL:()=>CN,SIGNAL_PING_TIMEOUT:()=>RN,SIGNAL_RECONNECTION_COUNT:()=>sD,SMALL_STAT_BIT:()=>UN,SPEAKER_DEFAULT:()=>RD,STORAGE_EXPIRES_TIME:()=>kN,STREAM_TYPE_BIG:()=>gD,STREAM_TYPE_SMALL:()=>TD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ND,SYNC_USER_LIST_INTERVAL:()=>cD,Scene:()=>xN,Switch:()=>NN,THIRD_HOST:()=>_N,TIMEOUT:()=>LD,TRANSPORT_DIRECTION:()=>LN,TRTC_ERROR_ASSISTANCE:()=>IN,TRTC_QUALITY_BAD:()=>XN,TRTC_QUALITY_DISCONNECTED:()=>ZN,TRTC_QUALITY_EXCELLENT:()=>YN,TRTC_QUALITY_GOOD:()=>qN,TRTC_QUALITY_POOR:()=>QN,TRTC_QUALITY_UNKNOWN:()=>zN,TRTC_QUALITY_VERY_BAD:()=>$N,UPDATE_OFFER_TIMEOUT:()=>lD,VIDEO_MUTE_BIT:()=>jN,VIDEO_STAT_BIT:()=>VN,audioProfileMap:()=>DN,getRetryCount:()=>rD,getScriptDir:()=>dN,innerVersion:()=>iN,loggerProxy:()=>uN,screenProfileMap:()=>wN,setLoggerProxy:()=>hN,setRetryCount:()=>nD,setVersion:()=>rN,version:()=>nN,videoProfileMap:()=>ON});var iN="4.15.00.1600",nN="5.0.0";function rN(e){nN=e;let[t,i,n]=e.split(".").map((e=>parseInt(e,10)));iN="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,n),".").concat(i.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var oN,sN,aN,cN="undefined"!=typeof importScripts,lN="undefined"!=typeof registerProcessor,dN=()=>{let e=cN?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},uN="",hN=e=>uN=e,pN="web.sdk.qcloud.com",mN="web.sdk.tencent.cn",_N="web.sdk.cloud.tencent.cn",fN="https://console.cloud.tencent.com/trtc",gN="https://".concat(pN,"/trtc/webrtc/v5/doc"),TN="".concat(gN,"/zh-cn/"),EN="https://yun.tim.qq.com",SN="https://apisgp.my-imcloud.com",IN="trtc_error_assistance",vN={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},yN={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},AN=((aN=AN||{})[aN.TRACE=0]="TRACE",aN[aN.DEBUG=1]="DEBUG",aN[aN.INFO=2]="INFO",aN[aN.WARN=3]="WARN",aN[aN.ERROR=4]="ERROR",aN[aN.NONE=5]="NONE",aN),RN=18e3,CN=2e3,bN={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},kN=6048e5,NN=((sN=NN||{}).USEAINS="useAINS",sN.ENABLEDEBUG="enableDebug",sN.USEV2="useV2",sN.USEWT="useWt",sN),DN={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},ON={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},wN={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},PN={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},LN={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},MN={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xN=((oN=xN||{}).LIVE="live",oN.RTC="rtc",oN),VN=1,UN=2,FN=4,BN=8,HN=64,jN=16,GN="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",WN="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",JN=PN.MAIN,KN=PN.AUXILIARY,zN=0,YN=1,qN=2,QN=3,XN=4,$N=5,ZN=6,eD="unknown",tD={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},iD=1/0;function nD(e){iD=e}function rD(){return iD}var oD,sD=30,aD={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},cD=1e4,lD=1e4,dD=1e4,uD="unified-plan",hD="plan-b",pD=1028,mD=((oD=mD||{})[oD.UNPUBLISH=-1]="UNPUBLISH",oD[oD.PUBLISHING=0]="PUBLISHING",oD[oD.PUBLISHED=1]="PUBLISHED",oD),_D=500,fD=1e3,gD=PN.BIG,TD=PN.SMALL,ED=1e4,SD={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},ID=2e3,vD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},yD=5,AD="default",RD=AD,CD="communications",bD=Object.keys(AN),kD=["normal leave","timeout leave","kick","role change"],ND=10,DD=2e3,OD="ric",wD="raf",PD="interval",LD="timeout",MD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],xD=1e8,VD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},UD=e=>Number(e)<14e8,FD=function(e,t){let i;i=uN||(UD(e)?SN:EN);let n=Math.floor(Math.random()*QC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function BD(){return Pb?4:Db?2:kb?3:mk?12:pk?5:_k?13:1}function HD(){return Pb?"Android":Db?"iPhone":kb?"iPad":mk?"Mac":pk?"Windows":_k?"Linux":"unknown"}var jD="unknown";function GD(){if("unknown"!==jD)return jD;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===r&&(r="2g"),n&&(jD=WD(n,r)),jD}function WD(e,t){if(bN[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function JD(e){jD=WD(e)}function KD(){return bN[GD()]}var zD=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:BD(),uint32_device_type:0,str_os_verion:HD(),uint32_link_type:1,str_client_version:iN,uint32_net_type:bN[GD()],ua:navigator.userAgent,version:""}}}};function YD(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,n)}return e}function qD(e){return QD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function QD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function XD(e){return 4*$D(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function $D(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var ZD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},eO=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},tO=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function iO(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:iO(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function nO(e){return e>8?3e4:1e3*iO(e)}function rO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var oO=e=>"function"==typeof e,sO=e=>void 0===e,aO=e=>"string"==typeof e,cO=e=>"number"==typeof e,lO=e=>"boolean"==typeof e,dO=e=>"object"===rO(e),uO=e=>"array"===rO(e),hO=e=>rO(e)==="MediaStreamTrack".toLowerCase(),pO=e=>e.isRemote,mO=e=>"promise"===rO(e),_O=e=>oO(e)&&e.prototype.constructor===e,fO=e=>_O(e)?e.prototype.constructor.name:"",gO="undefined"!=typeof AudioWorkletNode;function TO(e){return new Promise(((t,i)=>{let n=[];e.forEach((r=>{r.then(t).catch((t=>{n.push(t),n.length===e.length&&i(n)}))}))}))}function EO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var SO=e=>+e<10?"0".concat(e):e,IO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),n=SO(i[1])+SO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(n)},vO=Object.prototype.hasOwnProperty;function yO(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(tO(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(vO.call(e,t))return!1;return!0}return!1}function AO(e,t){return{userId:t,hasAudio:!!(e&BN),hasVideo:!!(e&VN),hasAuxiliary:!!(e&FN),hasSmall:!!(e&UN),audioMuted:!!(e&HN),videoMuted:!!(e&jN),audioAvailable:!(!(e&BN)||e&HN),videoAvailable:!(!(e&VN)||e&jN)}}function RO(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}function CO(e){let t={urls:"turn:".concat(e.url)};return!sO(e.username)&&!sO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",sO(e.credentialType)||(t.credentialType=e.credentialType)),t}function bO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!aO(e))return 0;let i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var kO=function(e,t,i,n){if(!dO(e)||!dO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(r=s[a],!(sO(t[r])||i&&i.includes(r)))if(dO(e[r])&&dO(t[r]))o+=kO(e[r],t[r],i,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=NO(t[r]),o+=1)}return o};function NO(e){if(uO(e)){let t=[];return e.forEach(((e,i)=>{t[i]=NO(e)})),t}if(dO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=NO(e[i])})),t}return e}var DO=e=>{let t=[];if(uO(e))t=[...e];else if(aO(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},OO=e=>aO(e)?document.getElementById(e):e,wO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),PO=()=>wO.format(new Date);function LO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(uO(e))return"[".concat(e.map((e=>LO(e,{keysToInclude:i,keysToExclude:n}))).join(","),"]");if(!tO(e)||!uO(i)&&!uO(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach((s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=tO(e[s])||uO(e[s])?JSON.parse(LO(e[s],{keysToExclude:n,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(oD){return"{}"}}function MO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((n=>{t===e[n]&&i.push(n)})),LO(e,{keysToInclude:i})}function xO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var VO=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&QO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{QO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),UO=()=>{var e,t,i,n;return null!=(e=window.screen)&&e.orientation?!(null==(n=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)||!n.includes("portrait")):0===window.orientation||180===window.orientation},FO=e=>sb(void 0,null,(function*(){return new Promise(((t,i)=>{let n;if(aO(e))n=new Image,n.crossOrigin="anonymous",n.src=e;else if(n=e,n.complete)return void t(n);n.onload=()=>t(n),n.onerror=i}))})),BO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},HO=e=>(Object.keys(e).forEach((t=>{cO(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(tO(e[t])||uO(e[t]))&&HO(e[t])})),e);function jO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=r||5e3,o.open(n||"POST",t,!0),o.send(i)}))}function GO(e){return sb(this,null,(function*(){let t=EO(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let e=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),n=yield(yield(yield new Response(e)).blob()).arrayBuffer();return QO.debug("compressJSON ".concat(i.length," -> ").concat(n.byteLength," ").concat(EO()-t,"ms")),n}catch(oD){return i}}))}var WO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>sb(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},s=()=>{2!==m&&h<(oO(d)?d():d)?(h++,m=1,oO(r)&&r.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),oO(u)?u(h):u)):(t(),oO(o)&&o.call(this,f))};oO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},JO=class{constructor(e){rb(this,"userId"),rb(this,"remoteUserId"),rb(this,"id"),rb(this,"sdkAppId"),rb(this,"type"),rb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!lO(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),QO.log(e,t,sO(this.userId)||yO(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}},KO=new(ib(ab(),1).default),zO=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e))(zO||{}),YO=zO,qO=!(wb||Pb||Lk),QO=new class{constructor(){this._isEnableUploadLog=!0,this._localJoinedUser=new Map,this._queue=[],this._timeoutId=-1,this._logLevel=1,this._logLevelToUpload=2,!cN&&!lN&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){KO.on(YO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&AN[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),KO.on(YO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),KO.once(YO.JOIN_FAILED,(()=>{this.startUpload()})),KO.on(YO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]})}));else if(aO(i.userId)&&cO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return sb(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:n,logs:r}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Eb(),sdkAppId:String(n),userId:i,version:nN,log:r.map((e=>e.log)).join("\n")}),n),r.forEach((e=>e.uploaded=!0))}}catch(sN){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return WO({retryFunction:()=>jO({url:FD(t,vN.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(Tb());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(AN[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){sO(AN[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(aO(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(oN){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:n,sdkAppId:r,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=AN[e])?void 0:o.toLowerCase())||"info";qO?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[s](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new JO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;AN[t]&&(this._logLevelToUpload=t)}},XO=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},$O=new class{constructor(){rb(this,"_prefix","TRTC"),rb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){zk()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(zk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(UP){QO.warn(UP)}}getItem(e){if(!zk())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(oN){QO.warn(oN)}}setItem(e,t){if(zk())try{let i={expiresIn:Date.now()+kN,value:t};this._queue.set(this.getRealKey(e),i)}catch(oD){QO.warn(oD)}}deleteItem(e){if(!zk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(oN){return QO.warn(oN),!1}}clear(){if(zk())try{localStorage.clear()}catch(UP){QO.warn(UP)}}},ZO={};tb(ZO,{HTTPS_API:()=>Ew,IS_GET_CAPABILITIES_SUPPORTED:()=>xw,IS_GET_SETTINGS_SUPPORTED:()=>Mw,IS_SEI_SUPPORTED:()=>Vw,IS_SPC_SUPPORTED:()=>Ow,basis:()=>jw,checkSystemRequirementsInternal:()=>fw,decodeSupportStatus:()=>_w,encodeSupportStatus:()=>mw,getBrowserInfo:()=>aw,getDisplayResolution:()=>Iw,isAddTransceiverSupported:()=>Dw,isBrowserSupported:()=>cw,isGetReceiversSupported:()=>bw,isGetSendersSupported:()=>kw,isGetTransceiversSupported:()=>Nw,isGetUserMediaSupported:()=>vw,isMediaDevicesSupported:()=>dw,isMediaSessionSupported:()=>Bw,isMediaStreamTrackProcessorSupported:()=>pw,isReplaceTrackSupported:()=>Pw,isScreenCaptureApiAvailable:()=>Tw,isSelectedCandidatePair:()=>Sw,isSetParametersSupported:()=>Lw,isSmallStreamAPISupported:()=>Aw,isSmallStreamSupported:()=>Rw,isStopTransceiverSupported:()=>ww,isTRTCSupported:()=>gw,isUnifiedPlanDefault:()=>Cw,isUsedInHttpProtocol:()=>hw,isWebAudioSupported:()=>yw,isWebCodecSupported:()=>Fw,isWebCodecsSupported:()=>lw,isWebRTCSupported:()=>Uw,isWebTransportSupported:()=>Hw});var ew={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},tw={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(rO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(rO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:n}=e;return"failed to subscribe ".concat(i," ").concat(n," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:n,maxSizeInSecond:r}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(r," bytes"):n," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},iw=(e,t)=>t?"".concat(gN,"/").concat(e,"/").concat(t):"".concat(gN,"/").concat(e,"/index.html"),nw=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(IN);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n}}return{}};function rw(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o="",s="",a="";oO(tw[t])?o=tw[t](i):aO(tw[t])&&(o=tw[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=nw();n?a="".concat(n.className,".html#").concat(n.fnName):l&&l[t]&&(oO(l[t])?a=l[t](i):aO(l[t])&&(a=l[t]));let d=o;return eO()&&(c&&c[t]&&(oO(c[t])?s=c[t](i):aO(c[t])&&(s=c[t])),s&&(d=r?"".concat(s,"\n请查看文档: ").concat(iw("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),r&&(d+=" \nRefer to: ".concat(iw("en",a),"\n")),d}var ow={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},sw=new Map([[Vb,["Firefox",Ub]],[jb,["Edg",Gb]],[Pk,["Chrome",xk]],[Vk,["Safari",Fk]],[qb,["TBS",Qb]],[Xb,["XWEB",$b]],[ik&&Db,["WeChat",nk]],[ak,["QQ(Win)",ck]],[ok,["QQ(Mobile)",sk]],[rk,["QQ(Mobile X5)",sk]],[lk,["QQ(Mac)",dk]],[uk,["QQ(iPad)",hk]],[Sk,["MI",Ik]],[vk,["HW",Ak]],[Rk,["Samsung",Ck]],[bk,["OPPO",kk]],[Nk,["VIVO",Dk]],[Bb,["EDGE",Hb]],[Jb,["SogouMobile",Kb]],[zb,["Sogou",Yb]]]);function aw(){let e=sw.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var cw=function(){return!(Tk||Bb||jb&&Wb<80||Vb&&Fb<56)},lw=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},dw=function(){if(!navigator.mediaDevices)return hw()||QO.error(tw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},uw=!1;function hw(){return"http:"===location.protocol&&!Kk&&(uw||QO.error(rw({key:ew.NOT_SUPPORTED_HTTP})),uw=!0,!0)}var pw=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},mw=function(){return sb(this,null,(function*(){if(ow.detail.isH264EncodeSupported||ow.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ow.detail.isH264EncodeSupported,isVp8EncodeSupported:ow.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection,r=document.createElement(PN.CANVAS);r.getContext("2d");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),ow.detail.isH264EncodeSupported=t,ow.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:ow.detail.isH264EncodeSupported,isVp8EncodeSupported:ow.detail.isVp8EncodeSupported}}catch(oD){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},_w=function(){return sb(this,null,(function*(){if(ow.detail.isH264DecodeSupported&&ow.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ow.detail.isH264DecodeSupported,isVp8DecodeSupported:ow.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection;return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(oD){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},fw=function(){return sb(this,null,(function*(){if(ow.result)return ow;let e=cw(),t=Uw(),i=lw(),n=dw(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield mw(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield _w();return ow.result=e&&t&&n&&(r||o)&&(s||a),ow.detail.isBrowserSupported=e,ow.detail.isWebRTCSupported=t,ow.detail.isWebCodecsSupported=i,ow.detail.isMediaDevicesSupported=n,ow.detail.isScreenShareSupported=Tw(),ow.detail.isSmallStreamSupported=Rw(),ow.detail.isH264EncodeSupported=r,ow.detail.isVp8EncodeSupported=o,ow.detail.isH264DecodeSupported=s,ow.detail.isVp8DecodeSupported=a,ow.result||QO.error("".concat(navigator.userAgent," ").concat(MO(ow.detail,!1))),$O.setItem(Gw,{ua:navigator.userAgent,checkResult:ow}),ow}))},gw=function(){return ow.result},Tw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},Ew=(e,t,i)=>{"http:"===location.protocol&&!Kk&&(e[t]=()=>{throw new fb({code:mb.INVALID_OPERATION,message:tw.NOT_SUPPORTED_HTTP})})},Sw=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(lO(e.selected)&&!e.selected)};function Iw(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",i=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(i)}return e}function vw(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function yw(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function Aw(){return"captureStream"in HTMLCanvasElement.prototype}function Rw(){return!(ik||wb||Mk&&Mk<63)&&!(!cw()||!Aw())}var Cw=function(){if(sO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:uD}),e.addTransceiver(PN.AUDIO),t=!0}catch(oN){}return null==e||e.close(),t};function bw(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function kw(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Nw(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Dw(){return 11!==jk&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var Ow=!(!Dw()||wk&&Mk<74);function ww(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Pw(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Lw(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&kw()}var Mw=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,xw=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Vw="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ok()>=86,Uw=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function Fw(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return sO(window.AudioDecoder)||(e.AudioDecoder=!0),sO(window.AudioEncoder)||(e.AudioEncoder=!0),sO(window.VideoDecoder)||(e.VideoDecoder=!0),sO(window.VideoEncoder)||(e.VideoEncoder=!0),sO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function Bw(){return"mediaSession"in navigator&&!sO(navigator.mediaSession.setActionHandler)}function Hw(){return!sO(window.WebTransport)}function jw(){let e={browser:"".concat(Yk.name,"/").concat(Yk.version),os:Zk(),displayResolution:Iw(),isScreenShareSupported:Tw(),isWebRTCSupported:Uw(),isGetUserMediaSupported:vw(),isWebAudioSupported:yw(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Fw(),isMediaSessionSupported:Bw(),isWebTransportSupported:Hw()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var Gw="checkResult";!function(){hw();let e=$O.getItem(Gw);e&&e.ua===navigator.userAgent&&(ow=e.checkResult),fw()}();var Ww=ib(ab(),1),Jw=Symbol("instance"),Kw=Symbol("cacheResult"),zw=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,$w.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Yw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var qw=new Map;function Qw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=qw.get(n)||[];qw.has(n)||qw.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=Zw.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return i.sync?n[Kw]:Promise.resolve(n[Kw]);n.state instanceof zw&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;Array.isArray(e)?0==e.length?n.state instanceof zw&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Yw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e.join("|")))):e!==n.state&&(l=new Yw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=n.state,h=new zw(u,t,s);$w.call(n,h);let p=e=>{var r;return n[Kw]=e,h.aborted||($w.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Kw])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return $w.call(n,u,e),d(new Yw(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var Xw="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function $w(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Zw.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Zw=class extends Ww.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Zw.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Jw];n?this.name=n.name+"-"+n.count++:i[Jw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=qw.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);qw.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=Zw.instances.get(e),t||Zw.instances.set(e,t=new Zw(e,void 0,Object.create(Zw.prototype)))):(t=Zw.instances2.get(e),t||Zw.instances2.set(e,t=new Zw(e.constructor.name,void 0,Object.create(Zw.prototype)))),t}static getState(e){var t;return null===(t=Zw.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Xw(Zw.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){$w.call(this,e)}};Zw.STATECHANGED="stateChanged",Zw.UPDATEAFSM="updateAFSM",Zw.INIT="[*]",Zw.ON="on",Zw.OFF="off",Zw.instances=new Map,Zw.instances2=new WeakMap;var eP=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},tP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},iP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),nP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=$C(e===PD?{delay:2e3,count:0,backgroundTask:!0}:e===OD?{delay:1e4,count:0}:e===wD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),dO(t)&&(i=$C($C({},i),t)),oO(e)&&(t=e,e=LD);let n=$C({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")])));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=EO(),n=()=>{if(t=EO()-i,t>=e.delay&&(i=EO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=eP(n,{timeout:e.delay})};return e.ricID=eP(n,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=EO(),n=()=>document.hidden&&e.backgroundTask?(t=EO()-i,i=EO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=EO()-i,t>=e.delay&&(i=EO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=EO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&iP(n),r&&tP(r),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};nP.taskMap=new Map,nP.currentTaskID=1;var rP=nP;PN.SEI_MESSAGE;var oP={LOADED_DATA:PN.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"},sP=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:nN,env:yN.QCLOUD,browserVersion:Yk.name+Yk.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r))}logSuccessEvent(e){Kk||!QO.isAbleToUpload||this._configs.env===yN.QCLOUD&&this.uploadEventToKibana(ZC($C({},e),{result:"success"}))}logFailedEvent(e){if(Kk||!QO.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:"failed",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||mb.UNKNOWN};this._configs.env===yN.QCLOUD&&this.uploadEventToKibana(ZC($C({},o),{error:n}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:n}=e,r={timestamp:Eb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:nN,log:t};n&&(r.errorInfo=n.message),this.sendRequest(FD(this._configs.sdkAppId,vN.LOG),r)}sendRequest(e,t){QO.isAbleToUpload?jO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},aP="trtc_autoplay",cP="".concat(aP,"_mask"),lP="".concat(aP,"_wrapper"),dP="".concat(aP,"_header"),uP="".concat(aP,"_content"),hP="".concat(aP,"_action_wrapper"),pP="".concat(aP,"_question"),mP="".concat(aP,"_collapse"),_P="".concat(aP,"_action_confirm"),fP="".concat(aP,"_detail"),gP="#2473E8",TP="dialog",EP="".concat(TP,"-show"),SP="".concat(TP,"-1"),IP="".concat(TP,"-2"),vP=!1,yP=()=>!!document.querySelector(".".concat(lP)),AP="".concat(gN,"/").concat(eO()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),RP="<br><a href='".concat(AP,"' target='_blank'>").concat(eO()?"其他方案?":"Any other solution?","</a>"),CP="".concat(eO()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(RP):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(RP)),bP=class{constructor(){if(rb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),rb(this,"_dialogNode",null),rb(this,"_bodyPosition",""),rb(this,"_showDetail",!1),rb(this,"_isCollapseClicked",!1),rb(this,"_isQuestionClicked",!1),eO()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!vP){let e=document.createElement("style");e.innerHTML=".".concat(cP,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(cP," div:not(.").concat(hP,"){display:block !important;}.").concat(lP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(lP," a{color:").concat(gP,";}.").concat(dP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(uP,"{margin:8px 0;}.").concat(hP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(mP,"{margin-right:auto;cursor:pointer}.").concat(pP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(_P,"{margin-left:8px;color:#fff;background:").concat(gP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(_P,":hover{opacity:0.9;}.").concat(mP,",.").concat(_P,",.").concat(uP,",.").concat(pP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(lP,"{width:80vw;}}"),document.head.appendChild(e),vP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(cP,"\"><div class='").concat(lP,"'><div class='").concat(dP,"'>").concat(location.host,"</div><div class='").concat(uP,"'>").concat(this.content,"</div><div class='").concat(fP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(CP,"</div><div class='").concat(hP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=_P,t.innerText=eO()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=pP,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=mP,n.innerText="".concat(eO()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(".".concat(hP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r}addDiaLog(){yP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(lP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",QO.info("show autoplay dialog"),sP.uploadEvent({log:EP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){QO.warn("confirm clicked, try resume stream"),KO.emit(YO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(fP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||sP.uploadEvent({log:SP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(AP,"_blank"),this._isQuestionClicked||sP.uploadEvent({log:IP}),this._isQuestionClicked=!0}},kP={};tb(kP,{create:()=>DP,remove:()=>OP});var NP=new WeakMap;function DP(e,t){NP.has(e)||NP.set(e,[]);let i=NP.get(e),n={add:(e,r)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n}function OP(e){let t=NP.get(e);t&&(t.forEach((e=>e())),NP.delete(e))}var wP=class extends Zw{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,rb(this,"id"),rb(this,"element",null),rb(this,"track"),rb(this,"url"),rb(this,"attr"),rb(this,"muted"),rb(this,"_log"),rb(this,"_pausedRetryCount"),rb(this,"_isElementPlayingFired",!1),rb(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=yD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return sb(this,null,(function*(){if(!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(oN){let t=rw({key:ew.PLAY_FAILED,data:{media:this.kind,error:oN}});if(this.track&&!this.track.muted&&this._log.warn(oN),t.includes("NotAllowedError"))throw new fb({code:mb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),this.element.srcObject=null,this.element=null),this.handleStopped(PN.ENDED),this._interval>0&&rP.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Wk?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return DP(this.element,this.element).add(PN.PLAYING,e).add(PN.ENDED,e).add(PN.PAUSE,e).add(PN.ERROR,e).add(PN.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==kP||kP.create(this.track,this.track).add(PN.ENDED,e).add(PN.MUTE,e).add(PN.UNMUTE,e),this.track.readyState===PN.ENDED&&this.handleTrackEvent({type:PN.ENDED}),this.track.muted&&this.handleTrackEvent({type:PN.MUTE})}}bindAutoPlayEvent(){KO.on(YO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&OP(this.track)}unbindEvents(){this.element&&OP(this.element),this.unbindTrackEvents(),KO.off(YO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case PN.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(PN.PLAYING),this._interval&&(rP.clearTask(this._interval),this._interval=-1);break;case PN.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(PN.ENDED);break;case PN.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(PN.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=Ok();this._pausedRetryCount>0&&(this.kind===PN.VIDEO&&!yP()||this.kind===PN.AUDIO&&(cO(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),wb&&(this._interval=rP.run(LD,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case PN.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),sP.uploadEvent({log:"stat-".concat(this.kind,"-").concat(aD.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case PN.LOADEDDATA:this.kind===PN.VIDEO&&this.emit(oP.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case PN.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(PN.ENDED);break;case PN.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(PN.MUTE);break;case PN.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(PN.UNMUTE)}}handlePlaying(e){this.emit(oP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(oP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(oP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};nb([Qw([],"PLAYING",{sync:!0})],wP.prototype,"handlePlaying",1),nb([Qw("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],wP.prototype,"handlePaused",1),nb([Qw([],"STOPPED",{sync:!0})],wP.prototype,"handleStopped",1);var PP=class extends wP{constructor(e){super(e,PN.VIDEO),rb(this,"viewMirror",!1),rb(this,"objectFit"),rb(this,"container"),rb(this,"canvas"),this.container=e.container,this.canvas=e.canvas,sO(e.viewMirror)||(this.viewMirror=e.viewMirror),sO(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(PN.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(PN.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(PN.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.viewMirror&&this.element){let e=this.element.style.transform;t===PN.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):t===PN.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&(null==(i=this.container)||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){var e;this.setContainer(null),super.stop(),null==(e=this.canvas)||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(oP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}},LP=class{constructor(e){rb(this,"context"),rb(this,"blob_"),rb(this,"ready"),this.context=e.context,this.blob_=new Blob(['class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);'],{type:"application/javascript"}),this.ready=this.addModuleToContext()}addModuleToContext(){return sb(this,null,(function*(){try{yield this.context.audioWorklet.addModule(URL.createObjectURL(this.blob_)),QO.info("worklet addModule success")}catch(UP){QO.info("worklet addModule catch error. ".concat(UP.message))}}))}};"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var MP=new window.AudioContext({sampleRate:48e3}),xP=()=>{"suspended"===MP.state?(MP.resume(),document.addEventListener("click",xP)):"interrupted"===MP.state?MP.resume():document.removeEventListener("click",xP)};document.addEventListener("click",xP),MP.onstatechange=()=>{QO.info("context state: ".concat(MP.state)),xP()};var VP,UP,FP=e=>MP,BP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=QO.createLogger({id:"kv"}),e&&(KO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===PN.AUDIO?jP.START_MICROPHONE:GP.START_CAMERA,cost:i})})),KO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===PN.AUDIO?jP.START_MICROPHONE:GP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:BO(this.version||nN),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:n=!0}=e;var r;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(r=this.distributionMap)?void 0:r.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:n=100,useUV:r=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(cO(n))a=Math.floor(i/n);else for(let c=n.length-1;c>0;c--)if(i>n[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:n,split:r}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:n||t+100,value:i,split:r}):n||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let n=mb.UNKNOWN;cO(i)?n=i:(!sO(i.extraCode)||!sO(i.code))&&(n=i.extraCode||i.code),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:n,useUV:!1})}},HP=((VP=HP||{})[VP.enterRoom=500700]="enterRoom",VP[VP.exitRoom=500701]="exitRoom",VP[VP.switchRole=500702]="switchRole",VP[VP.destroy=500703]="destroy",VP[VP.startLocalAudio=500704]="startLocalAudio",VP[VP.updateLocalAudio=500705]="updateLocalAudio",VP[VP.stopLocalAudio=500706]="stopLocalAudio",VP[VP.startLocalVideo=500707]="startLocalVideo",VP[VP.updateLocalVideo=500708]="updateLocalVideo",VP[VP.stopLocalVideo=500709]="stopLocalVideo",VP[VP.startScreenShare=500710]="startScreenShare",VP[VP.updateScreenShare=500711]="updateScreenShare",VP[VP.stopScreenShare=500712]="stopScreenShare",VP[VP.startRemoteVideo=500713]="startRemoteVideo",VP[VP.updateRemoteVideo=500714]="updateRemoteVideo",VP[VP.stopRemoteVideo=500715]="stopRemoteVideo",VP[VP.muteRemoteAudio=500716]="muteRemoteAudio",VP[VP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",VP),jP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(jP||{}),GP=((UP=GP||{})[UP.START_CAMERA=511700]="START_CAMERA",UP),WP=new BP(!0),JP=new BP(!1),KP=WP,zP=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.preNodeReconnect(),this.reconnect(),KP.addSuccessEvent({key:502701})}catch(oD){QO.error(oD),KP.addFailedEvent({key:502701,error:oD})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),KP.addSuccessEvent({key:502702})}catch(oN){QO.error(oN),KP.addFailedEvent({key:502702,error:oN})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},YP=class extends zP{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,n="M".concat(t,",").concat(i);for(let r=0;r<e.length;r++)i=e[r]/128*100/2,n+="L".concat(t,",").concat(i),t+=1;return n}},qP=class{constructor(){this.source=new zP,this.gain=new zP,this.destination=new zP}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t=$P.get(e);if(t)return t;let i=FP();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return $P.set(e,t),t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},QP=class extends qP{constructor(e){super(),this.context=e,this.denoiser=new zP,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}},XP=class{constructor(){this.audioContext=FP(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0,this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},$P=new WeakMap;var ZP=new LP({context:FP()}),eL=class{constructor(e){rb(this,"_volume",0),rb(this,"_log"),rb(this,"_scriptProcessorNode",null),rb(this,"_audioWorkletNode",null),rb(this,"_interval",200),rb(this,"ready",this.preload());let{log:t}=e;this._log=t,KO.on(YO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return ZP.ready.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ZP.context,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(UP){sP.logFailedEvent({userId:this._log.userId,eventType:aD.LOAD_WORKLET,error:UP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=FP().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let n=0;n<t.length;++n)i+=t[n]*t[n];this._volume=Math.sqrt(i/t.length)||0}}catch(UP){this._log.error("volumeMeter init script processor error: ".concat(UP))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,KO.off(YO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},tL=class extends zP{constructor(e){super(),rb(this,"_volumeMeter"),this._volumeMeter=new eL(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}init(){return sb(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}},iL=class extends qP{constructor(e){super(),this.log=e,rb(this,"volumeMeter"),rb(this,"analyser",new YP),this.volumeMeter=new tL({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},nL=class extends wP{constructor(e){super(e,PN.AUDIO),rb(this,"_outputDeviceId"),rb(this,"_volume",1),rb(this,"_destination",FP().createMediaStreamDestination()),rb(this,"pipeline"),rb(this,"volumeMeterMode","worklet"),this.pipeline=new iL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===Hk||"15.3"===Hk||"15.4"===Hk)&&this.muted)return void this._log.info("audioElement is muted.");let e=new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,this.bindElementEvents()}play(){return sb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(FP().createAnalyser()),this.setVolume(this._volume),ob(nL.prototype,this,"play").call(this)}))}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return sb(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},rL=class extends nL{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(oP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},oL=class extends nL{constructor(e){super(e),rb(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(oP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),OP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}},sL=class extends Zw{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,PlayerClass:o=(1===n?oL:PP)}=e;var s;super(),rb(this,"id",XO()),rb(this,"userId",""),rb(this,"isRemote"),rb(this,"mediaType"),rb(this,"room"),rb(this,"user"),rb(this,"_log"),rb(this,"_inputTrack"),rb(this,"_outputTrack"),rb(this,"isPlayCalled"),rb(this,"container",null),rb(this,"player"),rb(this,"subVideoPlayerMap"),rb(this,"muted",!1),rb(this,"abortCtrl"),rb(this,"objectFit","cover"),rb(this,"mirror"),rb(this,"isScreen",!1),rb(this,"manager"),rb(this,"trackSettings"),this.userId=t||"",this.mediaType=n,this._log=QO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=r||this.room)?void 0:s.userId,remoteUserId:this instanceof LL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof LL}),this.player=new o({track:null,muted:!1,container:null,id:this.userId||this.id,log:this.log}),this.player.on(oP.PLAYER_STATE_CHANGED,(e=>{KO.emit(YO.PLAYER_STATE_CHANGED,$C({track:this},e)),this.emit("player-state-changed",e)})),this.kind===PN.VIDEO&&(this.player.on(oP.LOADED_DATA,(()=>{KO.emit(YO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(oP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})))}get log(){return this._log||QO}get kind(){return 1===this.mediaType?PN.AUDIO:PN.VIDEO}get strMediaType(){return 4===this.mediaType?PN.VIDEO:2===this.mediaType?PN.SCREEN:PN.AUDIO}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}play(e,t){return sb(this,null,(function*(){let i=uO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!sO(t.muted)&&this.setPlayerMute(t.muted),t&&!sO(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof PP&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),uO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!sO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===PN.VIDEO)&&this.setPlayerMute(!0),t&&!sO(t.objectFit)&&(this.objectFit=t.objectFit),this.kind===PN.VIDEO&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof PP&&this.player.setContainer(i)),KO.emit(YO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),uO(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==PN.VIDEO||sO(e)||e===this.mirror)return;this.mirror=e;let i=this.player;if(t&&(i=t),lO(this.mirror))return i.setViewMirror(this.mirror),void(this.room&&(this.room.videoManager.mirror=!1));switch(this.mirror){case"view":this.room&&(this.room.videoManager.mirror=!1),i.setViewMirror(!0);break;case"publish":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!0);break;case"both":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return sb(this,null,(function*(){if(!this._outputTrack||this.kind===PN.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var n;e.find((e=>i===e))||(t.stop(),null==(n=this.subVideoPlayerMap)||n.delete(i))}));for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(sO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new PP({id:this.userId||this.id,track:this.playerMediaTrack,container:r,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return sb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),KO.emit(e?YO.TRACK_MUTED:YO.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new bP;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}getVideoFrame(){return this.kind===PN.VIDEO?this.player.getVideoFrame():""}};nb([Qw([],Zw.INIT,{sync:!0})],sL.prototype,"close",1);var aL=Object.prototype.hasOwnProperty;var cL=function(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(tO(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(aL.call(e,t))return!1;return!0}return!1},lL=ib(ab(),1),dL=e=>t=>t.deviceId===e,uL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";rb(this,"kind"),rb(this,"type"),rb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&mL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(dL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");QO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(dL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");QO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},hL=class extends lL.EventEmitter{constructor(){super(),rb(this,"audioInputs",new uL(PN.AUDIO)),rb(this,"videoInputs",new uL(PN.VIDEO)),rb(this,"audioOutputs",new uL(PN.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||rP.run(PD,(()=>{this.update()}),{delay:1e4}))}init(){_L().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield _L(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},pL=lN||cN?null:new hL;function mL(e){return e.deviceId===e.groupId&&""===e.groupId}function _L(){return sb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(hw()||!dw())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{mL(e)&&(e.kind===PN.AUDIO_INPUT?i.audio=!0:e.kind===PN.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i)}catch(sN){QO.debug("capture before getDevices failed: ",sN)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let i={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&EL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function fL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return pL.update(e?1:0).then((e=>e.audioInputs.devices))}function gL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return pL.update(e?2:0).then((e=>e.videoInputs.devices))}function TL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return sb(this,null,(function*(){return pL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var EL=new Set;function SL(e,t){return sb(this,null,(function*(){let i=(yield fL()).find((e=>e.deviceId===AD));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var IL=WO({retryFunction:function(e){return sb(this,null,(function*(){let t=function(e){return{audio:yL(e),video:AL(e)}}(e);QO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],n=[],r=["label","deviceId"];t.audio&&(i=yield fL(),QO.info("microphones: ".concat(LO(i,{keysToInclude:r})))),t.video&&(n=yield gL(),QO.info("cameras: ".concat(LO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return xw&&e.getTracks().forEach((e=>{QO.info("".concat(e.kind," capabilities: ").concat(LO(e.getCapabilities(),{keysToInclude:MD})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&n&&0===n.length&&(t=rw({key:ew.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(t=rw({key:ew.MICROPHONE_NOT_FOUND}))),new fb({code:mb.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)):2===s?r[0].useDeviceIdOnly=!0:3===s&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&vL(r[0].microphoneId,!1),r[0].cameraId&&vL(r[0].cameraId,!0)},onRetrying:e=>{QO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{sP.logFailedEvent({eventType:aD.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{sP.logSuccessEvent({eventType:aD.GET_USER_MEDIA_RETRY}),sP.uploadEvent({log:"stat-".concat(aD.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function vL(e,t){return sb(this,null,(function*(){let i=(t?yield gL():yield fL()).find((t=>t.deviceId===e));i&&oO(i.getCapabilities)&&QO.warn(LO(i.getCapabilities(),{keysToInclude:MD}))}))}function yL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!cL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(cO(e.channelCount)&&(t.channelCount=e.channelCount),lO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),lO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),lO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!cL(t)||t)}function AL(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.useDeviceIdOnly&&!cL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Vb&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Vb&&(i.height.max=e.height)),Vb&&mk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!cL(i)||i)}var RL=IL;function CL(e){return kL(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return yield e.apply(this,n),t.apply(this,n)}))}))}function bL(e){return kL(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return e.call(this,t.apply(this,n))}))}))}function kL(e){return function(t,i,n){return n.value=e(n.value,i),n}}var NL=new WeakMap,DL=new WeakMap;function OL(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(NL.has(this)){let o=NL.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i})}else NL.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=NL.get(this);e&&(e.shift(),e[0]&&r($C({},e[0])))}))},i}}function wL(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return null==(t=NL.get(this))||t.forEach((e=>n.push(e))),null==(i=DL.get(this))||i.forEach((e=>e.forEach((e=>n.push(e))))),n.forEach((t=>{t.reject(new fb({code:mb.API_CALL_ABORTED,message:e}))})),NL.delete(this),DL.delete(this),r.apply(this,s)},n}}function PL(e){return function(t,i,n){let r=n.value,o=t=>cO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally((()=>{if(DL.has(n)&&DL.get(n).has(o(i))){let e=DL.get(n).get(o(i));e&&(e.shift(),e[0]&&s($C({},e[0])))}}))};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(DL.has(this))if(DL.get(this).has(o(t))){let n=DL.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i})}}else DL.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});else{let n=new Map;n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),DL.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i})}}))},n}}var LL=class extends sL{constructor(e,t){super({mediaType:e,PlayerClass:t}),rb(this,"isRemote",!1),rb(this,"deviceId"),rb(this,"groupId",""),rb(this,"label",""),rb(this,"_isRecapturing",!1),rb(this,"_lastRecaptureTime",0),rb(this,"_onMuteTimeoutId",-1),rb(this,"profile"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return"publish"===this.state}installTrackEvent(e){DP(e,e).add(PN.MUTE,this.onTrackMuted).add(PN.UNMUTE,this.onTrackUnmuted).add(PN.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===PN.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){OP(e)}setStateToCapture(){}capture(e){return sb(this,null,(function*(){var t;try{let i,n=EO();KO.emit(YO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield RL(e));let r=i.getTracks()[0];return yield this.setInputMediaStreamTrack(r),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),KO.emit(YO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:EO()-n}),i}catch(sN){throw KO.emit(YO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:sN}),this.log.error("getUserMedia error observed ".concat(sN)),sN}}))}setInputMediaStreamTrack(e){this.state===Zw.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),KO.emit(YO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return sb(this,null,(function*(){if(this.mediaTrack&&Mw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return sb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==PN.AUDIO||t!==AD||(yield SL(n,r)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),_L().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===PN.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(PN.AUDIO_INPUT);return!!EL.has(i)}(this.mediaTrack)||this.kind===PN.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(PN.VIDEO_INPUT);return!!EL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&mk&&Vk)}onTrackMuted(){if(VO(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<DD)return void setTimeout((()=>this.onTrackMuted()),DD);this._onMuteTimeoutId=setTimeout((()=>sb(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return sb(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<DD)return void setTimeout((()=>this.onTrackEnded()),DD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return sb(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield fL():yield gL()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return sb(this,null,(function*(){let e=this instanceof VL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(ML.get(t)||0)+1;if(ML.set(t,i),i>=3){let n=e?(yield gL()).find((e=>!ML.has(e.deviceId))):(yield fL()).find((e=>!ML.has(e.deviceId)));n&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(n.deviceId)),t=n.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};nb([Qw(Zw.INIT,"capture",{ignoreError:!0,sync:!0})],LL.prototype,"setStateToCapture",1),nb([OL()],LL.prototype,"capture",1),nb([Qw("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),KO.emit(YO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===mb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],LL.prototype,"publish",1),nb([kL((e=>function(){return sb(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),2===this.mediaType&&(this.mediaType=4)}))})),Qw([],"capture",{sync:!0})],LL.prototype,"unpublish",1);var ML=new Map;KO.on(YO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&ML.delete(e.track.deviceId)}));var xL=class extends LL{constructor(e){super(1,rL),rb(this,"mediaType",1),rb(this,"volume",0),rb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),rb(this,"playerMuted",!0),rb(this,"pipeline"),this.manager=e,this.pipeline=new QP(e)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return sb(this,null,(function*(){yield ob(xL.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};KP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),KP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),KP.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:n}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:n}))),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:n=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:n,customSource:i})}switchDevice(e){return sb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==AD)return;if(yield SL(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),KO.emit(YO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(oD){throw this.log.error("switch microphone failed ".concat(oD)),this.deviceId&&this.recapture(this.deviceId),oD}}}))}listenDeviceChange(){pL&&!pL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&pL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield fL();t[0]?this.recapture(t[0].deviceId):pL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return sb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!sO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!sO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!sO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&KP.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){KP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),pL.off("audioInputAdded",this.handleMicrophoneAdded,this),pL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}},VL=class extends LL{constructor(e){super(4,PP),rb(this,"mediaType",4),rb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),rb(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),rb(this,"small"),rb(this,"isNeedToSetBandwidth"),rb(this,"muteImage"),rb(this,"manager"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(ZC($C({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t)}get facingMode(){if(Mw&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}setMute(e){return sb(this,null,(function*(){var t,i,n;if(aO(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.deleteWatermark("mute"),yield null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,ob(VL.prototype,this,"setMute").call(this,!1)}else yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,ob(VL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:n=!1,customSource:r}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,customSource:r})}setProfile(e){let t=$C({},e),i=t.width>t.height;t.width*t.height<=19200&&Pb&&wk&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&Jk&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(ZC($C({},this.profile),{width:1920,height:1080})))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:PN.VIDEO,videoType:PN.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Mw&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:UO()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return sb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),KO.emit(YO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(oD){throw this.log.error("switch camera failed ".concat(oD)),this.deviceId&&this.recapture(this.deviceId),oD}}))}listenDeviceChange(){pL&&!pL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&pL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield gL();t[0]?this.recapture(t[0].deviceId):pL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return sb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}play(e,t){return sb(this,null,(function*(){return sO(this.mirror)&&!this.isScreen&&this.setMirror("view"),ob(VL.prototype,this,"play").call(this,e,t)}))}close(){pL.off("videoInputAdded",this.handleCameraAdded,this),pL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}},UL=XO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:UL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(WU){}var FL,BL=function(e){return sb(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Vk?{max:e.width}:{ideal:e.width,max:e.width},height:Vk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3}}return t}(e);QO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===n.getAudioTracks().length&&(Pk&&Mk<74||Vk||Vb)&&QO.warn("Your browser not support capture system audio");let r=n.getVideoTracks()[0];if(r){if(e.frameRate)try{yield r.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){QO.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return sb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&oO(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==UL)return;let n=yield CropTarget.fromElement(t);yield e.cropTo(n)}catch(n){QO.warn("cropTo target failed ".concat(n))}}))}(r,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return sO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);QO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0])}return n}))},HL=class extends VL{constructor(e){super(e),rb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),rb(this,"objectFit","contain"),rb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return sb(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:n,echoCancellation:r,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield BL({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:n,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof fb?e:new fb({code:mb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return sb(this,null,(function*(){throw new Error("Method not implemented.")}))}},jL=class extends xL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var GL=class extends XP{constructor(e){super(),this.room=e,rb(this,"_localAudioTrack"),rb(this,"_localScreenAudioTrack"),rb(this,"log",QO.createLogger({id:"am"})),rb(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let n=[],r=[];null!=(t=this._localAudioPipline)&&t.source.node&&(n.push(this._localAudioPipline.source.node),r.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(n.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(n.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info("dump audio track ".concat(r,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<r.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(r[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=function(e){return sb(this,null,(function*(){let t=FP();FL||(FL=t.audioWorklet.addModule(URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield FL;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}(n).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){var t;if(e instanceof jL)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof xL)this._localAudioTrack=e,this.destination.channelCount=(null==(t=e.trackSettings)?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof KL)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof jL?delete this._localScreenAudioTrack:e instanceof xL&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}},WL=class extends sL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,rb(this,"tinyId"),rb(this,"isRemote",!0),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===WL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed:".concat(this.isSubscribed," hasFlag:").concat(this.hasFlag," hasTrack:").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},JL=WL;rb(JL,"STATE_SUBSCRIBE","subscribe"),nb([Qw(Zw.INIT,JL.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),KO.emit(YO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],JL.prototype,"subscribe",1),nb([Qw(JL.STATE_SUBSCRIBE,Zw.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),KO.emit(YO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],JL.prototype,"unsubscribe",1);var KL=class extends JL{constructor(e,t){super(e,t,1),rb(this,"volume",0),rb(this,"mediaType",1),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},zL=class extends JL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),rb(this,"mediaType",4),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},YL=class extends zL{constructor(e,t){super(e,t,2),rb(this,"mediaType",2),rb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function qL(){}var QL=e=>e(),XL=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,$L=1,ZL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new rM(e,this,this.streamId++);return oM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},eM=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=qL,this.error=qL,this.next=qL,this.dispose=qL,this.subscribe=qL,this.doDefer()}subscribe(e){return e instanceof ZL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(QL),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},tM=class extends eM{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}};function iM(e,t,i){if(XL()){let n=Object.defineProperties(Object.setPrototypeOf(e,ZL.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:i,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});oM.create(n);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof ZL&&oM.addSource(n,t)}return n}return e}function nM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var rM=class extends tM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{oM.defer(this.source,this.id)}))}next(e){oM.next(this.source,this.id,e),this.sink.next(e)}complete(){oM.complete(this.source,this.id),this.sink.complete()}error(e){oM.complete(this.source,this.id,e),this.sink.error(e)}},oM={addSource(e,t){nM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){nM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:n}=e;nM("subscribe",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){nM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){nM("defer",{id:e.id,streamId:t})},pipe(e){nM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){nM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=$L++),nM("create",{name:e.toString(),id:e.id})}},sM=class extends eM{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};var aM=function(e,t){return function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return i=>{if(i instanceof ZL){let r=iM((t=>{let o=new e(t,...n);o.sourceId=r.id,o.subscribe(i)}),t,arguments);return r.source=i,oM.pipe(r),r}return t=>i(new e(t,...n))}}}(class extends tM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];i.reduce(((e,t)=>t(e)),e)}(function(e){return iM((t=>{let i=0,n=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(n)})),"interval"}),"interval",arguments)}(250),aM((()=>performance.now())),function(){return e=>{let t=new sM(e);if(e instanceof ZL){let i=iM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,oM.pipe(i),i}return iM(t.add.bind(t),"share",arguments)}}());var cM=new Map;function lM(e,t){let i=ZC($C({},t),{timestamp:Tb()});cM.has(e)?cM.get(e).push(i):cM.set(e,[i])}KO.on(YO.JOIN_SUCCESS,(e=>{let{room:t}=e;lM(t.userId,{eventId:32788,eventDesc:"join room"})})),KO.on(YO.LEAVE_START,(e=>{let{room:t}=e;lM(t.userId,{eventId:32789,eventDesc:"leave room"})})),KO.on(YO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),lM(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),KO.on(YO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),lM(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),KO.on(YO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===PN.AUDIO?lM(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):lM(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),KO.on(YO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===PN.AUDIO?lM(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):lM(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),KO.on(YO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&lM(t.room.userId,{eventId:32777,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&lM(t.room.userId,{eventId:32776,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&lM(t.room.userId,{eventId:32803,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(PN.SMALL_VIDEO),remoteUserId:t.userId}))})),KO.on(YO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&lM(t.room.userId,{eventId:32779,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&lM(t.room.userId,{eventId:32778,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&lM(t.room.userId,{eventId:32804,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(PN.SMALL_VIDEO),remoteUserId:t.userId}))})),KO.on(YO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&lM(t.room.userId,{eventId:t.kind===PN.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===PN.VIDEO?"camera":"microphone")})})),KO.on(YO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&lM(t.room.userId,{eventId:t.kind===PN.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),KO.on(YO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===r?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===r?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&lM(n.userId,{eventId:t,eventDesc:i})})),KO.on(YO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===r?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&lM(n.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var dM=ib(ab(),1),uM=class extends dM.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,rb(this,"userMap",new Map),rb(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n="peer leave [".concat(e,"]");sO(t)||(n+=":".concat(kD[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:r.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:n,userId:r,tinyId:o}=e,s=AO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:AO(0,r),muteState:s,flag:n})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var hM,pM=!0,mM={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"},_M={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},fM=((hM=fM||{})[hM.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",hM[hM.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",hM[hM.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",hM[hM.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",hM[hM.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",hM[hM.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",hM[hM.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",hM[hM.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",hM[hM.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",hM[hM.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",hM[hM.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",hM[hM.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",hM[hM.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",hM[hM.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",hM[hM.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",hM[hM.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",hM[hM.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",hM[hM.INVALID_OPERATION=5100]="INVALID_OPERATION",hM[hM.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",hM[hM.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",hM[hM.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",hM[hM.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",hM[hM.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",hM[hM.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",hM[hM.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",hM[hM.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",hM[hM.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",hM[hM.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",hM[hM.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",hM[hM.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",hM[hM.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",hM[hM.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",hM[hM.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",hM[hM.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",hM[hM.DEVICE_ERROR=5300]="DEVICE_ERROR",hM[hM.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",hM[hM.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",hM[hM.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",hM[hM.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",hM[hM.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",hM[hM.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",hM[hM.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",hM[hM.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",hM[hM.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",hM[hM.SERVER_ERROR=5400]="SERVER_ERROR",hM[hM.NEED_TO_BUY=5401]="NEED_TO_BUY",hM[hM.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",hM[hM.OPERATION_FAILED=5500]="OPERATION_FAILED",hM[hM.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",hM[hM.REJOIN_FAILED=5502]="REJOIN_FAILED",hM[hM.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",hM[hM.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",hM[hM.OPERATION_ABORT=5998]="OPERATION_ABORT",hM[hM.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",hM);var gM=ZC($C({},tw),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(rO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(rO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=TM(t),error:n}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function TM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var EM=class extends Error{constructor(e){let{code:t,extraCode:i,message:n="",messageParams:r,fnName:o="",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s="",a=fM[i];try{t=gM[a]}catch(o){t=gM.UNKNOWN_ERROR}return oO(t)?s=t(n):aO(t)&&(s=t),r&&(s+=" doc:"),s}({code:i||t,params:$C({fnName:o,error:s},r)}),super(c),rb(this,"name","RtcError"),rb(this,"code"),rb(this,"extraCode"),rb(this,"functionName"),rb(this,"message"),rb(this,"handler"),rb(this,"originError"),this.name=fM[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes("system"))&&(this.handler=()=>{let e=document.createElement("a");pk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):mk&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let n=e;if(e instanceof fb){let{stack:r}=e,o={code:_M.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case mb.INVALID_PARAMETER:o.code=_M.INVALID_PARAMETER,o.message=e.message;break;case mb.INVALID_OPERATION:o.code=_M.INVALID_OPERATION;break;case mb.NOT_SUPPORTED:case mb.NOT_SUPPORTED_H264:o.code=_M.ENV_NOT_SUPPORTED,e.getCode()===mb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(tw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case mb.SERVER_TIMEOUT:case mb.SWITCH_ROLE_FAILED:o.code=_M.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case mb.API_CALL_ABORTED:o.code=_M.OPERATION_ABORT;break;case mb.DEVICE_NOT_FOUND:case mb.DEVICE_AUTO_RECOVER_FAILED:case mb.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case mb.UNKNOWN:break;default:o.code=_M.OPERATION_FAILED}n=new EM(o),r&&(n.stack+=r.substr(r.indexOf("\n")))}else{if(e instanceof EM)return e;n=new EM({code:_M.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};var SM=EM,IM={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vM={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},yM={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(aO(e)&&!document.getElementById(e))throw new SM({code:_M.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},AM={name:"userId",required:!0,type:"string"},RM={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[mM.AUDIO_PROFILE_STANDARD,mM.AUDIO_PROFILE_STANDARD_STEREO,mM.AUDIO_PROFILE_HIGH,mM.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function CM(e,t){if(!e)throw new SM({code:_M.INVALID_OPERATION,extraCode:5101,fnName:t})}function bM(e,t,i){if(!e)throw new SM({code:_M.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var kM={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(e,t,i){if(this._room.isJoined)throw new SM({code:_M.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(aO(e.roomId))throw new SM({code:_M.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new SM({code:_M.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new SM({code:_M.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new SM({code:_M.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:yM,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:IM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&hw())throw new SM({code:_M.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},yM),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:IM}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:RM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&hw())throw new SM({code:_M.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:RM}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:yM,publish:{type:"boolean"},option:vM},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&hw())throw new SM({code:_M.ENV_NOT_SUPPORTED,extraCode:5201});if(!Tw())throw new SM({code:_M.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:yM,publish:{type:"boolean"},option:vM}},muteRemoteAudio:[AM,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[AM,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:yM,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){CM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(bM(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new SM({code:_M.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},yM),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){CM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(bM(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new SM({code:_M.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&sO(e.streamType))throw new SM({code:_M.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){CM(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!Vw)throw new SM({code:_M.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new SM({code:_M.INVALID_OPERATION,messageParams:{key:ew.SEI_DISABLED}});if(e.byteLength>1e3)throw new SM({code:_M.INVALID_PARAMETER,messageParams:{key:ew.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new SM({code:_M.INVALID_PARAMETER,messageParams:{key:ew.SEI_EMPTY}});if(CM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new SM({code:_M.INVALID_PARAMETER,messageParams:{key:ew.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},NM={TRTC:kM},DM=class extends Error{};function OM(e,t){let i=NO(e);for(let n=0;n<t.length;n++)kO(i[n],t[n]);return i}function wM(e){this._resolve=Promise.resolve(e)}function PM(e){this._reject=Promise.reject(e)}var LM=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=OM;let i=LM.instances.get(e);i?i.set(t,this):LM.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=LM.instances.get(e);return i&&i.get(t)||new LM(e,t)}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new DM("start failed")),null==(n=this.currentOp)||n.action(),t},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:wM,reject:PM};try{switch(this.state){case 1:if(0===e)throw new DM("already started");break;case 4:if(2===e)throw new DM("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(n,r)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new DM("already start");break;case 3:switch(e.type){case 2:throw new DM("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new DM("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new DM("keep stop");if(this.ops.slice(1).forEach((t=>t.reject(e))),this.ops=this.ops.slice(0,1),3===this.state)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new DM("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new DM("start not allowed after update");case 0:throw new DM("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new DM("keep start")),new DM("already start")}}e.promise=new Promise(((t,i)=>{e._resolve?e._resolve.then(t):e.resolve=t,e._reject?e._reject.catch(i):e.reject=i}));let{action:t}=e;return e.action=()=>t().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},MM=LM;MM.instances=new WeakMap;var xM=new WeakMap,VM=(e,t)=>{if(t instanceof DM){let{stack:i}=t;t=new SM({code:_M.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function UM(e,t){return kL(((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];let a=MM.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(VM.bind(null,n))}))}function FM(e,t){let{merge:i,debounce:n}=t||{};return kL(((t,r)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=MM.get(this,"string"==typeof e?e:e.call(this,...s));if(i&&(c.mergeUpdate=i.bind(this)),n&&n.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=n;return new Promise(((n,o)=>{var a,l;let d=null==(a=xM.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(VM.bind(null,r)).then(n,o)}),e);xM.has(this)?null==(l=xM.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):xM.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]))}))}return c.action(2,t.bind(this),s).catch(VM.bind(null,r))}))}function BM(e){return kL(((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return MM.get(this,"string"==typeof e?e:e.call(this,...r)).action(3,t.bind(this),r).catch(VM.bind(null,i))}))}var HM={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function jM(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function GM(e){return e===mM.QOS_PREFERENCE_CLEAR?"detail":e===mM.QOS_PREFERENCE_SMOOTH?"motion":""}function WM(e,t,i){return{room:e,assetsPath:i,innerEmitter:KO,constants:tN,environment:Ib,utils:Sb,eventLogger:sP,log:e.getLogger(),errorModule:t,kvStatManager:KP,clearStarted(t,i){let n=t.getAlias(),r=MM.instances.get(e);if(r)if(i){let e=r.get(n+i);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(n)&&(e.started=!1)}))}}}var JM=new WeakMap;function KM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return kL(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{YM.call(this,t,r,i,this._name)}catch(sN){return Promise.reject(sN)}return e.apply(this,r)}))}function zM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return kL(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{YM.call(this,t,r,i,this._name)}catch(sN){throw sN}return e.apply(this,r)}))}function YM(e,t,i,n){if(uO(e))for(let r=0;r<e.length;r++)qM.call(this,{rule:e[r],value:t[r],key:e[r].name,fnName:i,className:n});else qM.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:n})}function qM(e){let{rule:t,value:i,key:n,fnName:r,className:o}=e;function s(e){return{code:_M.INVALID_PARAMETER,extraCode:e,fnName:r,messageParams:{key:n,rule:t,value:i}}}if(sO(i)){if(t.required)throw new SM(s(5001));if(sO(t.defaultValue))return void(oO(t.validate)&&t.validate.call(this,i,n,r,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let n=0;n<t.type.length;n++)null===t.type[n]&&null===i&&(e=!0),oO(t.type[n])&&i instanceof t.type[n]&&(e=!0),aO(t.type[n])&&rO(i)===t.type[n].toLowerCase()&&(e=!0);if(!e)throw new SM({code:_M.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:n,rule:{type:t.type.map((e=>_O(e)?fO(e):aO(e)?e:rO(e)))},value:i}})}else if(!sO(t.type)&&rO(i)!==t.type)throw new SM(s(5002));if(!1===t.allowEmpty){let e=cO(i)&&(0===i||Number.isNaN(i)),t=aO(i)&&""===i.trim();if(e||t)throw new SM(s(5003))}if(t.notLessThanZero&&cO(i)&&i<0)throw new SM(s(5006));if(!sO(t.min)&&cO(i)&&i<t.min)throw new SM(s(5007));if(!sO(t.max)&&cO(i)&&i>t.max)throw new SM(s(5008));if(aO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new SM(s(5004))}else if(oO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new SM(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new SM(s(5005));let{properties:a}=t;tO(a)&&dO(i)&&Object.keys(a).forEach((e=>{qM.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:r,className:o})}));let{arrayItem:c}=t;tO(c)&&uO(i)&&i.forEach(((e,t)=>{qM.call(this,{rule:c,value:e,key:"".concat(n,"[").concat(t,"]"),fnName:r,className:o})})),oO(t.validate)&&t.validate.call(this,i,n,r,o,this)}function QM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=(()=>""),getRemoteId:i=(()=>"")}=e;return kL(((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];function a(e,t,i){if(i&&i.includes(e))return"hided";if(t===o||e in o)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(rO(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(rO(t))}}let c=this._log||QO,l=t.call(this,...o),d=""!==l?"".concat(l,".").concat(n):n;o.length>0?c.info("".concat(d,"() ").concat(JSON.stringify(o,((e,t)=>a(e,t,["userSig","privateMapKey"]))))):c.info("".concat(d,"()"));try{let t=e.apply(this,o),n=EO();return mO(t)?t.then((e=>(c.info("".concat(d,"() success ").concat(i.call(this,...o))),KP.addSuccessEvent({key:HP[d],cost:EO()-n}),e))).catch((e=>{throw e=SM.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error("".concat(d,"() failed ").concat(i.call(this,...o)," ").concat(e," params: ").concat(JSON.stringify(o,a))),KP.addFailedEvent({key:HP[d],error:e}),e})):(KP.addSuccessEvent({key:HP[d]}),t)}catch(u){throw u=SM.convertFrom.call(this,u,d),c.error("".concat(d,"() failed ").concat(u," params: ").concat(JSON.stringify(o,a))),KP.addFailedEvent({key:HP[d],error:u}),u}}))}var XM=e=>kL(((t,i)=>function(n,r){return sb(this,null,(function*(){let o=this._plugins.get(n);if(o)return YM.call(this,o.getValidateRule(e),[r],i,"TRTC"),t.call(this,o,r);this._log.warn("plugin ".concat(n," is not found"))}))})),$M=0,ZM=class{constructor(e,t){rb(this,"player"),rb(this,"publisher"),rb(this,"mixInput"),this.mixInput=new QP(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}},ex=class{constructor(e){this.core=e,rb(this,"log"),rb(this,"mixedMusicMap",new Map),rb(this,"cacheMusicMap",new Map),$M+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat($M)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat($M)),this.core=e}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return ex.startValidateRule;case"update":return ex.updateValidateRule;case"stop":return ex.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:n}=e;if(this.mixedMusicMap.has(i))return;let r=this.cacheMusicMap.get(i);r?e.url?r.reset():(r.mixInput.replaceSource(e.track),r.mixInput.connect()):(r=new ZM(e,t.audioManager),this.cacheMusicMap.set(i,r)),yield r.play(),this.mixedMusicMap.set(i,r),this.log.info("start mix audio track ".concat(i," success.")),KP.addEnum({key:502700,value:3})}))}update(e){return sb(this,null,(function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(sO(i)||(s.volume=i),sO(n)||(s.loop=n),sO(r)||s.setOperation(r),sO(o)||s.seek(o)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return sb(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},tx=ex;rb(tx,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],r=t.split(".").pop(),o=n.indexOf(r)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new SM({code:_M.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new SM({code:_M.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i})}}),rb(tx,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}}}),rb(tx,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var ix=e=>(e=Number(e))>0&&e<14e8,nx=0,rx=class{constructor(e){this.core=e,rb(this,"log"),rb(this,"ready"),rb(this,"audioContext",FP()),rb(this,"workletNode"),nx+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(nx)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(nx)),e.assetsPath&&(this.ready=this.audioContext.audioWorklet.addModule("".concat(e.assetsPath,"/denoiser-wasm.js")),this.ready.catch((t=>{this.log.error("Init assets from ".concat(e.assetsPath," failed! Reason: ").concat(t))})))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,n,r){if(!e.room.audioManager.hasAudioTrack)throw new SM({code:_M.INVALID_OPERATION,extraCode:5106,fnName:n})}}}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return rx.startValidateRule(this.core);case"update":return rx.updateValidateRule;case"stop":return rx.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core;if(this.ready||(this.ready=this.audioContext.audioWorklet.addModule("".concat(e.assetsPath,"/denoiser-wasm.js")),this.ready.catch((t=>{this.log.error("Init assets from ".concat(e.assetsPath," failed! Reason: ").concat(t))}))),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield function(e){return sb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e="https://".concat(function(e){let t;return t=ix(e)?sx.MAIN_OVERSEA:sx.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(n,"&timestamp=").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(ZC($C({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new SM({code:_M.INVALID_PARAMETER,message:o});yield this.ready,this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign:n,status:r}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return sb(this,null,(function*(){}))}stop(){return sb(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){}},ox=rx;rb(ox,"updateValidateRule",{type:"object"}),rb(ox,"stopValidateRule",{type:"object"});var sx={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var ax=0,cx=new Set,lx=null;rN("5.5.0-beta.8");var dx=class extends hb.EventEmitter{constructor(e,t){super(),rb(this,"_room"),rb(this,"_eventListened",new Set),rb(this,"_localVideoTrack",null),rb(this,"_localAudioTrack",null),rb(this,"_localScreenTrack",null),rb(this,"_localScreenAudioTrack",null),rb(this,"_localVideoConfig",null),rb(this,"_localScreenConfig",null),rb(this,"_localAudioConfig",null),rb(this,"_remoteVideoConfigMap",new Map),rb(this,"_remoteAudioConfigMap",new Map),rb(this,"_remoteAudioMuteMap",new Map),rb(this,"_mediaTrackMap",new WeakMap),rb(this,"_log",QO.createLogger({id:"t".concat(++ax)})),rb(this,"_plugins",new Map),rb(this,"_networkQuality",null),rb(this,"_speakerId"),this._room=new e($C({logger:this._log,frameWorkType:dx.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}});let i={RtcError:SM,ErrorCode:_M,ErrorCodeDictionary:fM};t.plugins&&t.plugins.forEach((e=>{let n=new e(WM(this._room,i,t.assetsPath));this._plugins.set(n.getName(),n)}));let n=new tx(WM(this._room,i,t.assetsPath));this._plugins.set(n.getName(),n);let r=new ox(WM(this._room,i,t.assetsPath));this._plugins.set(r.getName(),r),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(HM.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{let{reason:t,error:i}=e;this._log.error(new SM({code:_M.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];try{return n.apply(e,o)}catch(i){let n=rw({key:ew.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return QO.warn("".concat(n,"\n\n").concat(i.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;pM&&(pM=!1,5!==QO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(gN,"/en/index.html")),console.info("* Changelog: ".concat(gN,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),QO.info("TRTC Web SDK Version:",nN),QO.info("UA:",navigator.userAgent),QO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),Xk().then((e=>{if(e){let t="UAData: ".concat(e.platform,"/").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=" ".concat(e.architecture,"/").concat(e.bitness)),e.mobile&&(t+=" mobile"),e.model&&(t+=" model: ".concat(e.model)),e.fullVersionList&&(t+=" ".concat(e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(","))),QO.info(t)}})));let n=new dx(e,t||{});return cx.add(n),n}_listenEvents(){DP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(HM.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(HM.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(HM.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(HM.ERROR,SM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(HM.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(HM.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{DP(t,t).add("player-state-changed",(i=>{let n=ZC($C({},i),{userId:e.userId});t.kind===PN.VIDEO&&(n.streamType=jM(t.streamType)),this.emit(t.kind===PN.AUDIO?HM.AUDIO_PLAY_STATE_CHANGED:HM.VIDEO_PLAY_STATE_CHANGED,n)})).add("error",(e=>{e.getCode()===mb.PLAY_NOT_ALLOWED&&this.emit(HM.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{OP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i,r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete("".concat(n,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(n,"_","sub")),r!==s&&(this.emit(s?HM.REMOTE_AUDIO_AVAILABLE:HM.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),s?this._onAudioAvailable({userId:n}):this._onAudioUnavailable({userId:n})),o!==a&&(this.emit(a?HM.REMOTE_VIDEO_AVAILABLE:HM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"}),a?this._onVideoAvailable({userId:n,streamType:"main"}):this._onVideoUnavailable({userId:n,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?HM.REMOTE_VIDEO_AVAILABLE:HM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:n,streamType:"sub"}):this._onVideoUnavailable({userId:n,streamType:"sub"}))})).add("firewall-restriction",(()=>{this.emit(HM.ERROR,new SM({code:_M.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(HM.SEI_MESSAGE,ZC($C({},e),{streamType:jM(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,n,r,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/xD},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/xD},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(HM.STATISTICS,l)})),DP(this,pL).add("audioInputAdded",(e=>{this.emit(HM.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(HM.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(HM.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(HM.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>sb(this,null,(function*(){if(this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),lx&&lx.deviceId===RD){let e=(yield TL()).find((e=>e.deviceId===RD));e&&lx.groupId!==e.groupId&&(lx=e,this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>sb(this,null,(function*(){this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield TL())[0];t&&lx&&(lx.deviceId===e.deviceId||lx.deviceId===RD&&lx.groupId!==t.groupId)&&(lx=t,this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}enterRoom(e){return sb(this,null,(function*(){var t,i;let{scene:n="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!aO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,lO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),yield this._room.join(a,n,dx.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return sb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return sb(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){OP(this),this.removeAllListeners(),this._room.destroy(),cx.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>e.destroy()))}startLocalAudio(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:n,option:r}=t,o=new xL(e._room.audioManager),s={},a={muted:!0};r&&(sO(r.microphoneId)?sO(r.audioTrack)||(s.customSource=r.audioTrack):s.deviceId=r.microphoneId,r&&cO(r.captureVolume)&&o.setCaptureVolume(r.captureVolume),sO(r.profile)||(aO(r.profile)?DN[r.profile]&&o.setProfile(DN[r.profile]):o.setProfile(r.profile)),cO(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),sO(r.echoCancellation)||(o.profile.echoCancellation=r.echoCancellation),sO(r.noiseSuppression)||(o.profile.noiseSuppression=r.noiseSuppression),sO(r.autoGainControl)||(o.profile.autoGainControl=r.autoGainControl)),o.on("5",(t=>{e.emit(HM.ERROR,new SM({code:_M.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(HM.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=SM.convertFrom(t.error)),e.emit(HM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),sO(n)||o.setMute(n),DP(o,o).add("player-state-changed",(t=>{e.emit(HM.AUDIO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=ZC($C({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return sb(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):sO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),sO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),sO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!sO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),sO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),kO(this._localAudioConfig,e)}))}stopLocalAudio(){return sb(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),OP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:n=!0,mute:r,option:o}=t,s=new VL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:sO(o.useFrontCamera)?sO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?PN.FACING_MODE_USER:PN.FACING_MODE_ENVIRONMENT,sO(o.profile)||(aO(o.profile)?ON[o.profile]&&s.setProfile(ON[o.profile]):s.setProfile(o.profile)),sO(o.fillMode)||(c.objectFit=o.fillMode),sO(o.mirror)||(c.mirror=o.mirror),sO(o.small)||(Rw()?aO(o.small)?s.small=ON[o.small]:!0===o.small?s.small=ON["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(HM.ERROR,new SM({code:_M.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(HM.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=SM.convertFrom(t.error)),e.emit(HM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),sO(r)||(yield s.setMute(r)),(null==o?void 0:o.qosPreference)&&s.mediaTrack){let e=GM(o.qosPreference);s.mediaTrack.contentHint=e}DP(s,s).add("player-state-changed",(t=>{e.emit(HM.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"main"}))})),n&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=ZC($C({},t),{view:i,publish:n}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return sb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r){if(sO(r.profile)||(aO(r.profile)?ON[r.profile]&&this._localVideoTrack.setProfile(ON[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&sO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):sO(r.useFrontCamera)?sO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?PN.FACING_MODE_USER:PN.FACING_MODE_ENVIRONMENT),sO(r.fillMode)||(o.objectFit=r.fillMode),sO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack){let e=GM(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(r.small){let e=!this._localVideoTrack.small;Rw()?(!0===r.small?this._localVideoTrack.small=ON["120p"]:aO(r.small)?this._localVideoTrack.small=ON[r.small]:this._localVideoTrack.small=r.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===r.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!sO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),sO(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),kO(this._localVideoConfig,e)}))}stopLocalVideo(){return sb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),OP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:n=!0,option:r}=t,o=new HL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=SM.convertFrom(t.error)),e.emit(HM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null;o.setMediaType(2);let a={},c={};r&&(sO(r.profile)||(aO(r.profile)?wN[r.profile]&&o.setProfile(wN[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),sO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack),r.captureElement&&(a.captureElement=r.captureElement),r.preferDisplaySurface&&(a.preferDisplaySurface=r.preferDisplaySurface));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=GM(r.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(PN.ENDED,(()=>{e._stopScreenShare(),e.emit(HM.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new jL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),DP(o,o).add("player-state-changed",(t=>{e.emit(HM.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=ZC($C({},t),{view:i,publish:n}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return sb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(sO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=GM(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!sO(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),kO(this._localScreenConfig,e)}))}stopScreenShare(){return sb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return sb(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),r&&(sO(r.fillMode)||(a.objectFit=r.fillMode),sO(r.mirror)||(a.mirror=r.mirror),"main"===n&&!sO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),r&&!sO(r.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:r.receiveWhenViewVisible,viewRoot:null==r?void 0:r.viewRoot})}))}updateRemoteVideo(e){return sb(this,null,(function*(){var t,i;let{view:n,userId:r,streamType:o,option:s}=e,a="".concat(r,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};s&&(sO(s.fillMode)||(l.objectFit=s.fillMode),sO(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(r);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!sO(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:n,playOption:l,track:d,prevConfig:h}),kO(h,e);let p=sO(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=sO(n)?h.view:n,_=sO(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return sb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;"main"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let r=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return sb(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return sb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return sb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return sb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let n,r="main";if(aO(e)?n=e:(n=e.userId,e.streamType&&(r=e.streamType)),!n)return"sub"===r?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(n);if(e)return e.remoteAudioTrack.mediaTrack}return null}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return sb(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(sO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o})}catch(CU){throw this._remoteAudioConfigMap.delete(t),CU}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.get(i.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return sb(this,arguments,(function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(n.setMirror(i.mirror),sO(t)&&r&&r.view&&!yO(i)){let e=DO(r.view);e.length>0&&(yield n.play(e,i))}if(!sO(t)){let e=DO(t);e.length>0?yield n.play(e,i):n.stop()}}()}))}_updateAudioPlayOption(e){return sb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(aN){}sO(t.muted)||i.setPlayerMute(t.muted),sO(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e)))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit(HM.TRACK,{userId:t,streamType:jM(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:n=!1,viewRoot:r}=e;if(sO(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(jM(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||uO(i)&&0===i.length||!n)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==r)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:r}));let l=new Set(DO(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return sb(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{OP(e.remoteAudioTrack),OP(e.remoteVideoTrack),OP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return sb(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),OP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return sb(this,null,(function*(){if(lx&&!mL(lx))this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"active",device:lx});else{let e=yield TL();if(e[0]&&!mL(e[0]))lx=e[0],this.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!lx||mL(lx))&&(this._initActiveSpeaker(),KO.off("102",this._initActiveSpeaker))};KO.on("102",e)}}}))}_onAudioAvailable(e){let{userId:t}=e;!this._room.autoReceiveAudio||this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(t)||this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let n=this._room.remotePublishedUserMap.get(t);if(n){let e="main"===i?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}static setLogLevel(e,t){QO.setLogLevel(e),sO(t)||(t?QO.enableUploadLog():QO.disableUploadLog())}static isSupported(){return fw()}static getCameraList(){return gL(!0)}static getMicrophoneList(){return fL(!0)}static getSpeakerList(){return TL(!0)}static setCurrentSpeaker(e){return sb(this,null,(function*(){(yield TL()).forEach((t=>{t.deviceId===e&&(cx.forEach((i=>{i.setCurrentSpeaker(e),i.emit(HM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),lx=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:n,base:r,useUV:o,version:s}=e;switch(s&&(JP.version=s),t){case"count":JP.addCount({key:i,useUV:o});break;case"enum":JP.addEnum({key:i,value:n,useUV:o});break;case"number":JP.addNumber({key:i,value:n,split:r})}}},ux=dx;rb(ux,"_loggerManager",QO),rb(ux,"EVENT",HM),rb(ux,"ERROR_CODE",_M),rb(ux,"TYPE",mM),rb(ux,"frameWorkType",30),nb([KM(NM.TRTC.enterRoom),UM("room",((e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId})),kL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),QM()],ux.prototype,"enterRoom",1),nb([QM()],ux.prototype,"exitRoom",1),nb([KM(NM.TRTC.switchRole),FM("room",{merge:(e,t)=>t}),QM()],ux.prototype,"switchRole",1),nb([QM()],ux.prototype,"destroy",1),nb([KM(NM.TRTC.startLocalAudio),UM("audio",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId)})),QM()],ux.prototype,"startLocalAudio",1),nb([KM(NM.TRTC.updateLocalAudio),FM("audio",{debounce:{delay:200,getKey:()=>"".concat(ax,"-localAudio"),isNeedToDebounce:e=>{var t;return!sO(null==(t=e.option)?void 0:t.captureVolume)}}}),QM()],ux.prototype,"updateLocalAudio",1),nb([BM("audio"),QM()],ux.prototype,"stopLocalAudio",1),nb([KM(NM.TRTC.startLocalVideo),UM("video",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId)})),QM()],ux.prototype,"startLocalVideo",1),nb([KM(NM.TRTC.updateLocalVideo),FM("video"),QM()],ux.prototype,"updateLocalVideo",1),nb([BM("video"),QM()],ux.prototype,"stopLocalVideo",1),nb([KM(NM.TRTC.startScreenShare),UM("screen",(()=>!0)),QM()],ux.prototype,"startScreenShare",1),nb([KM(NM.TRTC.updateScreenShare),FM("screen"),QM()],ux.prototype,"updateScreenShare",1),nb([QM()],ux.prototype,"stopScreenShare",1),nb([KM(NM.TRTC.startRemoteVideo),UM((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),QM({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],ux.prototype,"startRemoteVideo",1),nb([KM(NM.TRTC.updateRemoteVideo),FM((e=>"v".concat(e.userId).concat(e.streamType))),QM({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],ux.prototype,"updateRemoteVideo",1),nb([KM(NM.TRTC.stopRemoteVideo),kL((e=>function(t){return sb(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_","main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_","sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),QM({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],ux.prototype,"stopRemoteVideo",1),nb([BM((e=>"v".concat(e.userId).concat(e.streamType)))],ux.prototype,"_stopRemoteVideo",1),nb([KM(...NM.TRTC.muteRemoteAudio),QM({getRemoteId:e=>e})],ux.prototype,"muteRemoteAudio",1),nb([zM(...NM.TRTC.setRemoteAudioVolume),function(e,t){return kL(((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];var s,a;let c=null==(s=JM.get(this))?void 0:s.get(t(...r));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,r)}),e);JM.has(this)?null==(a=JM.get(this))||a.set(t(...r),l):JM.set(this,new Map([[t(...r),l]]))}))}(200,(e=>e)),QM({getRemoteId:e=>e})],ux.prototype,"setRemoteAudioVolume",1),nb([XM("start"),UM(((e,t)=>e.getAlias()+e.getGroup(t))),QM({namePrefix:e=>e.getName()})],ux.prototype,"startPlugin",1),nb([XM("update"),FM(((e,t)=>e.getAlias()+e.getGroup(t))),QM({namePrefix:e=>e.getName()})],ux.prototype,"updatePlugin",1),nb([XM("stop"),BM(((e,t)=>e.getAlias()+e.getGroup(t))),QM({namePrefix:e=>e.getName()})],ux.prototype,"stopPlugin",1),nb([zM(...NM.TRTC.enableAudioVolumeEvaluation)],ux.prototype,"enableAudioVolumeEvaluation",1),nb([QM()],ux.prototype,"setCurrentSpeaker",1),nb([UM((e=>"a".concat(e.userId)),(()=>!0))],ux.prototype,"_startRemoteAudio",1),nb([kL((e=>function(t){return sb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(ZC($C({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),BM((e=>"a".concat(e.userId)))],ux.prototype,"_stopRemoteAudio",1),nb([BM("room")],ux.prototype,"_exitRoom",1),nb([BM("screen")],ux.prototype,"_stopScreenShare",1),nb([KM(NM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return kL(((e,r)=>{let o=new Map;return KO.on(YO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],ux.prototype,"sendSEIMessage",1),nb([QM()],ux.prototype,"getVideoSnapshot",1),nb([KM(NM.TRTC.create)],ux,"_create",1);var hx=ux,px=class{constructor(){this._set=new Set,KO.on(YO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(n)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(n)}getKey(e,t,i,n){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(n)}isJoined(e){let{userId:t,roomId:i,sdkAppId:n,room:r}=e;return"rtc"!==r.scene&&this._set.has(this.getKey(t,i,n,r.useStringRoomId))}};function mx(){return sb(this,null,(function*(){let e,t;try{let t=yield fL();e=t&&t.length}catch(u){}try{let e=yield gL();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:n,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=ZO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:n,h264Decode:o,vp8Encode:r,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};sP.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),sP.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var _x=ib(ab(),1),fx=Symbol("instance"),gx=Symbol("cacheResult"),Tx=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,yx.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Ex=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Sx=new Map;function Ix(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Sx.get(n)||[];Sx.has(n)||Sx.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=Ax.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return n[gx];n.state instanceof Tx&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;if(Array.isArray(e)?0==e.length?n.state instanceof Tx&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Ex(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not in from config"))):e!==n.state&&(l=new Ex(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=n.state,u=new Tx(d,t,s);yx.call(n,u);let h=e=>{var r;return n[gx]=e,u.aborted||(yx.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[gx])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(yx.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new Ex(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var vx="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function yx(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Ax.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Ax=class extends _x.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Ax.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[fx];n?this.name=n.name+"-"+n.count++:i[fx]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Sx.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);Sx.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=Ax.instances.get(e),t||Ax.instances.set(e,t=new Ax(e,void 0,Object.create(Ax.prototype)))):(t=Ax.instances2.get(e),t||Ax.instances2.set(e,t=new Ax(e.constructor.name,void 0,Object.create(Ax.prototype)))),t}static getState(e){var t;return null===(t=Ax.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};vx(Ax.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){yx.call(this,e)}};Ax.STATECHANGED="stateChanged",Ax.UPDATEAFSM="updateAFSM",Ax.INIT="[*]",Ax.ON="on",Ax.OFF="off",Ax.instances=new Map,Ax.instances2=new WeakMap;var Rx=ib(ab()),Cx="1",bx="5",kx="2",Nx="3",Dx="4",Ox={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158},wx=[Ox.UPDATE_REMOTE_MUTE_STAT,Ox.UPLINK_NETWORK_STATS,Ox.USER_LIST_RES,Ox.MUTE_RESULT],Px={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report"},Lx="publish_change",Mx="join",xx="leave",Vx="quality_report",Ux="mute_uplink",Fx="publish",Bx="publish_state_change",Hx="unpublish",jx="subscribe",Gx="unsubscribe",Wx="subscribe_change",Jx="start_publishing",Kx="stop_publishing",zx="start_push_user_cdn",Yx="stop_push_user_cdn",qx="start_mcu_mix",Qx="stop_mcu_mix",Xx="get_user_list",$x="change_role",Zx="update_constraint_config",eV="rebuild_pc",tV="join/v2",iV="publish/v2",nV="subscribe/v3",rV="ability_status_report",oV="reconnect",sV=new WeakMap;function aV(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=WO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,(()=>{var t;null!=(t=sV.get(e))&&t.has(o)?r():s(n)}),s,a)},onRetrying(t,i){var r;oO(n)&&n.call(this,t,i),null!=(r=sV.get(e))&&r.has(o)&&(sV.get(e).get(o).stopRetry=i)},onRetryFailed:r});return s.value=function(){let t=sV.get(e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return t?t.set(o,{args:n}):sV.set(e,new Map([[o,{args:n}]])),a.apply(this,n).finally((()=>{var t;return null==(t=sV.get(e))?void 0:t.delete(o)}))},s}}function cV(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(r=sV.get(e))&&r.has(t)){let{stopRetry:r,args:s}=sV.get(e).get(t),a=!0;if(n)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),r&&r(),null==(o=sV.get(e))||o.delete(t))}return s.apply(this,c)},o}}var lV=null,dV=!0;function uV(e){lO(e)&&e!==dV&&(dV=e,QO.info("setIsNeedToSchedule ".concat(e)))}function hV(e){return sb(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:n,roomId:r,userSig:o,version:s,frameWorkType:a}=e;return function*(){if(!dV&&lV)return{isCached:!0,result:lV};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(n)),c.append("groupId",String(r)),c.append("sdkVersion",s),c.append("userSig",String(o)),a&&c.append("frameWorkType",String(a));let l=EO(),d=yield function(e,t,i){return new Promise(((n,r)=>{let o=null;TO([gV((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n()}))(_V(i,PN.MAIN),e,{get timeout(){return 1e3*iO(2+t.count[0])}}),gV((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n()}))(_V(i,PN.BACKUP),e,{get timeout(){return 1e3*iO(2+t.count[1])}})]).then((e=>{o=e,n(o)})).catch(r)}))}(c,e,i);d.config&&(d.config.loggerDomain&&hN(d.config.loggerDomain),lO(d.config.scheduleCache)&&uV(!d.config.scheduleCache)),e.delta=EO()-l;let u=function(e,t,i){let n=performance.getEntriesByType("resource"),r=_V(e,PN.MAIN),o=_V(e,PN.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?PN.MAIN:PN.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];sP.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=ZC($C({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,l);return lV=d,{isCached:!1,result:d,detailCost:u}}catch(c){let e=uO(c)?c[0]:c,t=cO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),n=new fb({code:mb.SCHEDULE_FAILED,extraCode:t,message:rw({key:ew.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw QO.error(i,t),n}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(SD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),KO.on("28",(()=>uV(!0))),KO.on("63",(()=>uV(!0))),KO.on("84",(()=>uV(!0))),KO.on("201",(e=>{"RECONNECTING"===e.state&&uV(!0)})),KO.on("202",(e=>{"RECONNECTING"===e.state&&uV(!0)}));var pV={main:"",backup:""};function mV(e){uO(e)?(pV.main=e[0],pV.backup=e[1]):pV.main=e}function _V(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:PN.MAIN;return t=UD(e)?i===PN.MAIN?SD.MAIN_OVERSEA:SD.BACKUP_OVERSEA:i===PN.MAIN?SD.MAIN:SD.BACKUP,"https://".concat(pV[i]||t,"/api/v1/config")}function fV(e,t,i){return new Promise(((n,r)=>{jO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg})})).catch(r)}))}var gV=(e,t)=>WO({retryFunction:fV,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var TV=new Set;var EV=class extends Rx.default{constructor(e){var t,i;super(),rb(this,"room"),rb(this,"url"),rb(this,"backupUrl"),rb(this,"race"),rb(this,"_socketInUse"),rb(this,"_socket"),rb(this,"_backupSocket"),rb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_seq",0),rb(this,"_log"),rb(this,"_lastMessageTime",-1),rb(this,"_connnectStartTime",-1),rb(this,"_stopConnectRetry"),rb(this,"bytesSent",0),rb(this,"bytesReceived",0),rb(this,"keepAlive",!1),this.room=e.room,this.race=!!sO(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-TV.size>0&&this.room.enableSPC&&(this.keepAlive=!0,TV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=QO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=EO();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield TO(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?PN.BACKUP:PN.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:n}=e,r=new WebSocket(t);this.bindSocket(r),n?this._socket=r:this._backupSocket=r;let o=-1;return new Promise(((e,t)=>{r.onclose=t,r.onerror=t,r.onopen=()=>e(r),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(n?PN.MAIN:PN.BACKUP),t(new fb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{r.onclose=null,r.onerror=null,r.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===PN.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(oD){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(oD){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||1e3!==e.code)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?PN.MAIN:PN.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),e.target===this._socketInUse&&(this.unbindAndCloseSocket(PN.MAIN),this.unbindAndCloseSocket(PN.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=xO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(Ox),o=Object.keys(Ox)[r.indexOf(i)],s=Px[o];switch(wx.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case Ox.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&function(e){gb=e-(new Date).getTime();let t=new Date;t.setTime(e),QO.info("baseTime from server: ".concat(t," offset: ").concat(gb))}(n.svrTime),this._log.info("ChannelSetup Success"),KP.addSuccessEvent({key:521701,cost:EO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(Cx,{signalInfo:this._signalInfo});else{let e=new fb({code:mb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:rw({key:ew.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),KP.addFailedEvent({key:521701,error:e}),this.emit(bx,e)}break;case Ox.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return sb(this,null,(function*(){try{uV(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(oN){}}))}reconnect(){return sb(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:n,relayPort:r}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:oV,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:i,relayPort:r},responseCommand:Px.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),KP.addSuccessEvent({key:521702,cost:EO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(KP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(oN){this._log.error(oN),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=xO(n),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(r,l);let e=new fb({code:mb.API_CALL_TIMEOUT,message:rw({key:ew.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t))};this.on(r,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return WO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(n,"]"))},settings:{retries:n,timeout:r},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),TV.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(PN.MAIN),this.unbindAndCloseSocket(PN.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof Tx&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(Ax.STATECHANGED,i))};this.room.on(Ax.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(kx,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e&&this.emit(Nx))}};nb([aV({settings:{retries:1/0,timeout:2e3},onError(e,t){this.room.isDestroyed||t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,this.room.isDestroyed&&t())}})],EV.prototype,"connect",1);var SV=ib(ab()),IV=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],n=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let r=6;r<this.dataView.buffer.byteLength;r++){let i=this.dataView.getUint8(r);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),n=new DataView(i);for(let r=0;r<i.byteLength;r++,t++)n.setInt8(r,this.dataView.getInt8(t));return n}},vV=class{constructor(e,t){this._singlePC=e,this._log=t,rb(this,"_seiMessageList",[]),rb(this,"_smallSeiMessageList",[]),rb(this,"_seiPayloadType",243),rb(this,"_seiAbortMap",new Map),rb(this,"_nonSeiAbortMap",new Map),rb(this,"onSEIMessage",null)}isRunning(e){return this._seiAbortMap.has(e)}start(e){let t=e.direction===PN.TRANSCEIVER_DIRECTION_SENDONLY,i=(t?e.sender:e.receiver).createEncodedStreams(),n=i.readable,r=i.writable,o=new TransformStream({transform:t?(t,i)=>this.encodeVideoFrame(t,i,e):(t,i)=>this.decodeVideoFrame(t,i,e)}),s=new AbortController;n.pipeThrough(o).pipeTo(r,s).catch((e=>{this._log.warn(e)})),this._seiAbortMap.set(e,s)}restart(e){this.stop(e),this.start(e)}stop(e){var t;null==(t=this._seiAbortMap.get(e))||t.abort(),this._seiAbortMap.delete(e)}destroy(){this._seiAbortMap.forEach((e=>e.abort())),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach((e=>e.abort())),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach(((e,t)=>{var i,n;if("inactive"!==e.direction&&e.mid)if(t<4)1===t||2===t?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let r=(t-4)%3==1,o=(t-4)%3==2;(null==(n=null==(i=e.receiver)?void 0:i.track)?void 0:n.kind)===PN.VIDEO&&(r||o)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}}))}catch(UP){this._log.warn(UP)}}pipeSenderOrReceiver(e){let t=e.direction===PN.TRANSCEIVER_DIRECTION_SENDONLY?e.sender:e.receiver,{readable:i,writable:n}=t.createEncodedStreams(),r=new AbortController;this._nonSeiAbortMap.set(e,r),i.pipeTo(n,r).catch((()=>{}))}push(e,t){var i,n;t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==(n=null==(i=this._singlePC.getPeerConnection())?void 0:i.getSenders()[2])?void 0:n.track)&&this._smallSeiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0,n=new DataView(e);for(let r=0;r<e.byteLength;r++)switch(n.getUint8(r)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encodeVideoFrame(e,t,i){try{let t=2===Number(i.mid)?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&t.length>0&&!this.isEmptyFrame(e)){let i=9-this.getNaluCount(e.data);if(i<=0)return;let n=t.splice(0,i).reverse().map(this.encodeSEINalu.bind(this)),r=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(r+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<n.length;e++)for(let t=0;t<n[e].dataView.byteLength;t++)s.setInt8(c++,n[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));e.data=o,this._log.debug("".concat(n.length," sei sent"))}}catch(sN){this._log.warn(sN)}t.enqueue(e)}decodeVideoFrame(e,t,i){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],n=new DataView(e.data),r=0,o=-1,s=-1;for(let i=0;i<e.data.byteLength;i++){let a=n.getUint8(i);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=i-r;if(-1===o?o=a:-1===s&&(s=a,t.push(new IV(new DataView(n.buffer.slice(o,s)))),o=a,s=-1),6!==n.getUint8(i+1)){e.data=new DataView(n.buffer.slice(a)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),oO(this.onSEIMessage)&&t.reverse().forEach((e=>{let t=Number(i.mid);this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,mid:t,streamType:(t-4)%3==2?"auxiliary":"main"})}))}}catch(sN){this._log.warn(sN)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)r.push(255);r.push(n);let o=new DataView(e);return r.push(...new Uint8Array(o.buffer)),r.push(128),new IV(new DataView(new Uint8Array(r).buffer),!0)}},yV=0,AV=!1,RV=new Set,CV=!1,bV=class{constructor(e){rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_isErrorObserved",!1),rb(this,"_waitForPeerConnectionConnectedPromise"),rb(this,"_waitForPeerConnectionConnectedPromiseReject",null),rb(this,"_peerConnection",null),rb(this,"_emitter",new SV.default),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_reconnectionCount",0),rb(this,"_reconnectionTimer",-1),rb(this,"_isFirstConnection",!0),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),rb(this,"_localAddress"),rb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=QO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Vw&&(this._sei=new vV(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=EO())}afterConnect(e){return sb(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,KP.addSuccessEvent({key:521705,cost:Math.min(EO()-this._prevTime,3e4)})):this._isReconnecting&&KP.addSuccessEvent({key:521706,cost:EO()-this._prevTime}),this._prevTime=-1}catch(oN){throw this._isFirstConnection?(this._isFirstConnection=!1,KO.emit(YO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:oN}),KP.addFailedEvent({key:521705,error:oN})):this._isReconnecting&&this._reconnectionCount>=3&&(KP.addFailedEvent({key:521706,error:oN}),KO.emit(YO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:oN})),oN}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&Vw,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),RV.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new fb({code:mb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return eD;let e=null;if(this._isUplink){if(!kw()||0===this._peerConnection.getSenders().length)return eD;e=this._peerConnection.getSenders()[0].transport}else{if(!bw()||0===this._peerConnection.getReceivers().length)return eD;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:eD}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===tD.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===tD.FAILED||e.target.connectionState===tD.CLOSED){let n="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),r=new fb({message:n,code:mb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",r)}(e.target.connectionState===tD.CONNECTED||e.target.connectionState===tD.COMPLETED)&&(this.logSelectedCandidate(),sP.logSuccessEvent({userId:this._room.userId,eventType:aD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(yV=0,AV=!1,CV=!0,RV.add(this)):RV.delete(this),KO.emit(YO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(Sw(t)){let i=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{KO.off(YO.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{r();let e=new fb({code:mb.API_CALL_TIMEOUT,message:"connection timeout"});var i;yV+=1,i=this._signalChannel.isConnected,yV>2&&!AV&&0===RV.size&&i&&(this._log.warn("firewall restrition"),AV=!0,this._emitter.emit("firewall-restriction")),t(e)}),ED);KO.on(YO.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Nx,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=rD()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new fb({code:this._isUplink?mb.UPLINK_RECONNECTION_FAILED:mb.DOWNLINK_RECONNECTION_FAILED,message:rw({key:this._isUplink?ew.UPLINK_RECONNECTION_FAILED:ew.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Nx,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},kV=ib(ub()),NV=function(e){return kV.default.parse(e)},DV=function(e){return kV.default.write(e)};function OV(e){return Object.keys(e).filter((t=>e[t]))}var wV=class extends bV{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,auxiliary:0}),rb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new KL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new zL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new YL(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return AO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===PN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===GN?PN.MAIN:PN.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=PN.AUDIO;i.kind===PN.VIDEO&&(r=n===PN.MAIN?PN.VIDEO:PN.AUXILIARY);let o=this.remoteAudioTrack;r===PN.VIDEO?o=this.remoteVideoTrack:r===PN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let n=[...i];for(let r=0;r<n.length;r++){let[e,i]=n[r];t.splice(e+r,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=NV(e);return t.media.forEach((e=>{e.type===PN.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),DV(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=NV(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),DV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===tD.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===tD.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(aN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(aN.message," ").concat(JSON.stringify(this.muteState))),new fb({code:mb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):aN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(n," stream already unsubscribed"));let e=$C({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let r="subscribe_change";Object.values(e).find((e=>!0===e))||(r="unsubscribe"),t._log.info("".concat("unsubscribe"===r?r:"subscribe"," ").concat(n," [").concat(OV(e),"]")),yield t.sendSubscription(r,e),"unsubscribe"===r&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Gx,r=Px.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Wx,r=Px.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:rw({key:ew.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(oD){throw e.closePeerConnection(!0),oD}}()}))}exchangeSDP(e){return sb(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:jx,commandDesc:"exchange sdp",data:n,responseCommand:Px.SUBSCRIBE_RESULT,timeout:dD});if(!this._peerConnection){let e=new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(r),this._isSDPExchanging=!1}catch(oD){throw this._isSDPExchanging=!1,oD}}))}createOffer(){return sb(this,null,(function*(){let e={voiceActivityDetection:!1};Dw()&&this._sdpSemantics===uD?(this._peerConnection.addTransceiver(PN.AUDIO,{direction:LN.RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:LN.RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:LN.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield _w();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=NV(e);return t.media.forEach((e=>{var t,i;if(e.type===PN.VIDEO){let n=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&n.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t)}));let r=e=>{let{payload:t}=e;return!n.has(t)};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!n.has(Number(e)))).join(" ")}})),DV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=NV(e);return t.media.forEach((e=>{e.type===PN.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),DV(t)}(t.sdp),this._sdpSemantics===uD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return sb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===pD)throw new fb({code:mb.NOT_SUPPORTED_H264,message:rw({key:ew.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new fb({code:t,message:rw({key:ew.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",ZC($C({},e),{userId:this.userId}))}),this.updateSSRC(r)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{NV(e).media.forEach((e=>{if(e.ssrcs)if(e.type===PN.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(GN)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(GN)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(WN)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(oD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return sb(this,null,(function*(){if(!(ob(wV.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(oD){let t=nO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}},PV=wV;nb([kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],PV.prototype,"subscribe",1),nb([bL(bV.prototype.afterConnect),CL(bV.prototype.beforeConnect)],PV.prototype,"connect",1);var LV=PV,MV={voiceActivityDetection:!1},xV=class extends bV{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Nw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===PN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),Dw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==n?void 0:n.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||PN.AUDIO,{direction:LN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?PN.VIDEO:s||PN.VIDEO,{direction:LN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||PN.VIDEO,{direction:LN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||PN.VIDEO,{direction:LN.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:PN.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:PN.VIDEO,videoType:o?PN.AUXILIARY:PN.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:PN.VIDEO,videoType:PN.SMALL}),e.push(2))}yield t.setTransceiverDirection(LN.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==n||n.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info("publish by addtrack");let e=null==n?void 0:n.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream;e.addTrack(r),t._peerConnection.addTrack(r,e)}yield t.connect()}()}))}enableSmall(e){return sb(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(LN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(LN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!Nw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent("DISCONNECTED",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(LN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Bx,data:t,responseCommand:Px.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:Hx,commandDesc:"unpublish",responseCommand:Px.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Mw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Zx,data:this._mediaSettings,responseCommand:Px.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?PN.AUXILIARY:PN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),Dw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield n[0].sender.replaceTrack(e.outMediaTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===LN.INACTIVE&&(yield this.setTransceiverDirection(LN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Nw()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===PN.VIDEO&&e instanceof VL&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===hD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=NV(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===PN.VIDEO)return!0;return!1}removeSender(e){let t=null;Nw()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&oO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?PN.AUXILIARY:PN.MAIN," stream")),Dw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield i[0].sender.replaceTrack(null);else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(LN.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Vb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(LN.INACTIVE,"|").concat(LN.RECVONLY,"|").concat(LN.SENDONLY,")")))&&o++,t.includes(o)){if(e===LN.INACTIVE&&i.includes("a=".concat(LN.RECVONLY)))return n=!0,"a=".concat(e);if(e===LN.SENDONLY&&i.includes("a=".concat(LN.INACTIVE)))return n=!0,"a=".concat(LN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===PN.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===PN.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===PN.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=Dw()?e.kind===PN.AUDIO?n[0]:n[1]:n.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(r?PN.AUXILIARY:PN.MAIN," stream")),e.kind===PN.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===PN.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return sb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(MV);Vb&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===PN.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:Lx,data:r,responseCommand:Px.UPDATE_OFFER_RESULT,timeout:lD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(sN){throw this._log.error(sN),sN}}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!Lw())return o?n===PN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(Dw()){let t=0;n===PN.VIDEO&&(t=r===PN.SMALL?2:r===PN.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===n));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(r||"").concat(n," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return n===PN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let n="AS";Vb&&(n="TIAS",t*=1e3);let r=0,o=-1;return i===PN.SMALL?r=1:i===PN.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===r?"".concat(e,"b=").concat(n,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return Vb&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return sb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(oN){throw this.closePeerConnection(!0),this.uninstallEvents(),oN}}))}exchangeSDP(){return sb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(oN){throw oN}}))}createOffer(){return sb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(MV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(oN){throw oN}}))}doExchangeSDP(){let e={command:Fx,responseCommand:Px.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof HL||this.localAuxVideoTrack instanceof HL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",n=NV(e);return n.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),DV(n)}acceptAnswer(e){return sb(this,null,(function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?PN.AUXILIARY:PN.BIG;s=yield this.setBandwidth({bandwidth:e,type:PN.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:PN.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:PN.VIDEO,videoType:PN.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(CU){throw this._log.error("failed to accept remote answer ".concat(CU)),CU}}))}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info("send muted state: ".concat(JSON.stringify(r))),this._signalChannel.send(Ux,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return sb(this,null,(function*(){if(!(ob(xV.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Hx,responseCommand:Px.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(oD){let t=nO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&KO.emit(YO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{NV(e).media.forEach(((e,t)=>{if(e.type===PN.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===hD&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(oD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:PN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===PN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===PN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===PN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===PN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===pD?(this._log.error(tw.NOT_SUPPORTED_H264ENCODE),new fb({code:mb.NOT_SUPPORTED_H264,message:rw({key:ew.NOT_SUPPORTED_H264ENCODE})})):new fb({code:mb.UNKNOWN,message:rw({key:ew.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Px.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},VV=xV;nb([kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],VV.prototype,"publish",1),nb([bL(bV.prototype.afterConnect),CL(bV.prototype.beforeConnect)],VV.prototype,"connect",1);var UV=VV,FV=class{constructor(e,t){this.room=e,rb(this,"_log"),rb(this,"_prevReportTime"),rb(this,"_prevReport",{}),rb(this,"_prevEncoderImplementation"),rb(this,"_prevQualityLimitationReason"),rb(this,"_prevAuxQualityLimitationReason"),rb(this,"_prevDecoderImplementationMap",new Map),rb(this,"totalBytesSent",0),rb(this,"totalBytesReceived",0),rb(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return sb(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var r;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===PN.VIDEO){let r,o;if(i.ssrc===n.video?(r=PN.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=PN.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=PN.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,sO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),sO(i.nackCount)||(t[r].nackCount=i.nackCount),sO(i.pliCount)||(t[r].pliCount=i.pliCount),sO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),sO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),sO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!sO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!sO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!sO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?Sw(i)&&cO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===PN.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===PN.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(PN.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(PN.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!sO(i.audioLevel)&&(null==(r=e.localMainAudioTrack)?void 0:r.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!sO(i.frameWidth)){let r=PN.SMALL;i.trackIdentifier===e.getVideoTrackId(PN.VIDEO)||i.ssrc===n.video?r=PN.VIDEO:(i.trackIdentifier===e.getVideoTrackId(PN.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=PN.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(r){this._log.warn("failed to getStats on sender connection ".concat(r))}return t}))}getReceiverStats(e){return sb(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===PN.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,i.jitterBufferDelay&&(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount),t.hasAudio=!0}else{if(Vb&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===n.auxiliary&&r.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&Sw(i)&&cO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);sO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!sO(i.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&i.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(sN){this._log.warn("failed to getStats on receiver connection ".concat(sN))}return t}))}getStats(e,t){return sb(this,null,(function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&r.push(e))),this._spcStats=r}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e)}return{senderStats:i,receiverStats:n}}))}getDifferenceValue(e,t){if(cL(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!cL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*xD,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*xD);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e)}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r}}let{statInterval:r}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=n.get("".concat(e.userId,"_").concat(JN)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=n.get("".concat(e.userId,"_").concat(KN)),r=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),pk&&115===Ok()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),sO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),sO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),sO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),sO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),sO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),sO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r))}));let a=o.msg_down_stream_info;return i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid)))),i.msg_down_stream_info.forEach((e=>{let t=a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(cL(e.msg_audio_status)||cL(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status,o=this.getDifferenceValue(n.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(n.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/o)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/r),i.uint32_audio_total_bitrate=Math.round(8*a/r)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r)}))}})),i}getStatsReport(e){return sb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,n);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},BV=ib(ab()),HV=class extends BV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_log"),rb(this,"_uplinkRTT",0),rb(this,"_uplinkLoss",0),rb(this,"_downlinkRTT",0),rb(this,"_downlinkLoss",0),rb(this,"_downlinkPrevStatMap",new Map),rb(this,"_downlinkLossAndRTTMap",new Map),rb(this,"_interval",-1),rb(this,"_uplinkNetworkQuality",0),rb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=QO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(Px.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(kx,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return sb(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===tD.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r<t.length;r++){let e=t[r].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:n,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=n-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[r].getUserId(),audioDelay:t[r].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[r].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i)}))}getStat(e){return sb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!bw())return t;let i=e.getReceivers();try{for(let e=0;e<i.length;e++)(yield i[e].getStats()).forEach((e=>{"candidate-pair"===e.type&&cO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===PN.AUDIO||e.mediaType===PN.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(n){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==tD.DISCONNECTED&&e.connectionState!==tD.FAILED&&e.connectionState!==tD.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=rP.run(OD,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];KO.emit(YO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(HV.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(rP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r})}}))}},jV=HV;rb(jV,"EVENT_NETWORK_QUALITY","0");var GV=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=QO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&oO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];let o=t.apply(i,n);return mO(o)?o.catch((e=>QO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(oD){QO.error("".concat(t.name,"() error observed ").concat(oD))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=rP.run(OD,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:nN,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Xk().then((e=>{this._basicInfo.string_os_version=eN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),KO.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(YO.JOIN_START,this.handleJoinStart).addEvent(YO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(YO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(YO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(YO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(YO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(YO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(YO.JOIN_FAILED,this.handleJoinFailed).addEvent(YO.LEAVE_START,this.handleLeaveStart).addEvent(YO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(YO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(YO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(YO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(YO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(YO.PUBLISH_START,this.handlePublishStart).addEvent(YO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(YO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(YO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(YO.PLAY_TRACK_START,this.handlePlayStart).addEvent(YO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(YO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:n}=e;!pO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(n===PN.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(YO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(YO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(YO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(YO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(n.userId,"auxiliary")})).addEvent(YO.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)}))}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach(((e,t)=>KO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),rP.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(sO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),sO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),sO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof fb?Number(i.getExtraCode()||i.getCode()):mb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let n="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:ZC($C({},JV),{msg_user_info:new KV({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(n,r)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new KV({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===n?(i.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!pO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!pO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/xD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/xD,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n="".concat(r,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*QC(10,6)))}})),i){let e="".concat(r,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/xD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/xD,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof fb?i.getExtraCode()||i.getCode():mb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&VN))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&BN))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&FN))>=0}hitTest(e){return e===this._room}checkStorage(){return sb(this,null,(function*(){try{let e=$O.getItem(this._storageKey);e&&(yield this.upload(e),$O.deleteItem(this._storageKey))}catch(UP){this._log.warn(UP)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&$O.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,PN.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,PN.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,WV);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>WV&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+WV):this._pathMainAudioMap.delete(t)})),this._pathMainVideoMap.forEach(((e,t)=>{this.hasVideoFlag(e.userId)?e.statsToReport.uint64_render_first_frame_time-e.statsToReport.uint64_start_enter_time>WV&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+WV):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>WV&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+WV)}getReportData(){this._basicInfo.uint32_networkType=KD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new KV({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:bO(this._signalInfo.relayIp),uint32_client_ip:bO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*QC(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map((e=>e.statsToReport)),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map((e=>e.statsToReport)),uint32_info_client_ip:bO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return HO(e),e}report(){return sb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),$O.deleteItem(this._storageKey),this.initData()}catch(UP){this._log.warn(UP)}}))}upload(e){return sb(this,null,(function*(){if(Kk&&!Ek||0===e.msg_path_enter_room.uint64_start_time||[pN,mN,_N].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=yield GO(e),n=i instanceof ArrayBuffer,r="".concat(FD(t,vN.KEY_POINT),"&gzip=").concat(+n),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,i)),o||jO({url:r,body:i}),this.uploadKVStat(KP),this.uploadKVStat(JP)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return sb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=ZC($C({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield GO(t),n="".concat(FD(+this._room.sdkAppId,vN.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),r=!1;navigator.sendBeacon&&(r=navigator.sendBeacon(n,i)),r||jO({url:n,body:i})}))}};nb([aV({settings:{timeout:500,retries:3}})],GV.prototype,"upload",1);var WV=5e3,JV={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},KV=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},zV=GV,YV=class{constructor(){rb(this,"_startTime"),rb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=EO())}stop(){0===this._endTime&&(this._endTime=EO())}getDuration(){return 0===this._endTime?EO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},qV=class{constructor(e){rb(this,"_room",null),rb(this,"_durationMap"),rb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(YO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(YO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(YO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),PN.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),PN.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),PN.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,PN.AUDIO,"main"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,PN.VIDEO,"main"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,PN.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>KO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>KO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);if(n.muteState.hasAudio&&"main"===i)if(n.remoteAudioTrack.isSubscribed){let e=new YV,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,PN.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new YV,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,PN.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDurationItem(o,PN.AUDIO),this.stopDurationItem(o,PN.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let n="".concat(e,"_").concat(i),r=new YV,o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===PN.AUDIO?[r]:[],video:t===PN.AUDIO?[]:[r]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},QV=class{constructor(e){rb(this,"_room"),rb(this,"_renderFreezeMap",new Map),rb(this,"_isVideoPlayingEventFiredMap",new Map),rb(this,"_dataFreezeMap",new Map),rb(this,"_monitorFreezeData",new Map),rb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(YO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(YO.PLAY_TRACK_START,this.onPlayTrackStart).set(YO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDataFreeze({key:o,userId:r,type:i})})).set(YO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e="main",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}if(i.hasAuxiliary&&!n.hasAuxiliary){let e="auxiliary",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}})).set(YO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:n,type:r}=e;if(pO(t)&&this.hitTest(t.room)&&r===PN.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}n===PN.MUTE?this.onVideoTrackMuted(t):n===PN.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(YO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>KO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>KO.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i),r=this._dataFreezeMap.get(n),o=new YV;r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i);this.stopDataFreeze({key:n,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:n}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>_D?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return sb(this,arguments,(function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e="".concat(i,"_").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=EO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=EO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!pO(t)||!this.hitTest(t.room)||t.kind!==PN.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<_D&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,n=0;if(t)if(t.isFreeze){let e=EO()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),n=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},XV=ib(ab(),1),$V=[-1,-1,1,-1,-1,1,1,1],ZV=[0,0,1,0,0,1,1,1],eU=class extends Zw{constructor(e,t){if(super(),this.context=e,rb(this,"name"),rb(this,"input"),rb(this,"output"),rb(this,"texture"),rb(this,"image"),rb(this,"ctx2d",null),rb(this,"fbo"),rb(this,"width",0),rb(this,"height",0),rb(this,"x",0),rb(this,"y",0),rb(this,"program"),rb(this,"vertexShader"),rb(this,"fragmentShader"),rb(this,"totalFrames",0),rb(this,"dropFrames",0),rb(this,"matchInputSize",!0),rb(this,"texCoordBuffer"),rb(this,"positionBuffer"),rb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),rb(this,"cost",0),rb(this,"_canvas",null),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof uU){if(e.ctx&&t.create2d){let e=document.createElement("canvas"),t="function"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext("2d"),this.image=t,this._canvas=t}}else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(ZV),this.positionBuffer=this.createBuffer($V),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(sN){this.context.destroy(sN)}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof dU&&this.render(e)||this.context instanceof uU&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof dU){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:c,fps:l,name:s,cost:a},$C({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};nb([Qw(Zw.INIT,"connected",{sync:!0})],eU.prototype,"connect",1),nb([Qw("connected",Zw.INIT,{ignoreError:!0,sync:!0})],eU.prototype,"disconnect",1),nb([Qw([],"closed",{sync:!0})],eU.prototype,"close",1);var tU=[0,1,1,1,0,0,1,0],iU=class extends eU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),rb(this,"_intervalId",0),rb(this,"_sequence",0),rb(this,"checkGLError",!1),e instanceof uU?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(tU)}start(e){this._intervalId=rP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(rP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof dU){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),rP.clearTask(this._intervalId)}},nU=class extends iU{constructor(e,t){super(e,t),rb(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,n)},n=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,n)};e instanceof dU&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},rU=class extends nU{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},oU=class extends nU{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;QO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>r?i=n/r:(QO.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},sU=class extends eU{constructor(e,t,i){super(e,$C({name:"imageSource"},i)),this.image=t,rb(this,"_image"),rb(this,"_totalFrames",0),rb(this,"_autoResize",!1),this._autoResize=!1!==(null==i?void 0:i.autoResize)}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(oO(this.image.getVideoPlaybackQuality)&&!Uk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:i,videoHeight:n}=this.image),this.image.width=i,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);if(!this._autoResize)return!0;if(this.width===i&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},aU=class extends sU{constructor(e,t,i){let n=document.createElement("video");n.setAttribute("playsinline","playsinline"),n.setAttribute("muted",""),super(e,n,i),this._videoTrack=t,rb(this,"_mediaStream"),this.name="videoTrackSource",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play())}close(){var e;super.close(),null==(e=this._mediaStream)||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}},cU=class extends Zw{constructor(e){super(),rb(this,"frameRate"),rb(this,"_canvas"),rb(this,"log"),rb(this,"hasAlpha",!1),rb(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e){return new aU(this,e)}createVideoTrackDestination(e){return new nU(this,e)}createVideoImageSource(e,t){return new sU(this,e,t)}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},lU={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},dU=class extends cU{constructor(){super(...arguments),rb(this,"defaultProgam"),rb(this,"defaultVShader"),rb(this,"defaultFShader"),rb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",lU),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}createProgram(e,t){let i=this.ctx,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),i.getProgramParameter(n,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(n)),n}};nb([Qw(Zw.INIT,"created",{sync:!0})],dU.prototype,"create",1),nb([Qw("created",Zw.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],dU.prototype,"destroy",1);var uU=class extends cU{constructor(){super(...arguments),rb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};nb([Qw(Zw.INIT,"created",{sync:!0})],uU.prototype,"create",1),nb([Qw("created",Zw.INIT,{ignoreError:!0,sync:!0})],uU.prototype,"destroy",1);var hU=[1,0,0,0,1,1,0,1],pU=class extends eU{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof dU)try{this.setTexBuffer(hU)}catch(oN){e.destroy(oN)}else this.ctx2d&&setTimeout((e=>{e.scale(-1,1),e.translate(-this.width,0)}),0,this.ctx2d)}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},mU=class{constructor(e,t){this.node=e,this.layout=t,rb(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},_U=class extends eU{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),rb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new mU(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context instanceof dU&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:n,height:r,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:s,fps:a,name:o},$C({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof dU))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(n){}}))}},fU=class{constructor(e,t){this.createMediapipeSolutionsWasm=t,rb(this,"canvas"),rb(this,"locateFile"),rb(this,"_glName"),rb(this,"_solutionWasm"),rb(this,"ctx"),rb(this,"pl",{onResults:e=>this.onResults(e.get(0).glName)}),this.locateFile=t=>"".concat(e,"/").concat(t)}bindTexture(){var e;null==(e=this.ctx)||e.activeTexture(this.ctx.TEXTURE0),this.bindTexture2d(this._glName)}initialize(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"selfie_segmentation_landscape.tflite";return sb(this,null,(function*(){yield this.createMediapipeSolutionsWasm(this),this.canvas=e,this.createContext(e,!0,!0,{}),this._glName=this.createTexture(),this._solutionWasm=new this.SolutionWasm;let i=new this.StringList;i.push_back("segmentation_mask");let n=this.PacketListener.implement(this.pl);this._solutionWasm.attachMultiListener(i,n),i.delete(),this._solutionWasm.loadGraph(yield fetch(this.locateFile("selfie_segmentation.binarypb")).then((e=>e.arrayBuffer()))),this._solutionWasm.overrideFile("third_party/mediapipe/modules/selfie_segmentation/selfie_segmentation_landscape.tflite",yield fetch(this.locateFile(t)).then((e=>e.arrayBuffer())));let r=new this.GraphOptionChangeRequestList;return r.push_back({calculatorIndex:1,calculatorName:"",calculatorType:"GlScalerCalculator",fieldName:"flip_horizontal",valueBoolean:!1,valueNumber:0,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value",valueBoolean:!1,valueNumber:1,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"InferenceCalculator",calculatorName:"",fieldName:"use_cpu_inference",valueBoolean:!1,valueNumber:0,valueString:""}),this._solutionWasm.changeOptions(r),this}))}send(e,t){let i=new this.PacketDataList;i.pushTexture2d({stream:"input_frames_gpu",timestamp:1e3*performance.now(),glName:this._glName,width:e,height:t}),this._solutionWasm.send(i),i.delete()}close(){var e,t,i;null==(e=this.canvas)||delete e.getContext,delete this.readyPromiseResolve,delete this.readyPromiseReject,this.pl.onResults=null,delete this.onResults,null==(t=this.deleteTexture)||t.call(this,this._glName),null==(i=this._solutionWasm)||i.delete();for(let n of Object.keys(this))delete this[n]}},gU=class extends aU{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0}),rb(this,"ready",!1),rb(this,"_bgTexture"),rb(this,"_waterMarkTexture"),rb(this,"_lastMaskTexture"),rb(this,"_textureValid",!1),rb(this,"_selfieTextureValid",!1),rb(this,"_selfieSegmentation"),rb(this,"wasm"),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return sb(this,null,(function*(){let t=yield e.Wasm(),i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:n,height:r}=e.waterMark;this.wasm.setWaterMark(t,i,n,r)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._selfieSegmentation=yield e.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.ready=!0}))}onPredict(e){let t=this.context.ctx;this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image)),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,0==(1&this.totalFrames)?this._lastMaskTexture:this.texture),t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,this.width,this.height),this.useProgram(),this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.activeTexture(t.TEXTURE4),t.bindTexture(t.TEXTURE_2D,0!=(1&this.totalFrames)?this._lastMaskTexture:this.texture),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality&&!Uk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:n}=this.image;this.image.width=i,this.image.height=n;let r=!1;if(this.totalFrames)this._selfieSegmentation.bindTexture(),r=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),r=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===n&&r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&this._selfieSegmentation.send(i,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),null==(e=this.wasm)||e.close()}},TU=class extends XV.EventEmitter{constructor(e){super(),this.room=e,rb(this,"videoContext"),rb(this,"_glVideoContext"),rb(this,"_2dVideoContext"),rb(this,"destination"),rb(this,"smallVideoContext"),rb(this,"smallDestination"),rb(this,"smallTrackSource"),rb(this,"smallImageSource"),rb(this,"_isMirror",!1),rb(this,"cameraTrack"),rb(this,"cameraNode"),rb(this,"mirrorNode"),rb(this,"mixNode"),rb(this,"screenTrack"),rb(this,"screenNode"),rb(this,"selfModel",!1),rb(this,"blurRadius",3),rb(this,"Wasm"),rb(this,"waterMarkNode"),rb(this,"_waterMarkOption"),rb(this,"watermarkImageList",[]),rb(this,"_isMixScreen",!1),rb(this,"_virualBackground"),rb(this,"_bgAssetPath"),rb(this,"log",QO.createLogger({id:"vm"})),rb(this,"_checkId",0),rb(this,"_use2d",!1),rb(this,"_autoSwitchRenderMode",!0),rb(this,"_selfieSegmentation"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new uU({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirualBg(){return!!this._virualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new uU({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new dU({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(oN){this.emit("error",{reason:"create",error:oN}),this.sendCreateResult("videoCtxGl",oN)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=rP.run(PD,(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}destroy(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),rP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirualBg}get active(){return(Uk||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?KP.addFailedEvent({key:t,error:e}):KP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){if(!this._selfieSegmentation){let t=new fU(e.assetPath||"./selfie_segmentation",e.createMediapipeSolutionsWasm),i=this.getGlVideoContext();return i.available?this._selfieSegmentation=t.initialize(i._canvas,"selfie_segmentation_landscape.tflite"):Promise.reject(new Error("init virtual background failed, reason: video context unavailable"))}return this._selfieSegmentation}_setMainOutput(e){var t;let i=this.cameraTrack,{small:n,settings:r,player:o}=i;return n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new oU(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=r.width,this.smallTrackSource.height=r.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Uk&&o.setCanvas(e),i.setOutputMediaStreamTrack(e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack)}update(){return sb(this,null,(function*(){var e,t;if(this.cameraTrack&&this.cameraTrack.mediaTrack){if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this._use2d||!this._selfieSegmentation?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new rU(this.videoContext,{name:"mainDestination"})),this.cameraNode=new gU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate}if(this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new pU(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new _U(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)}}))}changeInput(e){return this.log.info("change input"),e instanceof HL?this.setScreenTrack(e):e instanceof VL?this.setCameraTrack(e):e instanceof zL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){var t;e instanceof HL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof VL&&(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource))}setCameraTrack(e){return sb(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return sb(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let n=i.getContext("2d");return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:r,width:o,height:s}=e;n.drawImage(t,i,r,o,s)})),FO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setWatermark(e){return sb(this,null,(function*(){let t;try{t=yield FO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new fb({code:mb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:n=0,width:r=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:n,width:r,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return sb(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return sb(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let n=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:n.width,height:n.height,image:n},this.update()}))}setVirtualBackground(e){return sb(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virualBackground=yield FO(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virualBackground=e.type)}else this._virualBackground=void 0;this.log.info("".concat(this._virualBackground?"start":"stop"," visual background, ").concat((null==e?void 0:e.type)||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},EU=0,SU=class extends Zw{constructor(e){super("room"),this.seq=++EU,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=QO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,lO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),lO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),lO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new zV({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new qV({room:this}),this.badCaseDetector=new QV({room:this}),this.audioManager=new GL(this),this.videoManager=new TU(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return sb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return sb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return sb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(aO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(tO(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(mV([o,o]),hN("https://".concat(o))):(n&&hN(n),r&&mV(r))}KO.once(YO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:pV.main,sched_back_domain:pV.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return sb(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let n="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(tw.INVALID_DESTROY),new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,KO.emit(YO.ROOM_DESTROY,{room:this})}schedule(e,t){return sb(this,null,(function*(){var i,n;let r=EO();try{let{isCached:o,result:s,detailCost:a}=yield hV({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:nN,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(LO(s,{keysToExclude:["username","credential"]}))),o&&KO.once(YO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=$C($C({},this.scheduleResult),s),cO(null==(i=s.config)?void 0:i.retryCount)&&nD(s.config.retryCount),aO(null==(n=s.config)?void 0:n.loggerDomain)&&hN(s.config.loggerDomain),KO.emit(YO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),KP.addSuccessEvent({key:521700,cost:EO()-r,split:50})}catch(o){throw KP.addFailedEvent({key:521700,error:o}),o}}))}},IU=ib(ab()),vU=ib(ub()),yU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=NV(n),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:PN.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:PN.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(AU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),r&&s.media.push(o.media.find((e=>"dc"===e.mid))),DV(s)},AU=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:PN.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:PN.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;a<i.video.codecs.length;a++)RU(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));RU(s,i.video.codecs[e])}else if(o)for(let a=0;a<n.video.codecs.length;a++)RU(s,n.video.codecs[a]);else RU(s,n.video.codecs[0]);return s.payloads=s.payloads.trim(),s},RU=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var CU,bU=e=>{let t=vU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===PN.AUDIO||e.type===PN.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===PN.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===PN.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),vU.default.write(t)},kU=((CU=kU||{}).TRACK="track",CU.DATA_CHANNEL_MESSAGE="data_channel_msg",CU[CU.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",CU[CU.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",CU.RECONNECTED="spc-reconnected",CU.RECONNECT_FAILED="spc-reconnect-failed",CU.ERROR="error",CU.SEI_MESSAGE="sei-message",CU),NU=0,DU=!1,OU=new Set,wU=1,PU=class extends IU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),rb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),rb(this,"currentState","DISCONNECTED"),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_peerConnection",null),rb(this,"_datachannel",null),rb(this,"_enableCustomMessage"),rb(this,"_log"),rb(this,"_downlinkMIDMap",new Map),rb(this,"_downlinkMIDUserIDMap",new Map),rb(this,"_reconnectionTimer",-1),rb(this,"reconnectionCount",0),rb(this,"_clientAbility",null),rb(this,"_serverAbility",null),rb(this,"addDownlinkQueue",new Set),rb(this,"removeDownlinkQueue",new Set),rb(this,"_parsedAnswer",null),rb(this,"_updateSDPPromise",null),rb(this,"_waitForPCConnectedPromise"),rb(this,"_waitForPCConnectedPromiseReject",null),rb(this,"_isSDPLogged",!1),rb(this,"seiCodec",null),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=QO.createLogger({id:"spc".concat(wU++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Vw&&(this._log.info("create sei codec"),this.seiCodec=new vV(this,this._log),this.seiCodec.onSEIMessage=e=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(e.mid),data:e.data,seiPayloadType:e.seiPayloadType,streamType:e.streamType})})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return null!=(e=this._serverAbility)&&e.useVp8?"vp8":"h264"}get isUsingH264(){return"h264"===this.videoCodec}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=NV(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var n;if(e.ssrcs&&!sO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return sb(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Vw,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new MU(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(PN.AUDIO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=((e,t)=>{var i,n;let r=NV(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||"",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||""),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||"";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(oN){throw this._log.error("initialize failed ".concat(oN)),oN}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return sb(this,null,(function*(){var i;try{if("CONNECTED"===this.currentState)return;let n=EO(),r={type:"answer",sdp:yU({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||KP.addSuccessEvent({key:521703,cost:EO()-n}),null==(i=this.seiCodec)||i.handleEncodedStreams()}catch(n){let t=n instanceof fb&&n.code===mb.API_CALL_ABORTED;throw t||this._log.error("connect failed: ".concat(n),e),this.reset(),!t&&!this.isReconnecting&&(KP.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}}))}reconnect(){return sb(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(Nx,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:eV,responseCommand:Px.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new fb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),KP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),KO.emit(YO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(oN){if(!this.isReconnecting)return;if(null!=oN&&oN.message.includes("timeout")){let e=nO(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(null==oN?void 0:oN.code," ").concat(oN)),KP.addFailedEvent({key:521704,error:oN}),this.reconnectionCount>=rD()&&this._log.warn("SDK has tried reconnect for ".concat(rD()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return sb(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Nx,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===tD.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(i)),e.target.connectionState===tD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===tD.FAILED||e.target.connectionState===tD.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===tD.CONNECTED||e.target.connectionState===tD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),KO.emit(YO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return eD;let e=null;return kw()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,bw()&&0!==this._peerConnection.getReceivers().length&&e?e.state:eD):eD}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(kU.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(Sw(i)){let t=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&JD(t.networkType)),n&&this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{KO.off(YO.LEAVE_SUCCESS,n,this),this.off(kU.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{r();let e=new fb({code:mb.API_CALL_TIMEOUT,message:"connection timeout"});var i;NU+=1,i=this._signalChannel.isConnected,NU>2&&!DU&&0===OU.size&&i&&(this._log.warn("firewall restrition"),DU=!0,this.emit(kU.FIREWALL_RESTRICTION)),t(e)}),ED);KO.on(YO.LEAVE_SUCCESS,n,this),this.on(kU.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return sb(this,null,(function*(){var t;if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),null==(t=this.seiCodec)||t.handleEncodedStreams(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(sN){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=PN.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(PN.AUDIO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=NV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=AU({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:NV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}r.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(n)},{id:t.audio,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-audio")}],o.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(n)},{id:t.video,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(n)},{id:t.videoRtx,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],s.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY;let c="".concat(n,"-aux");s.ssrcs=[{id:t.auxiliary,attribute:"cname",value:c},{id:t.auxiliary,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[r.mid,o.mid,s.mid]),this._downlinkMIDUserIDMap.set(r.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i)}removeDownlink(e,t){return sb(this,null,(function*(){if(!this._downlinkMIDMap.has(t)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let e=this._downlinkMIDMap.get(t),i=!1;this._peerConnection.getTransceivers().forEach((t=>{null!=e&&e.includes(Number(t.mid))&&(i=!0,t.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=NV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((t=>{null!=e&&e.includes(Number(t.mid))&&(i=!0,t.direction="inactive",t.ssrcs=[],t.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(t),null==e||e.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(t,") done"))}))}setBandwidth(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(Lw()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&n?o=n:3===s&&r&&(o=r),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),r&&e[3].track&&(o=this.setStartBitrate(3,r)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth".concat(o))}}))}setStartBitrate(e,t){var i,n;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=NV(this._peerConnection.remoteDescription.sdp)),null==(n=this._parsedAnswer.media[e])||!n.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=NV(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=NV(this._peerConnection.remoteDescription.sdp));let s=Vb?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:Vb?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:Vb?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:Vb?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:Vb?1e3*i:i}]),n&&(o.media[2].bandwidth=[{type:s,limit:Vb?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:Vb?1e3*n:n}]),r&&(o.media[3].bandwidth=[{type:s,limit:Vb?1e3*r:r}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:Vb?1e3*r:r}]);let a={type:"offer",sdp:DV(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=DV(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,n)=>sb(this,null,(function*(){var r,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(CU){this._log.error(CU),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(r=this._peerConnection.localDescription)?void 0:r.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,n(CU)}})))),this._updateSDPPromise}filterSDPDirection(){return NV(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:bU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var i;null==(i=this.seiCodec)||i.push(e,t)}};nb([wL("reconnect")],PU.prototype,"startReconnection",1),nb([OL()],PU.prototype,"updateSDP",1);var LU=class{constructor(e){rb(this,"tag"),rb(this,"len"),rb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},MU=class{constructor(e){rb(this,"tinyId"),rb(this,"data");let t=new DataView(e),i=0,n=[];for(;i<t.byteLength;){let r=t.getUint16(i+2),o=new LU(new Uint8Array(e).slice(i,i+2+2+r).buffer);n.push(o),i+=4+r}n.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},xU=new Set;function VU(){let e=Math.floor(4294967296*Math.random());return xU.has(e)?VU():(xU.add(e),e)}var UU=ib(ab()),FU=class extends UU.default{constructor(e){super(),rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_currentState","DISCONNECTED"),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=QO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Vw&&(this._sei=new vV(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(KO.emit(YO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},BU=class extends FU{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Nw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===PN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new fb({code:mb.NOT_SUPPORTED_H264,message:rw({key:ew.NOT_SUPPORTED_H264ENCODE})});Pb&&115===Ok()&&n.profile.width*n.profile.height<=230400&&(t._log.warn("fallback video to 480p"),n.setProfile(ON["480p_2"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n,r?(h.auxVideo=!0,p.auxVideo=n.muted):(h.bigVideo=!0,p.bigVideo=n.muted)}if(t._isPublishingAux=r,n&&!r&&n.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponse({command:iV,responseCommand:Px.SPC_PUBLISH_RESULT,data:ZC($C({},t.singlePC.uplinkSSRC),{state:h,muteState:p})}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:u,isAuxiliary:r}),null==(e=t.singlePC.seiCodec)||e.handleEncodedStreams(),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r)n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i);else{if(n){t.localMainVideoTrack=n;let{scaleResolutionDownBy:e}=n;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(o=t.localMainAudioTrack)?void 0:o.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(l=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:l.bitrate,auxVideo:null==(d=t.localAuxVideoTrack)?void 0:d.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;if(!Dw())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e)}let d=this.setTransceiverDirection(LN.SENDONLY,l);return c.push(d),Promise.all(c)}enableSmall(e){return sb(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(LN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(LN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(LN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Bx,data:t,responseCommand:Px.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:Hx,commandDesc:"unpublish",responseCommand:Px.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===mb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Mw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Zx,data:this._mediaSettings,responseCommand:Px.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?PN.AUXILIARY:PN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),Nw()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield n[0].sender.replaceTrack(e.outMediaTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===LN.INACTIVE&&(yield this.setTransceiverDirection(LN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?PN.AUXILIARY:PN.MAIN," stream")),Nw()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(LN.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Vb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(LN.INACTIVE,"|").concat(LN.RECVONLY,"|").concat(LN.SENDONLY,")")))&&o++,t.includes(o)){if(e===LN.INACTIVE&&i.includes("a=".concat(LN.RECVONLY)))return n=!0,"a=".concat(e);if(e===LN.SENDONLY&&i.includes("a=".concat(LN.INACTIVE)))return n=!0,"a=".concat(LN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!n||i.find((e=>e.track===n)))return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(n.kind," track on ").concat(r?PN.AUXILIARY:PN.MAIN," stream")),n.kind===PN.AUDIO&&i[0]&&(yield i[0].replaceTrack(n)),n.kind===PN.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(n)),r&&i[3]&&(yield i[3].replaceTrack(n)))}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===PN.AUDIO?e.audio=i:"big"===r?e.bigVideo=i:"small"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:Ux,responseCommand:Px.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&KO.emit(YO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:PN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===PN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===PN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===PN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===PN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===pD?(this._log.error(tw.NOT_SUPPORTED_H264ENCODE),new fb({code:mb.NOT_SUPPORTED_H264,message:rw({key:ew.NOT_SUPPORTED_H264ENCODE})})):new fb({code:mb.UNKNOWN,message:rw({key:ew.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Px.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return sb(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};function HU(e){return Object.keys(e).filter((t=>e[t]))}var jU=class extends FU{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new KL(this._room,this),this.remoteVideoTrack=new zL(this._room,this),this.remoteAuxiliaryTrack=new YL(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return AO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===PN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=PN.AUDIO;i.kind===PN.VIDEO&&(r=n===PN.MAIN?PN.VIDEO:PN.AUXILIARY);let o=this.remoteAudioTrack;r===PN.VIDEO?o=this.remoteVideoTrack:r===PN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info("subscribe ".concat(t," ").concat(HU(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e)}catch(sN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(sN.message," ").concat(JSON.stringify(this.muteState))),new fb({code:mb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):sN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(n," stream already unsubscribed"));let r=$C({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1}}));let o="subscribe_change";Object.values(r).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(n," [").concat(HU(r),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Gx,r=Px.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Wx,r=Px.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:rw({key:ew.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:VU(),bigVideoSsrc:VU(),bigVideoRtxSsrc:VU(),auxVideoSsrc:VU(),auxVideoRtxSsrc:VU()},{audioSsrc:r,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:r,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let n=yield e._signalChannel.sendWaitForResponseWithRetry({command:nV,responseCommand:Px.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==n.data.code)throw new fb({code:n.data.code,message:n.data.message})}catch(n){throw yield e.removeDownlink(),n}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return sb(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};nb([kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this.off("closed",r),n(new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.CONNECTION_ABORTED,data:e})}))};this.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this.off("closed",r)}))}))}))],jU.prototype,"subscribe",1);var GU=jU;var WU,{isString:JU,isPlainObject:KU,isUndefined:zU,getNetworkType:YU,getTerminalType:qU,isEmpty:QU}=Sb,XU=class extends SU{constructor(e){super(e),this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this._signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=Ow,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new FV(this,this._log),this.userManager=new uM(this.userId,this._log),this._version=nN,this.sdpSemantics=hD,zU(e.sdpSemantics)?ZO.isUnifiedPlanDefault()&&(this.sdpSemantics=uD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(YU())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!zU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!zU(e.enableSPC)&&Ow&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return sb(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var n in e)zC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&JC)for(var n of JC(e))t.indexOf(n)<0&&YC.call(e,n)&&(i[n]=e[n]);return i})(e,[]);KO.emit(YO.REMOTE_PUBLISH_STATE_CHANGED,$C({room:this},t)),this.emit("remote-publish-state-changed",$C({},t))})),this._joinOptions=e,new Promise(((t,i)=>sb(this,null,(function*(){this._joinReject=i;try{this.checkDestroy();let[,i]=yield Promise.all([this.initialize(),this.initSinglePC()]);yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(n){i(n)}this._joinReject=null}))))}))}initSinglePC(){return sb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new PU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(oN){this.singlePC.close(),this.singlePC=null}}}))}doJoin(e,t){return new Promise(((i,n)=>sb(this,null,(function*(){var r,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(bx,(e=>{this.clearJoinTimeout(),KO.emit(YO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),n(e)})),lO(null==(o=null==(r=this.scheduleResult)?void 0:r.config)?void 0:o.singlePC)&&Ow&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:qU(),netType:KD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{n(new fb({code:mb.JOIN_ROOM_FAILED,message:rw({key:ew.JOIN_ROOM_TIMEOUT})}))}),c),KO.emit(YO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?tV:Mx,a),this._signalChannel.once(Px.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:r,data:o,tinyId:s}=e.data;KO.emit(YO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(r)),n(new fb({code:mb.JOIN_ROOM_FAILED,extraCode:t,message:rw({key:ew.JOIN_ROOM_FAILED,data:{error:r,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),i.push(this._signalChannel.connect())),yield Promise.all(i),yield this.doJoin(ZC($C({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),sP.logSuccessEvent({userId:this.userId,eventType:aD.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(kU.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof BU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(kU.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof UV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(oD){this._log.warn("reJoin fail ".concat(oD)),this.reset(),sP.logFailedEvent({userId:this.userId,eventType:aD.REJOIN,error:oD}),this.emit("error",new fb({code:mb.JOIN_ROOM_FAILED,message:rw({key:ew.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return sb(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...TV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new EV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._networkQuality||(this._networkQuality=new jV({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(jV.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),DP(this,this._signalChannel).add(kx,(e=>{KO.emit(YO.SIGNAL_CONNECTION_STATE_CHANGED,$C({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(Dx,(e=>{this.reset(),this.emit("error",e)})).add(Px.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n})})).add(Px.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(Px.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(Px.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(sP.uploadEvent({log:"stat-banned:".concat(i),userId:this.userId}),"user_time_out"===i)return this._log.warn("".concat(i," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),this.reset(),this.emit("banned",{reason:i})})),this._signalChannel.once(Cx,(e=>{this.tinyId=e.signalInfo.tinyId,KO.emit(YO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),KO.emit(YO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&KO.emit(YO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this._signalChannel=e,e||OP(this)}leave(){return sb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(oD){}this._log.info("leave() => leaving room"),KO.emit(YO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(xx)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=rP.run(OD,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),rP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return sb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if(cM.has(e)){let t=cM.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return cM.delete(e),t}return[]}(this.userId):[],r=$C({str_sdk_version:iN,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:KD()},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);KO.emit(YO.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(Vx,r),this.emit("heartbeat-report",ZC($C({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n}}));KO.emit(YO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:n}=e,r=new(this.singlePC?GU:LV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit("remote-published",r)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==mb.ICE_TRANSPORT_ERROR&&(i===mb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",ZC($C({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=rP.run(OD,this.syncUserList.bind(this)))}stopSyncUserListInterval(){rP.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this._signalChannel)&&e.isConnected?this._signalChannel.sendWaitForResponse({command:Xx,responseCommand:Px.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n}}));throw rw({key:ew.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Px.USER_LIST_RES,code:i,message:n}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!CV)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===tD.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof bV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===tD.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return sb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),sP.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(!1),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new UV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach((e=>{let t=new LV({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return sb(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:$x,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:Px.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this._signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:n}=t.data;if(0!==i)throw new fb({code:mb.SWITCH_ROLE_FAILED,message:rw({key:ew.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e})).catch((e=>{throw e instanceof fb&&e.getCode()===mb.API_CALL_TIMEOUT&&(e=new fb({code:mb.SWITCH_ROLE_FAILED,message:rw({key:ew.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof xL&&(t instanceof jL?i.audio=t:e.audio=t),t instanceof VL&&(t instanceof HL&&2===t.mediaType?i.video=t:e.video=t)}));let n=QU(e),r=QU(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new BU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new UV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",ZC($C({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==mb.ICE_TRANSPORT_ERROR&&(t===mb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");n||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),r||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof xL&&(t instanceof jL?i.audio=t:e.audio=t),t instanceof VL&&(t instanceof HL&&2===t.mediaType?i.video=t:e.video=t))}));try{let n=t.map((e=>e.kind)).join(",");QU(e)||(this._log.info("unpublish() => main ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),QU(i)||(this._log.info("unpublish() => aux ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(n){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&Pw()?this.uplinkConnection.replaceTrack(e).then((t=>{KO.emit(YO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return sb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return sb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:PN.VIDEO,videoType:PN.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let r=$C({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),KO.emit(YO.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info("subscribe() => ".concat(e," ").concat(n," [").concat(OV(r),"] prev: [").concat(OV(i.subscribeState),"]")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),KO.emit(YO.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}catch(aN){let i=aN instanceof fb?aN.getCode():mb.UNKNOWN,r=aN;throw aN instanceof fb?i===mb.REMOTE_STREAM_NOT_EXIST&&(r=new fb({code:mb.API_CALL_ABORTED,message:rw({key:ew.API_CALL_ABORTED,data:{message:aN.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new fb({code:i,message:rw({key:ew.SUBSCRIBE_FAILED,data:{message:aN.message,userId:e,streamType:n}})}),this._log.error(r)),r}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n})}catch(aN){this._log.warn("unsubscribe() => failed ".concat(aN))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),KO.emit(YO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void rP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),KO.emit(YO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&rP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=rP.run(wD,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit("audio-volume",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return sb(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return sb(this,null,(function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)"main"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),"auxiliary"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Sb.getTurnServer(e)))):Sb.isPlainObject(e)&&i.push(Sb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:qx,data:e,timeout:5e3,responseCommand:Px.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:Qx,data:e,timeout:5e3,responseCommand:Px.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?Jx:zx,data:e,timeout:5e3,responseCommand:t?Px.START_PUBLISH_TENCENT_CDN_RES:Px.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?Kx:Yx,data:e,timeout:5e3,responseCommand:t?Px.STOP_PUBLISH_TENCENT_CDN_RES:Px.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:rV,data:e,timeout:5e3,responseCommand:Px.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Sb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this._signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return sb(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:n,hasVideo:r}}=e;if(!n&&!r||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&n)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!n&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(ND-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=ND}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(ND-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ND};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(JU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!zU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new fb({code:mb.INVALID_PARAMETER,message:rw({key:ew.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!zU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new fb({code:mb.INVALID_PARAMETER,message:rw({key:ew.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!zU(e.userDefinePushArgs)){if(!(JU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new fb({code:mb.INVALID_PARAMETER,message:rw({key:ew.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}QU(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}};return nb([Ix(["left",Ax.INIT],"joined"),aV({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),uV(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),kL((e=>{let t=new px;return function(i,n,r){return sb(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new fb({code:mb.INVALID_OPERATION,message:rw({key:ew.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),KO.emit(YO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield ZO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Sb.getEnv();s||(s=yN.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(MN.OLD_CLOUD_LADDER)?s=yN.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(MN.WEBRTC)&&(s=yN.WEBRTC))),sP.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),mx.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ZO.isWebRTCSupported()||!a&&!c)throw new fb({code:mb.NOT_SUPPORTED,message:rw({key:ew.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Sb.getEnv()&&(yield this.schedule(o,r));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Sb.performanceNow(),KO.emit(YO.JOIN_SUCCESS,{room:this}),sP.uploadEvent({log:"stat-conv-".concat(Number(Kk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),KO.emit(YO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],XU.prototype,"join",1),nb([Ix("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),kL((e=>function(){return sb(this,null,(function*(){KO.emit(YO.LEAVE_START,{room:this}),yield e.call(this),KO.emit(YO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),wL("leave room"),cV({fnName:"publish",validateArgs:!1}),cV({fnName:"unsubscribe",validateArgs:!1})],XU.prototype,"leave",1),nb([OL(),kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;KO.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),aV({settings:{retries:rD,timeout:e=>nO(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),KO.emit(YO.PUBLISH_FAILED,{room:this}))}})],XU.prototype,"publish",1),nb([cV({fnName:"publish"}),(WU="api-call",function(e,t,i){let n=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=NL.get(this);if(r){let e=r.filter(((e,i)=>{if(0===i)return!0;let n=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(n=!1)})),!n||(e.reject(new fb({code:mb.API_CALL_ABORTED,message:WU})),!1)}));NL.set(this,e)}return n.apply(this,t)},i}),OL(),kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>e.unpublish())),r}))],XU.prototype,"unpublish",1),nb([PL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),kL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(r))),r})),aV({settings:{retries:rD,timeout:e=>nO(e)},onError(e,t,i,n){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),KO.emit(YO.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}))}})],XU.prototype,"subscribe",1),nb([cV({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.singlePC||t.forEach((e=>{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close("you unsubscribed")}))}}),PL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],XU.prototype,"unsubscribe",1),hx.create=hx._create.bind(hx,XU),hx}));
1
+ !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).TRTC=t()}(this,(function(){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:{},i=function(e){try{return!!e()}catch(t){return!0}},n=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=n,o=Function.prototype,s=o.call,a=r&&o.bind.bind(s,s),c=r?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,S=TypeError,I=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,y=I,A=function(e){return v(y(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},N=C,D=Object.defineProperty,O=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0})}catch(i){N[e]=t}return t},w=O,P="__core-js_shared__",L=C[P]||w(P,{}),M=L;(k.exports=function(e,t){return M[e]||(M[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=I,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),G=Object.hasOwn||function(e,t){return j(H(e),t)},W=c,J=0,z=Math.random(),K=W(1..toString),Y=function(e){return"Symbol("+(void 0===e?"":e)+")_"+K(++J+z,36)},q="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=q,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=G,le=Y,de=oe,ue=se,he=C.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,_e=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===Ie}:function(e){return"object"==typeof e?null!==e:Se(e)},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Le=function(e){return Pe?we.createElement(e):{}},Me=Le,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Me("div"),"a",{get:function(){return 7}}).a})),Ve=n,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},Ge=c({}.isPrototypeOf),We=je,Je=Ee,ze=Ge,Ke=Object,Ye=se?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&ze(t.prototype,Ke(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=Ye,ut=nt,ht=function(e,t){var i,n;if("string"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if("string"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,mt);if(n){if(void 0===t&&(t="default"),i=ct(n,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=Ye,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,St=xe,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Nt="writable";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Nt in i&&!i[Nt]){var n=Ct(e,t);n&&n[Nt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i)}catch(n){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Dt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Dt)(t)},Pt=wt,Lt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Mt=Lt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Mt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Lt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Gt=function(e){return jt(e.length)},Wt=A,Jt=Ut,zt=Gt,Kt=function(e){return function(t,i,n){var r,o=Wt(t),s=zt(o),a=Jt(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}},Yt={includes:Kt(!0),indexOf:Kt(!1)},qt={},Qt=G,Xt=A,$t=Yt.indexOf,Zt=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt(Zt,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri)},si=ke,ai=Ne,ci=De,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e};var hi,pi=je("document","documentElement"),mi=Y,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,Si=qt,Ii=pi,vi=Le,yi="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ni=function(){try{hi=new ActiveXObject("htmlfile")}catch(r){}var e,t,i;Ni="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Ni[yi][Ei[n]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},Oi=_e,wi=Di,Pi=De.f,Li=Oi("unscopables"),Mi=Array.prototype;null==Mi[Li]&&Pi(Mi,Li,{configurable:!0,value:wi(null)});var xi,Vi,Ui,Fi=function(e){Mi[Li][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=De,zi=Wi,Ki=ke?function(e,t,i){return Ji.f(e,t,zi(1,i))}:function(e,t,i){return e[t]=i,e},Yi=Gi,qi=C,Qi=ve,Xi=Ki,$i=G,Zi=L,en=fi,tn=qt,nn="Object already initialized",rn=qi.TypeError,on=qi.WeakMap;if(Yi||Zi.state){var sn=Zi.state||(Zi.state=new on);sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,xi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t},Vi=function(e){return sn.get(e)||{}},Ui=function(e){return sn.has(e)}}else{var an=en("state");tn[an]=!0,xi=function(e,t){if($i(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t},Vi=function(e){return $i(e,an)?e[an]:{}},Ui=function(e){return $i(e,an)}}var cn={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rn("Incompatible receiver, "+e+" required");return i}}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable}:un;var mn=ke,_n=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=xe,vn=Object.getOwnPropertyDescriptor;ln.f=mn?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t)}catch(i){}if(Sn(e,t))return gn(!_n(fn.f,e,t),e[t])};var yn={},An={get exports(){return yn},set exports(e){yn=e}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Nn=Cn(bn,"name"),Dn={EXISTS:Nn,PROPER:Nn&&"something"===function(){}.name,CONFIGURABLE:Nn&&(!Rn||Rn&&kn(bn,"name").configurable)},On=Ee,wn=L,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e)});var Ln=wn.inspectSource,Mn=c,xn=i,Vn=Ee,Un=G,Fn=ke,Bn=Dn.CONFIGURABLE,Hn=Ln,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,zn=Mn("".slice),Kn=Mn("".replace),Yn=Mn([].join),qn=Fn&&!xn((function(){return 8!==Jn((function(){}),"length",{value:8}).length})),Qn=String(String).split("String"),Xn=An.exports=function(e,t,i){"Symbol("===zn(Wn(t),0,7)&&(t="["+Kn(Wn(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Un(e,"name")||Bn&&e.name!==t)&&(Fn?Jn(e,"name",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,"arity")&&e.length!==i.arity&&Jn(e,"length",{value:i.arity});try{i&&Un(i,"constructor")&&i.constructor?Fn&&Jn(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(r){}var n=jn(e);return Un(n,"source")||(n.source=Yn(Qn,"string"==typeof t?t:"")),e};Function.prototype.toString=Xn((function(){return Vn(this)&&Gn(this).source||Hn(this)}),"toString");var $n=Ee,Zn=De,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if($n(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t]}catch(s){}r?e[t]=i:Zn.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},nr={},rr=ti,or=ii.concat("length","prototype");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or)};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,mr=c([].concat),_r=dr("Reflect","ownKeys")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?mr(t,i(e)):t},fr=G,gr=_r,Tr=ln,Er=De,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s<n.length;s++){var a=n[s];fr(e,a)||i&&fr(i,a)||r(e,a,o(t,a))}},Ir=i,vr=Ee,yr=/#|\.prototype\./,Ar=function(e,t){var i=Cr[Rr(e)];return i==kr||i!=br&&(vr(t)?Ir(t):!!t)},Rr=Ar.normalize=function(e){return String(e).replace(yr,".").toLowerCase()},Cr=Ar.data={},br=Ar.NATIVE="N",kr=Ar.POLYFILL="P",Nr=Ar,Dr=C,Or=ln.f,wr=Ki,Pr=ir,Lr=O,Mr=Sr,xr=Nr,Vr=function(e,t){var i,n,r,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Dr:l?Dr[a]||Lr(a,{}):(Dr[a]||{}).prototype)for(n in t){if(o=t[n],r=e.dontCallGetSet?(s=Or(i,n))&&s.value:i[n],!xr(c?n:a+(l?".":"#")+n,e.forced)&&void 0!==r){if(typeof o==typeof r)continue;Mr(o,r)}(e.sham||r&&r.sham)&&wr(o,"sham",!0),Pr(i,n,o,e)}},Ur=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fr=G,Br=Ee,Hr=B,jr=Ur,Gr=fi("IE_PROTO"),Wr=Object,Jr=Wr.prototype,zr=jr?Wr.getPrototypeOf:function(e){var t=Hr(e);if(Fr(t,Gr))return t[Gr];var i=t.constructor;return Br(i)&&t instanceof i?i.prototype:t instanceof Wr?Jr:null},Kr=i,Yr=Ee,qr=ve,Qr=zr,Xr=ir,$r=_e("iterator"),Zr=!1;[].keys&&("next"in(lr=[].keys())?(cr=Qr(Qr(lr)))!==Object.prototype&&(ar=cr):Zr=!0);var eo=!qr(ar)||Kr((function(){var e={};return ar[$r].call(e)!==e}));eo&&(ar={}),Yr(ar[$r])||Xr(ar,$r,(function(){return this}));var to={IteratorPrototype:ar,BUGGY_SAFARI_ITERATORS:Zr},io=De.f,no=G,ro=_e("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!no(e,ro)&&io(e,ro,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Di,co=Wi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ao(so,{next:co(+!n,i)}),lo(e,r,!1),uo[r]=ho,e},mo=c,_o=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return mo(_o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(n){}},So=Ce,Io=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(n){}return function(i,n){return So(i),Io(n),t?e(i,n):i.__proto__=n,i}}():void 0),yo=Vr,Ao=Fe,Ro=Ee,Co=po,bo=zr,ko=vo,No=oo,Do=Ki,Oo=ir,wo=Bi,Po=Dn.PROPER,Lo=Dn.CONFIGURABLE,Mo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=_e("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,n,r,o,s){Co(i,t,n);var a,c,l,d=function(e){if(e===r&&_)return _;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||r&&p[r],_=!xo&&m||d(r),f="Array"==t&&p.entries||m;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Mo&&(ko?ko(a,Mo):Ro(a[Vo])||Oo(a,Vo,Ho)),No(a,u,!0)),Po&&r==Fo&&m&&m.name!==Fo&&(Lo?Do(p,"name",Fo):(h=!0,_=function(){return Ao(m,this)})),r)if(c={values:d(Fo),keys:o?_:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&Oo(p,l,c[l]);else yo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&Oo(p,Vo,_,{name:r}),wo[t]=_,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,zo=Bi,Ko=cn,Yo=De.f,qo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=Ko.set,es=Ko.getterFor($o),ts=qo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),is=zo.Arguments=zo.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{Yo(is,"name",{value:"values"})}catch(nF){}var ns={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},rs=Le("span").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=Ki,hs=_e,ps=hs("iterator"),ms=hs("toStringTag"),_s=ds.values,fs=function(e,t){if(e){if(e[ps]!==_s)try{us(e,ps,_s)}catch(nF){e[ps]=_s}if(e[ms]||us(e,ms,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i])}catch(nF){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=yn,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,ys=Is,As=ke,Rs=_e("species"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&ys(t,Rs,{configurable:!0,get:function(){return this}})},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ds={};Ds[_e("toStringTag")]="z";var Os="[object z]"===String(Ds),ws=Ee,Ps=h,Ls=_e("toStringTag"),Ms=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=Os?Ps: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(nF){}}(t=Ms(e),Ls))?i:xs?Ps(t):"Object"==(n=Ps(t))&&ws(t.callee)?"Arguments":n},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Ln,Gs=function(){},Ws=[],Js=je("Reflect","construct"),zs=/^\s*(?:class|function)\b/,Ks=Us(zs.exec),Ys=!zs.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(nF){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ys||!!Ks(zs,js(e))}catch(nF){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return qs(qs.call)||!qs(Object)||!qs((function(){e=!0}))||e}))?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=_e("species"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i)},ua=n,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(q),ba=C,ka=_a,Na=va,Da=Ee,Oa=G,wa=i,Pa=pi,La=ya,Ma=Le,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Ga=ba.Function,Wa=ba.MessageChannel,Ja=ba.String,za=0,Ka={},Ya="onreadystatechange";wa((function(){Xs=ba.location}));var qa=function(e){if(Oa(Ka,e)){var t=Ka[e];delete Ka[e],t()}},Qa=function(e){return function(){qa(e)}},Xa=function(e){qa(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Da(e)?e:Ga(e),i=La(arguments,1);return Ka[++za]=function(){ka(t,void 0,i)},$s(za),za},Ba=function(e){delete Ka[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Wa&&!Va?(ea=(Zs=new Wa).port2,Zs.port1.onmessage=Xa,$s=Na(ea.postMessage,ea)):ba.addEventListener&&Da(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!wa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=Ya in Ma("script")?function(e){Pa.appendChild(Ma("script"))[Ya]=function(){Pa.removeChild(this),qa(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,nc,rc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(q)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(q),lc=C,dc=va,uc=ln.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,Ic=lc.Promise,vc=uc(lc,"queueMicrotask"),yc=vc&&vc.value;if(!yc){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch(nF){throw Ac.head&&tc(),nF}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&Ic&&Ic.resolve?((rc=Ic.resolve(void 0)).constructor=Ic,oc=dc(rc.then,rc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,nc=Ec.createTextNode(""),new Tc(Rc).observe(nc,{characterData:!0}),tc=function(){nc.data=ic=!ic}),yc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=yc,bc=function(e){try{return{error:!1,value:e()}}catch(nF){return{error:!0,value:nF}}},kc=C.Promise,Nc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!Nc&&!Ts&&"object"==typeof window&&"object"==typeof document,Oc=C,wc=kc,Pc=Ee,Lc=Nr,Mc=Ln,xc=_e,Vc=Dc,Uc=Nc,Fc=ie;wc&&wc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(Oc.PromiseRejectionEvent),Gc=Lc("Promise",(function(){var e=Mc(wc),t=e!==String(wc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new wc((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=n,!(Hc=i.then((function(){}))instanceof n))return!0}return!t&&(Vc||Uc)&&!jc})),Wc={CONSTRUCTOR:Gc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},zc=et,Kc=TypeError,Yc=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw Kc("Bad Promise constructor");t=e,i=n})),this.resolve=zc(t),this.reject=zc(i)};Jc.f=function(e){return new Yc(e)};var qc,Qc,Xc,$c=Vr,Zc=Ts,el=C,tl=Fe,il=ir,nl=vo,rl=oo,ol=Cs,sl=et,al=Ee,cl=ve,ll=Ns,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(nF){}},ml=bc,_l=sc,fl=cn,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,Il=Wc.REJECTION_EVENT,vl=Wc.SUBCLASSING,yl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Nl=el.document,Dl=el.process,Ol=Tl.f,wl=Ol,Pl=!!(Nl&&Nl.createEvent&&el.dispatchEvent),Ll="unhandledrejection",Ml=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),r=!0)),i===e.promise?l(kl("Promise-chain cycle")):(n=Ml(i))?tl(n,i,c,l):c(i)):l(o)}catch(nF){d&&!r&&d.exit(),l(nF)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,n=e.reactions;i=n.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var n,r;Pl?((n=Nl.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),el.dispatchEvent(n)):n={promise:t,reason:i},!Il&&(r=el["on"+e])?r(n):e===Ll&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,n=e.value;if(Bl(e)&&(t=ml((function(){Zc?Dl.emit("unhandledRejection",n,i):Ul(Ll,i,n)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(n){e(t,n,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var n=Ml(t);n?hl((function(){var i={done:!1};try{tl(n,t,jl(Wl,i,e),jl(Gl,i,e))}catch(nF){Gl(i,nF,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(nF){Gl({done:!1},nF,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(qc,this);var t=yl(this);try{e(jl(Wl,t),jl(Gl,t))}catch(nF){Gl(t,nF)}}).prototype,(qc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=yl(this),n=Ol(dl(this,Cl));return i.parent=!0,n.ok=!al(e)||e,n.fail=al(t)&&t,n.domain=Zc?Dl.domain:void 0,0==i.state?i.reactions.add(n):hl((function(){xl(n,i)})),n.promise})),Qc=function(){var e=new qc,t=yl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=Ol=function(e){return e===Cl||undefined===e?new Qc(e):wl(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,vl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(nF){}nl&&nl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),rl(Cl,El,!1),ol(El);var Jl=Bi,zl=_e("iterator"),Kl=Array.prototype,Yl=function(e){return void 0!==e&&(Jl.Array===e||Kl[zl]===e)},ql=Vs,Ql=nt,Xl=T,$l=Bi,Zl=_e("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[ql(e)]},td=Fe,id=et,nd=Ce,rd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return nd(td(i,e));throw sd(rd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=nt,ud=function(e,t,i){var n,r;ld(e);try{if(!(n=dd(e,"return"))){if("throw"===t)throw i;return i}n=cd(n,e)}catch(nF){r=!0,n=nF}if("throw"===t)throw i;if(r)throw n;return ld(n),i},hd=va,pd=Fe,md=Ce,_d=Qe,fd=Yl,gd=Gt,Td=Ge,Ed=ad,Sd=ed,Id=ud,vd=TypeError,yd=function(e,t){this.stopped=e,this.result=t},Ad=yd.prototype,Rd=function(e,t,i){var n,r,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return n&&Id(n,"normal",e),new yd(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=Sd(e)))throw vd(_d(e)+" is not iterable");if(fd(r)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1)}n=Ed(e,r)}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value)}catch(nF){Id(n,"throw",nF)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Nd[Cd]=function(){return this},Array.from(Nd,(function(){throw 2}))}catch(nF){}var Dd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(nF){}return i},Od=kc,wd=Wc.CONSTRUCTOR||!Dd((function(e){Od.all(e).then(void 0,(function(){}))})),Pd=Fe,Ld=et,Md=Jc,xd=bc,Vd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Md.f(t),n=i.resolve,r=i.reject,o=xd((function(){var i=Ld(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ud=Vr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var zd=Fe,Kd=et,Yd=Jc,qd=bc,Qd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{race:function(e){var t=this,i=Yd.f(t),n=i.reject,r=qd((function(){var r=Kd(t.resolve);Qd(e,(function(e){zd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Xd=Fe,$d=Jc;Vr({target:"Promise",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},nu=Vr,ru=Wc.CONSTRUCTOR,ou=iu;je("Promise"),nu({target:"Promise",stat:!0,forced:ru},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e},du=ve,uu=h,hu=_e("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},mu=Vs,_u=String,fu=function(e){if("Symbol"===mu(e))throw TypeError("Cannot convert a Symbol value to a string");return _u(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in yu||Su(e,"flags")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Nu=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=De.f,wu=i,Pu=C.RegExp,Lu=wu((function(){var e=Pu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Mu=i,xu=C.RegExp,Vu=Mu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Uu=ke,Fu=C,Bu=c,Hu=Nr,ju=lu,Gu=Ki,Wu=nr.f,Ju=Ge,zu=pu,Ku=fu,Yu=Au,qu=Du,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=ir,$u=i,Zu=G,eh=cn.enforce,th=Cs,ih=Lu,nh=Vu,rh=_e("match"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu("".charAt),dh=Bu("".replace),uh=Bu("".indexOf),hh=Bu("".slice),ph=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,mh=/a/g,_h=/a/g,fh=new oh(mh)!==mh,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||$u((function(){return _h[rh]=!1,oh(mh)!=mh||oh(_h)==_h||"/a/i"!=oh(mh,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=zu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=Yu(h))),e=void 0===e?"":Ku(e),t=void 0===t?"":Ku(t),h=e,ih&&"dotAll"in mh&&(n=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in mh&&(r=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),nh&&(o=function(e){for(var t,i=e.length,n=0,r="",o=[],s={},a=!1,c=!1,l=0,d="";n<=i;n++){if("\\"===(t=lh(e,n)))t+=lh(e,++n);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:r+=t}return[r,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r="",o=!1;n<=i;n++)"\\"!==(t=lh(e,n))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),r+=t):r+="[\\s\\S]":r+=t+lh(e,++n);return r}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch(nF){}return s},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,"RegExp",Sh,{constructor:!0})}th("RegExp");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=cn.get,Dh=Lu,Oh=Vu,wh=b("native-string-replace",String.prototype.replace),Ph=RegExp.prototype.exec,Lh=Ph,Mh=Ah("".charAt),xh=Ah("".indexOf),Vh=Ah("".replace),Uh=Ah("".slice),Fh=function(){var e=/a/,t=/b*/g;return yh(Ph,e,"a"),yh(Ph,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec("")[1];(Fh||Hh||Bh||Dh||Oh)&&(Lh=function(e){var t,i,n,r,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Lh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,m=yh(Ch,c),_=c.source,f=0,g=d;if(p&&(m=Vh(m,"y",""),-1===xh(m,"g")&&(m+="g"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Mh(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Hh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Fh&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(r[o]=void 0)})),r&&h)for(r.groups=s=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=r[a[1]];return r});var jh=Lh;Vr({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,zh=ta,Kh=ve,Yh=_e("species"),qh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(zh(t)&&(t===qh||Jh(t.prototype))||Kh(t)&&null===(t=t[Yh]))&&(t=void 0)),void 0===t?qh:t},Xh=va,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),np=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Zh(c),_=$h(m),f=Xh(l,d),g=ep(_),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:n||r?r:S}},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=rp.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=ns,up=ss,hp=cp,pp=Ki,mp=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch(nF){e.forEach=hp}};for(var _p in dp)dp[_p]&&mp(lp[_p]&&lp[_p].prototype);mp(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Sp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r}},vp={left:Ip(!1),right:Ip(!0)}.left;Vr({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=_e,kp=Ki,Np=bp("species"),Dp=RegExp.prototype,Op=c,wp=Lt,Pp=fu,Lp=I,Mp=Op("".charAt),xp=Op("".charCodeAt),Vp=Op("".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Lp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=xp(o,s))<55296||n>56319||s+1===a||(r=xp(o,s+1))<56320||r>57343?e?Mp(o,s):n:e?Vp(o,s,s+2):r-56320+(n-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),zp=Hp("".slice),Kp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Yp=/\$([$&'`]|\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=Yp;return void 0!==r&&(r=jp(r),c=Kp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return zp(t,0,i);case"'":return zp(t,s);case"<":l=r[zp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o}l=n[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,em=jh,tm=TypeError,im=_a,nm=Fe,rm=c,om=function(e,t,i,n){var r=bp(e),o=!Cp((function(){var t={};return t[r]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags="",i[r]=/./[r]),i.exec=function(){return t=!0,null},i[r](""),!t}));if(!o||!s||i){var a=yp(/./[r]),c=t(r,""[e],(function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,r,c[1])}n&&kp(Dp[r],"sham",!0)},sm=i,am=Ce,cm=Ee,lm=T,dm=Lt,um=Ht,hm=fu,pm=I,mm=function(e,t,i){return t+(i?Bp(e,t).length:1)},_m=nt,fm=qp,gm=function(e,t){var i=e.exec;if($p(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n}if("RegExp"===Zp(e))return Qp(em,e,t);throw tm("RegExp#exec called on incompatible receiver")},Tm=_e("replace"),Em=Math.max,Sm=Math.min,Im=rm([].concat),vm=rm([].push),ym=rm("".indexOf),Am=rm("".slice),Rm=function(e){return void 0===e?e:String(e)},Cm="$0"==="a".replace(/./,"$0"),bm=!!/./[Tm]&&""===/./[Tm]("a","$0"),km=!sm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));om("replace",(function(e,t,i){var n=bm?"$":"$0";return[function(e,i){var n=pm(this),r=lm(e)?void 0:_m(e,Tm);return r?nm(r,e,n,i):nm(t,hm(n),e,i)},function(e,r){var o=am(this),s=hm(e);if("string"==typeof r&&-1===ym(r,n)&&-1===ym(r,"$<")){var a=i(t,o,s,r);if(a.done)return a.value}var c=cm(r);c||(r=hm(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=gm(o,s);if(null===h)break;if(vm(u,h),!l)break;""===hm(h[0])&&(o.lastIndex=mm(s,um(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=hm((h=u[_])[0]),g=Em(Sm(dm(h.index),s.length),0),T=[],E=1;E<h.length;E++)vm(T,Rm(h[E]));var S=h.groups;if(c){var I=Im([f],T,g,s);void 0!==S&&vm(I,S);var v=hm(im(r,void 0,I))}else v=fm(f,s,g,T,S,r);g>=m&&(p+=Am(s,m,g)+v,m=g+f.length)}return p+Am(s,m)}]}),!km||!Cm||bm);var Nm=Yt.includes,Dm=Fi;Vr({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Nm(this,e,arguments.length>1?arguments[1]:void 0)}}),Dm("includes");var Om=Lt,wm=fu,Pm=I,Lm=RangeError,Mm=c,xm=Ht,Vm=fu,Um=I,Fm=Mm((function(e){var t=wm(Pm(this)),i="",n=Om(e);if(n<0||Infinity==n)throw Lm("Wrong number of repetitions");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i})),Bm=Mm("".slice),Hm=Math.ceil,jm=function(e){return function(t,i,n){var r,o,s=Vm(Um(t)),a=xm(i),c=s.length,l=void 0===n?" ":Vm(n);return a<=c||""==l?s:((o=Fm(l,Hm((r=a-c)/l.length))).length>r&&(o=Bm(o,0,r)),e?s+o:o+s)}},Gm={start:jm(!1),end:jm(!0)},Wm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),Jm=Gm.start;Vr({target:"String",proto:!0,forced:Wm},{padStart:function(e){return Jm(this,e,arguments.length>1?arguments[1]:void 0)}});var zm=i,Km=ke,Ym=_e("iterator"),qm=!zm((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),!t.size&&!Km||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Ym]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),Qm=ir,Xm=function(e,t,i){for(var n in t)Qm(e,n,t[n],i);return e},$m=Tt,Zm=De,e_=Wi,t_=function(e,t,i){var n=$m(t);n in e?Zm.f(e,n,e_(0,i)):e[n]=i},i_=Ut,n_=Gt,r_=t_,o_=Array,s_=Math.max,a_=function(e,t,i){for(var n=n_(e),r=i_(t,n),o=i_(void 0===i?n:i,n),s=o_(s_(o-r,0)),a=0;r<o;r++,a++)r_(s,a,e[r]);return s.length=a,s},c_=a_,l_=Math.floor,d_=function(e,t){var i=e.length,n=l_(i/2);return i<8?u_(e,t):h_(e,d_(c_(e,0,n),t),d_(c_(e,n),t),t)},u_=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},h_=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},p_=d_,m_=Vr,__=C,f_=Fe,g_=c,T_=ke,E_=qm,S_=ir,I_=Is,v_=Xm,y_=oo,A_=po,R_=cn,C_=Ns,b_=Ee,k_=G,N_=va,D_=Vs,O_=Ce,w_=ve,P_=fu,L_=Di,M_=Wi,x_=ad,V_=ed,U_=Ra,F_=p_,B_=_e("iterator"),H_="URLSearchParams",j_=H_+"Iterator",G_=R_.set,W_=R_.getterFor(H_),J_=R_.getterFor(j_),z_=Object.getOwnPropertyDescriptor,K_=function(e){if(!T_)return __[e];var t=z_(__,e);return t&&t.value},Y_=K_("fetch"),q_=K_("Request"),Q_=K_("Headers"),X_=q_&&q_.prototype,$_=Q_&&Q_.prototype,Z_=__.RegExp,ef=__.TypeError,tf=__.decodeURIComponent,nf=__.encodeURIComponent,rf=g_("".charAt),of=g_([].join),sf=g_([].push),af=g_("".replace),cf=g_([].shift),lf=g_([].splice),df=g_("".split),uf=g_("".slice),hf=/\+/g,pf=Array(4),mf=function(e){return pf[e-1]||(pf[e-1]=Z_("((?:%[\\da-f]{2}){"+e+"})","gi"))},_f=function(e){try{return tf(e)}catch(nF){return e}},ff=function(e){var t=af(e,hf," "),i=4;try{return tf(t)}catch(nF){for(;i;)t=af(t,mf(i--),_f);return t}},gf=/[!'()~]|%20/g,Tf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Ef=function(e){return Tf[e]},Sf=function(e){return af(nf(e),gf,Ef)},If=A_((function(e,t){G_(this,{type:j_,iterator:x_(W_(e).entries),kind:t})}),"Iterator",(function(){var e=J_(this),t=e.kind,i=e.iterator.next(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.value]),i}),!0),vf=function(e){this.entries=[],this.url=null,void 0!==e&&(w_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rf(e,0)?uf(e,1):e:P_(e)))};vf.prototype={type:H_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,n,r,o,s,a,c=V_(e);if(c)for(i=(t=x_(e,c)).next;!(n=f_(i,t)).done;){if(o=(r=x_(O_(n.value))).next,(s=f_(o,r)).done||(a=f_(o,r)).done||!f_(o,r).done)throw ef("Expected sequence with length 2");sf(this.entries,{key:P_(s.value),value:P_(a.value)})}else for(var l in e)k_(e,l)&&sf(this.entries,{key:l,value:P_(e[l])})},parseQuery:function(e){if(e)for(var t,i,n=df(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=df(t,"="),sf(this.entries,{key:ff(cf(i)),value:ff(of(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],sf(i,Sf(e.key)+"="+Sf(e.value));return of(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yf=function(){C_(this,Af);var e=G_(this,new vf(arguments.length>0?arguments[0]:void 0));T_||(this.length=e.entries.length)},Af=yf.prototype;if(v_(Af,{append:function(e,t){U_(arguments.length,2);var i=W_(this);sf(i.entries,{key:P_(e),value:P_(t)}),T_||this.length++,i.updateURL()},delete:function(e){U_(arguments.length,1);for(var t=W_(this),i=t.entries,n=P_(e),r=0;r<i.length;)i[r].key===n?lf(i,r,1):r++;T_||(this.length=i.length),t.updateURL()},get:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=[],r=0;r<t.length;r++)t[r].key===i&&sf(n,t[r].value);return n},has:function(e){U_(arguments.length,1);for(var t=W_(this).entries,i=P_(e),n=0;n<t.length;)if(t[n++].key===i)return!0;return!1},set:function(e,t){U_(arguments.length,1);for(var i,n=W_(this),r=n.entries,o=!1,s=P_(e),a=P_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?lf(r,c--,1):(o=!0,i.value=a));o||sf(r,{key:s,value:a}),T_||(this.length=r.length),n.updateURL()},sort:function(){var e=W_(this);F_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=W_(this).entries,n=N_(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new If(this,"keys")},values:function(){return new If(this,"values")},entries:function(){return new If(this,"entries")}},{enumerable:!0}),S_(Af,B_,Af.entries,{name:"entries"}),S_(Af,"toString",(function(){return W_(this).serialize()}),{enumerable:!0}),T_&&I_(Af,"size",{get:function(){return W_(this).entries.length},configurable:!0,enumerable:!0}),y_(yf,H_),m_({global:!0,constructor:!0,forced:!E_},{URLSearchParams:yf}),!E_&&b_(Q_)){var Rf=g_($_.has),Cf=g_($_.set),bf=function(e){if(w_(e)){var t,i=e.body;if(D_(i)===H_)return t=e.headers?new Q_(e.headers):new Q_,Rf(t,"content-type")||Cf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),L_(e,{body:M_(0,P_(i)),headers:M_(0,t)})}return e};if(b_(Y_)&&m_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Y_(e,arguments.length>1?bf(arguments[1]):{})}}),b_(q_)){var kf=function(e){return C_(this,X_),new q_(e,arguments.length>1?bf(arguments[1]):{})};X_.constructor=kf,kf.prototype=X_,m_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:kf})}}var Nf={URLSearchParams:yf,getState:W_},Df="\t\n\v\f\r                 \u2028\u2029\ufeff",Of=I,wf=fu,Pf=Df,Lf=c("".replace),Mf=RegExp("^["+Pf+"]+"),xf=RegExp("(^|[^"+Pf+"])["+Pf+"]+$"),Vf=function(e){return function(t){var i=wf(Of(t));return 1&e&&(i=Lf(i,Mf,"")),2&e&&(i=Lf(i,xf,"$1")),i}},Uf={start:Vf(1),end:Vf(2),trim:Vf(3)},Ff=Dn.PROPER,Bf=i,Hf=Df,jf=Uf.trim;Vr({target:"String",proto:!0,forced:function(e){return Bf((function(){return!!Hf[e]()||"​…᠎"!=="​…᠎"[e]()||Ff&&Hf[e].name!==e}))}("trim")},{trim:function(){return jf(this)}});var Gf=Vr,Wf=ke,Jf=c,zf=G,Kf=Ee,Yf=Ge,qf=fu,Qf=Is,Xf=Sr,$f=C.Symbol,Zf=$f&&$f.prototype;if(Wf&&Kf($f)&&(!("description"in Zf)||void 0!==$f().description)){var eg={},tg=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:qf(arguments[0]),t=Yf(Zf,this)?new $f(e):void 0===e?$f():$f(e);return""===e&&(eg[t]=!0),t};Xf(tg,$f),tg.prototype=Zf,Zf.constructor=tg;var ig="Symbol(test)"==String($f("test")),ng=Jf(Zf.valueOf),rg=Jf(Zf.toString),og=/^Symbol\((.*)\)[^)]+$/,sg=Jf("".replace),ag=Jf("".slice);Qf(Zf,"description",{configurable:!0,get:function(){var e=ng(this);if(zf(eg,e))return"";var t=rg(e),i=ig?ag(t,7,-1):sg(t,og,"$1");return""===i?void 0:i}}),Gf({global:!0,constructor:!0,forced:!0},{Symbol:tg})}var cg=Fp.charAt,lg=fu,dg=cn,ug=jo,hg=Go,pg="String Iterator",mg=dg.set,_g=dg.getterFor(pg);ug(String,"String",(function(e){mg(this,{type:pg,string:lg(e),index:0})}),(function(){var e,t=_g(this),i=t.string,n=t.index;return n>=i.length?hg(void 0,!0):(e=cg(i,n),t.index+=e.length,hg(e,!1))}));var fg,gg=ke,Tg=c,Eg=Fe,Sg=i,Ig=oi,vg=sr,yg=dn,Ag=B,Rg=g,Cg=Object.assign,bg=Object.defineProperty,kg=Tg([].concat),Ng=!Cg||Sg((function(){if(gg&&1!==Cg({b:1},Cg(bg({},"a",{enumerable:!0,get:function(){bg(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!=Cg({},e)[i]||Ig(Cg({},t)).join("")!=n}))?function(e,t){for(var i=Ag(e),n=arguments.length,r=1,o=vg.f,s=yg.f;n>r;)for(var a,c=Rg(arguments[r++]),l=o?kg(Ig(c),o(c)):Ig(c),d=l.length,u=0;d>u;)a=l[u++],gg&&!Eg(s,c,a)||(i[a]=c[a]);return i}:Cg,Dg=Ce,Og=ud,wg=va,Pg=Fe,Lg=B,Mg=function(e,t,i,n){try{return n?t(Dg(i)[0],i[1]):t(i)}catch(nF){Og(e,"throw",nF)}},xg=Yl,Vg=ta,Ug=Gt,Fg=t_,Bg=ad,Hg=ed,jg=Array,Gg=c,Wg=2147483647,Jg=/[^\0-\u007E]/,zg=/[.\u3002\uFF0E\uFF61]/g,Kg="Overflow: input needs wider integers to process",Yg=RangeError,qg=Gg(zg.exec),Qg=Math.floor,Xg=String.fromCharCode,$g=Gg("".charCodeAt),Zg=Gg([].join),eT=Gg([].push),tT=Gg("".replace),iT=Gg("".split),nT=Gg("".toLowerCase),rT=function(e){return e+22+75*(e<26)},oT=function(e,t,i){var n=0;for(e=i?Qg(e/700):e>>1,e+=Qg(e/t);e>455;)e=Qg(e/35),n+=36;return Qg(n+36*e/(e+38))},sT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=$g(e,i++);if(r>=55296&&r<=56319&&i<n){var o=$g(e,i++);56320==(64512&o)?eT(t,((1023&r)<<10)+(1023&o)+65536):(eT(t,r),i--)}else eT(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&eT(t,Xg(n));var c=t.length,l=c;for(c&&eT(t,"-");l<r;){var d=Wg;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<d&&(d=n);var u=l+1;if(d-o>Qg((Wg-s)/u))throw Yg(Kg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((n=e[i])<o&&++s>Wg)throw Yg(Kg);if(n==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;eT(t,Xg(rT(m+_%f))),h=Qg(_/f),p+=36}eT(t,Xg(rT(h))),a=oT(s,u,l==c),s=0,l++}}s++,o++}return Zg(t,"")},aT=Vr,cT=ke,lT=qm,dT=C,uT=va,hT=c,pT=ir,mT=Is,_T=Ns,fT=G,gT=Ng,TT=function(e){var t=Lg(e),i=Vg(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=wg(r,n>2?arguments[2]:void 0));var s,a,c,l,d,u,h=Hg(t),p=0;if(!h||this===jg&&xg(h))for(s=Ug(t),a=i?new this(s):jg(s);s>p;p++)u=o?r(t[p],p):t[p],Fg(a,p,u);else for(d=(l=Bg(t,h)).next,a=i?new this:[];!(c=Pg(d,l)).done;p++)u=o?Mg(l,r,[c.value,p],!0):c.value,Fg(a,p,u);return a.length=p,a},ET=a_,ST=Fp.codeAt,IT=function(e){var t,i,n=[],r=iT(tT(nT(e),zg,"."),".");for(t=0;t<r.length;t++)i=r[t],eT(n,qg(Jg,i)?"xn--"+sT(i):i);return Zg(n,".")},vT=fu,yT=oo,AT=Ra,RT=Nf,CT=cn,bT=CT.set,kT=CT.getterFor("URL"),NT=RT.URLSearchParams,DT=RT.getState,OT=dT.URL,wT=dT.TypeError,PT=dT.parseInt,LT=Math.floor,MT=Math.pow,xT=hT("".charAt),VT=hT(/./.exec),UT=hT([].join),FT=hT(1..toString),BT=hT([].pop),HT=hT([].push),jT=hT("".replace),GT=hT([].shift),WT=hT("".split),JT=hT("".slice),zT=hT("".toLowerCase),KT=hT([].unshift),YT="Invalid scheme",qT="Invalid host",QT="Invalid port",XT=/[a-z]/i,$T=/[\d+-.a-z]/i,ZT=/\d/,eE=/^0x/i,tE=/^[0-7]+$/,iE=/^\d+$/,nE=/^[\da-f]+$/i,rE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,oE=/[\0\t\n\r #/:<>?@[\\\]^|]/,sE=/^[\u0000-\u0020]+/,aE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,cE=/[\t\n\r]/g,lE=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)KT(t,e%256),e=LT(e/256);return UT(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+=FT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},dE={},uE=gT({},dE,{" ":1,'"':1,"<":1,">":1,"`":1}),hE=gT({},uE,{"#":1,"?":1,"{":1,"}":1}),pE=gT({},hE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),mE=function(e,t){var i=ST(e,0);return i>32&&i<127&&!fT(t,e)?e:encodeURIComponent(e)},_E={ftp:21,file:null,http:80,https:443,ws:80,wss:443},fE=function(e,t){var i;return 2==e.length&&VT(XT,xT(e,0))&&(":"==(i=xT(e,1))||!t&&"|"==i)},gE=function(e){var t;return e.length>1&&fE(JT(e,0,2))&&(2==e.length||"/"===(t=xT(e,2))||"\\"===t||"?"===t||"#"===t)},TE=function(e){return"."===e||"%2e"===zT(e)},EE={},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},OE={},wE={},PE={},LE={},ME={},xE={},VE={},UE={},FE={},BE=function(e,t,i){var n,r,o,s=vT(e);if(t){if(r=this.parse(s))throw wT(r);this.searchParams=null}else{if(void 0!==i&&(n=new BE(i,!0)),r=this.parse(s,null,n))throw wT(r);(o=DT(new NT)).bindURL(this),this.searchParams=o}};BE.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,l=t||EE,d=0,u="",h=!1,p=!1,m=!1;for(e=vT(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=jT(e,sE,""),e=jT(e,aE,"$1")),e=jT(e,cE,""),n=TT(e);d<=n.length;){switch(r=n[d],l){case EE:if(!r||!VT(XT,r)){if(t)return YT;l=IE;continue}u+=zT(r),l=SE;break;case SE:if(r&&(VT($T,r)||"+"==r||"-"==r||"."==r))u+=zT(r);else{if(":"!=r){if(t)return YT;u="",l=IE,d=0;continue}if(t&&(c.isSpecial()!=fT(_E,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&_E[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=wE:c.isSpecial()&&i&&i.scheme==c.scheme?l=vE:c.isSpecial()?l=CE:"/"==n[d+1]?(l=yE,d++):(c.cannotBeABaseURL=!0,HT(c.path,""),l=VE)}break;case IE:if(!i||i.cannotBeABaseURL&&"#"!=r)return YT;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=ET(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=FE;break}l="file"==i.scheme?wE:AE;continue;case vE:if("/"!=r||"/"!=n[d+1]){l=AE;continue}l=bE,d++;break;case yE:if("/"==r){l=kE;break}l=xE;continue;case AE:if(c.scheme=i.scheme,r==fg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())l=RE;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.path.length--,l=xE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}break;case RE:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=xE;continue}l=kE}else l=bE;break;case CE:if(l=bE,"/"!=r||"/"!=xT(u,d+1))continue;d++;break;case bE:if("/"!=r&&"\\"!=r){l=kE;continue}break;case kE:if("@"==r){h&&(u="%40"+u),h=!0,o=TT(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=mE(f,pE);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=TT(u).length+1,u="",l=NE}else u+=r;break;case NE:case DE:if(t&&"file"==c.scheme){l=LE;continue}if(":"!=r||p){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return qT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=ME,t)return;continue}"["==r?p=!0:"]"==r&&(p=!1),u+=r}else{if(""==u)return qT;if(s=c.parseHost(u))return s;if(u="",l=OE,t==DE)return}break;case OE:if(!VT(ZT,r)){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var T=PT(u,10);if(T>65535)return QT;c.port=c.isSpecial()&&T===_E[c.scheme]?null:T,u=""}if(t)return;l=ME;continue}return QT}u+=r;break;case wE:if(c.scheme="file","/"==r||"\\"==r)l=PE;else{if(!i||"file"!=i.scheme){l=xE;continue}if(r==fg)c.host=i.host,c.path=ET(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){gE(UT(ET(n,d),""))||(c.host=i.host,c.path=ET(i.path),c.shortenPath()),l=xE;continue}c.host=i.host,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}}break;case PE:if("/"==r||"\\"==r){l=LE;break}i&&"file"==i.scheme&&!gE(UT(ET(n,d),""))&&(fE(i.path[0],!0)?HT(c.path,i.path[0]):c.host=i.host),l=xE;continue;case LE:if(r==fg||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&fE(u))l=xE;else if(""==u){if(c.host="",t)return;l=ME}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=ME}continue}u+=r;break;case ME:if(c.isSpecial()){if(l=xE,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=fg&&(l=xE,"/"!=r))continue}else c.fragment="",l=FE;else c.query="",l=UE;break;case xE:if(r==fg||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=zT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,"")):TE(u)?"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,""):("file"==c.scheme&&!c.path.length&&fE(u)&&(c.host&&(c.host=""),u=xT(u,0)+":"),HT(c.path,u)),u="","file"==c.scheme&&(r==fg||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)GT(c.path);"?"==r?(c.query="",l=UE):"#"==r&&(c.fragment="",l=FE)}else u+=mE(r,hE);break;case VE:"?"==r?(c.query="",l=UE):"#"==r?(c.fragment="",l=FE):r!=fg&&(c.path[0]+=mE(r,dE));break;case UE:t||"#"!=r?r!=fg&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":mE(r,dE)):(c.fragment="",l=FE);break;case FE:r!=fg&&(c.fragment+=mE(r,uE))}d++}},parseHost:function(e){var t,i,n;if("["==xT(e,0)){if("]"!=xT(e,e.length-1))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return xT(e,u)};if(":"==h()){if(":"!=xT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&VT(nE,h());)t=16*t+PT(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++}if(!VT(ZT,h()))return;for(;VT(ZT,h());){if(o=PT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[l]=256*c[l]+r,2!=++n&&4!=n||l++}if(4!=n)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(JT(e,1,-1)),!t)return qT;this.host=t}else if(this.isSpecial()){if(e=IT(e),VT(rE,e))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=WT(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(o=10,r.length>1&&"0"==xT(r,0)&&(o=VT(eE,r)?16:8,r=JT(r,8==o?1:2)),""===r)s=0;else{if(!VT(10==o?iE:8==o?tE:nE,r))return e;s=PT(r,o)}HT(i,s)}for(n=0;n<t;n++)if(s=i[n],n==t-1){if(s>=MT(256,5-t))return null}else if(s>255)return null;for(a=BT(i),n=0;n<i.length;n++)a+=i[n]*MT(256,3-n);return a}(e),null===t)return qT;this.host=t}else{if(VT(oE,e))return qT;for(t="",i=TT(e),n=0;n<i.length;n++)t+=mE(i[n],dE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return fT(_E,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&fE(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==r?(l+="//",e.includesCredentials()&&(l+=i+(n?":"+n:"")+"@"),l+=lE(r),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+UT(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw wT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new HE(e.path[0]).origin}catch(nF){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+lE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(vT(e)+":",EE)},getUsername:function(){return this.username},setUsername:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=mE(t[i],pE)}},getPassword:function(){return this.password},setPassword:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=mE(t[i],pE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?lE(e):lE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,NE)},getHostname:function(){var e=this.host;return null===e?"":lE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,DE)},getPort:function(){var e=this.port;return null===e?"":vT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=vT(e))?this.port=null:this.parse(e,OE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+UT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,ME))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=vT(e))?this.query=null:("?"==xT(e,0)&&(e=JT(e,1)),this.query="",this.parse(e,UE)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=vT(e))?("#"==xT(e,0)&&(e=JT(e,1)),this.fragment="",this.parse(e,FE)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var HE=function(e){var t=_T(this,jE),i=AT(arguments.length,1)>1?arguments[1]:void 0,n=bT(t,new BE(e,!1,i));cT||(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())},jE=HE.prototype,GE=function(e,t){return{get:function(){return kT(this)[e]()},set:t&&function(e){return kT(this)[t](e)},configurable:!0,enumerable:!0}};if(cT&&(mT(jE,"href",GE("serialize","setHref")),mT(jE,"origin",GE("getOrigin")),mT(jE,"protocol",GE("getProtocol","setProtocol")),mT(jE,"username",GE("getUsername","setUsername")),mT(jE,"password",GE("getPassword","setPassword")),mT(jE,"host",GE("getHost","setHost")),mT(jE,"hostname",GE("getHostname","setHostname")),mT(jE,"port",GE("getPort","setPort")),mT(jE,"pathname",GE("getPathname","setPathname")),mT(jE,"search",GE("getSearch","setSearch")),mT(jE,"searchParams",GE("getSearchParams")),mT(jE,"hash",GE("getHash","setHash"))),pT(jE,"toJSON",(function(){return kT(this).serialize()}),{enumerable:!0}),pT(jE,"toString",(function(){return kT(this).serialize()}),{enumerable:!0}),OT){var WE=OT.createObjectURL,JE=OT.revokeObjectURL;WE&&pT(HE,"createObjectURL",uT(WE,OT)),JE&&pT(HE,"revokeObjectURL",uT(JE,OT))}yT(HE,"URL"),aT({global:!0,constructor:!0,forced:!lT,sham:!cT},{URL:HE});var zE="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,KE=Lt,YE=Ht,qE=RangeError,QE=function(e){if(void 0===e)return 0;var t=KE(e),i=YE(t);if(t!==i)throw qE("Wrong length or index");return i},XE=Array,$E=Math.abs,ZE=Math.pow,eS=Math.floor,tS=Math.log,iS=Math.LN2,nS={pack:function(e,t,i){var n,r,o,s=XE(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?ZE(2,-24)-ZE(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=$E(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=eS(tS(e)/iS),e*(o=ZE(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*ZE(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*ZE(2,t),n+=l):(r=e*ZE(2,l-1)*ZE(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<<t|r,a+=t;a>0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<<r)-1,s=o>>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=ZE(2,t),d-=s}return(l?-1:1)*i*ZE(2,d-t)}},rS=B,oS=Ut,sS=Gt,aS=function(e){for(var t=rS(this),i=sS(t),n=arguments.length,r=oS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:oS(o,i);s>r;)t[r++]=e;return t},cS=C,lS=c,dS=ke,uS=zE,hS=Dn,pS=Ki,mS=Is,_S=Xm,fS=i,gS=Ns,TS=Lt,ES=Ht,SS=QE,IS=nS,vS=zr,yS=vo,AS=nr.f,RS=aS,CS=a_,bS=oo,kS=cn,NS=hS.PROPER,DS=hS.CONFIGURABLE,OS="ArrayBuffer",wS="DataView",PS="prototype",LS="Wrong index",MS=kS.getterFor(OS),xS=kS.getterFor(wS),VS=kS.set,US=cS[OS],FS=US,BS=FS&&FS[PS],HS=cS[wS],jS=HS&&HS[PS],GS=Object.prototype,WS=cS.Array,JS=cS.RangeError,zS=lS(RS),KS=lS([].reverse),YS=IS.pack,qS=IS.unpack,QS=function(e){return[255&e]},XS=function(e){return[255&e,e>>8&255]},$S=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},ZS=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},eI=function(e){return YS(e,23,4)},tI=function(e){return YS(e,52,8)},iI=function(e,t,i){mS(e[PS],t,{configurable:!0,get:function(){return i(this)[t]}})},nI=function(e,t,i,n){var r=SS(i),o=xS(e);if(r+t>o.byteLength)throw JS(LS);var s=o.bytes,a=r+o.byteOffset,c=CS(s,a,a+t);return n?c:KS(c)},rI=function(e,t,i,n,r,o){var s=SS(i),a=xS(e);if(s+t>a.byteLength)throw JS(LS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(uS){var oI=NS&&US.name!==OS;if(fS((function(){US(1)}))&&fS((function(){new US(-1)}))&&!fS((function(){return new US,new US(1.5),new US(NaN),1!=US.length||oI&&!DS})))oI&&DS&&pS(US,"name",OS);else{(FS=function(e){return gS(this,BS),new US(SS(e))})[PS]=BS;for(var sI,aI=AS(US),cI=0;aI.length>cI;)(sI=aI[cI++])in FS||pS(FS,sI,US[sI]);BS.constructor=FS}yS&&vS(jS)!==GS&&yS(jS,GS);var lI=new HS(new FS(2)),dI=lS(jS.setInt8);lI.setInt8(0,2147483648),lI.setInt8(1,2147483649),!lI.getInt8(0)&&lI.getInt8(1)||_S(jS,{setInt8:function(e,t){dI(this,e,t<<24>>24)},setUint8:function(e,t){dI(this,e,t<<24>>24)}},{unsafe:!0})}else BS=(FS=function(e){gS(this,BS);var t=SS(e);VS(this,{type:OS,bytes:zS(WS(t),0),byteLength:t}),dS||(this.byteLength=t,this.detached=!1)})[PS],jS=(HS=function(e,t,i){gS(this,jS),gS(e,BS);var n=MS(e),r=n.byteLength,o=TS(t);if(o<0||o>r)throw JS("Wrong offset");if(o+(i=void 0===i?r-o:ES(i))>r)throw JS("Wrong length");VS(this,{type:wS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),dS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[PS],dS&&(iI(FS,"byteLength",MS),iI(HS,"buffer",xS),iI(HS,"byteLength",xS),iI(HS,"byteOffset",xS)),_S(jS,{getInt8:function(e){return nI(this,1,e)[0]<<24>>24},getUint8:function(e){return nI(this,1,e)[0]},getInt16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return ZS(nI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return ZS(nI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return qS(nI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return qS(nI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){rI(this,1,e,QS,t)},setUint8:function(e,t){rI(this,1,e,QS,t)},setInt16:function(e,t){rI(this,2,e,XS,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){rI(this,2,e,XS,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){rI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){rI(this,4,e,$S,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){rI(this,4,e,eI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){rI(this,8,e,tI,t,arguments.length>2?arguments[2]:void 0)}});bS(FS,OS),bS(HS,wS);var uI={ArrayBuffer:FS,DataView:HS},hI=Vr,pI=Ta,mI=i,_I=Ce,fI=Ut,gI=Ht,TI=da,EI=uI.ArrayBuffer,SI=uI.DataView,II=SI.prototype,vI=pI(EI.prototype.slice),yI=pI(II.getUint8),AI=pI(II.setUint8);hI({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:mI((function(){return!new EI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(vI&&void 0===t)return vI(_I(this),e);for(var i=_I(this).byteLength,n=fI(e,i),r=fI(void 0===t?i:t,i),o=new(TI(this,EI))(gI(r-n)),s=new SI(this),a=new SI(o),c=0;n<r;)AI(a,c++,yI(s,n++));return o}});var RI,CI,bI,kI={},NI={get exports(){return kI},set exports(e){kI=e}},DI=zE,OI=ke,wI=C,PI=Ee,LI=ve,MI=G,xI=Vs,VI=Qe,UI=Ki,FI=ir,BI=Is,HI=Ge,jI=zr,GI=vo,WI=_e,JI=Y,zI=cn.enforce,KI=cn.get,YI=wI.Int8Array,qI=YI&&YI.prototype,QI=wI.Uint8ClampedArray,XI=QI&&QI.prototype,$I=YI&&jI(YI),ZI=qI&&jI(qI),ev=Object.prototype,tv=wI.TypeError,iv=WI("toStringTag"),nv=JI("TYPED_ARRAY_TAG"),rv="TypedArrayConstructor",ov=DI&&!!GI&&"Opera"!==xI(wI.opera),sv=!1,av={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},cv={BigInt64Array:8,BigUint64Array:8},lv=function(e){var t=jI(e);if(LI(t)){var i=KI(t);return i&&MI(i,rv)?i[rv]:lv(t)}},dv=function(e){if(!LI(e))return!1;var t=xI(e);return MI(av,t)||MI(cv,t)};for(RI in av)(bI=(CI=wI[RI])&&CI.prototype)?zI(bI)[rv]=CI:ov=!1;for(RI in cv)(bI=(CI=wI[RI])&&CI.prototype)&&(zI(bI)[rv]=CI);if((!ov||!PI($I)||$I===Function.prototype)&&($I=function(){throw tv("Incorrect invocation")},ov))for(RI in av)wI[RI]&&GI(wI[RI],$I);if((!ov||!ZI||ZI===ev)&&(ZI=$I.prototype,ov))for(RI in av)wI[RI]&&GI(wI[RI].prototype,ZI);if(ov&&jI(XI)!==ZI&&GI(XI,ZI),OI&&!MI(ZI,iv))for(RI in sv=!0,BI(ZI,iv,{configurable:!0,get:function(){return LI(this)?this[nv]:void 0}}),av)wI[RI]&&UI(wI[RI],nv,RI);var uv={NATIVE_ARRAY_BUFFER_VIEWS:ov,TYPED_ARRAY_TAG:sv&&nv,aTypedArray:function(e){if(dv(e))return e;throw tv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(PI(e)&&(!GI||HI($I,e)))return e;throw tv(VI(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,n){if(OI){if(i)for(var r in av){var o=wI[r];if(o&&MI(o.prototype,e))try{delete o.prototype[e]}catch(nF){try{o.prototype[e]=t}catch(s){}}}ZI[e]&&!i||FI(ZI,e,i?t:ov&&qI[e]||t,n)}},exportTypedArrayStaticMethod:function(e,t,i){var n,r;if(OI){if(GI){if(i)for(n in av)if((r=wI[n])&&MI(r,e))try{delete r[e]}catch(nF){}if($I[e]&&!i)return;try{return FI($I,e,i?t:ov&&$I[e]||t)}catch(nF){}}for(n in av)!(r=wI[n])||r[e]&&!i||FI(r,e,t)}},getTypedArrayConstructor:lv,isView:function(e){if(!LI(e))return!1;var t=xI(e);return"DataView"===t||MI(av,t)||MI(cv,t)},isTypedArray:dv,TypedArray:$I,TypedArrayPrototype:ZI},hv=C,pv=i,mv=Dd,_v=uv.NATIVE_ARRAY_BUFFER_VIEWS,fv=hv.ArrayBuffer,gv=hv.Int8Array,Tv=!_v||!pv((function(){gv(1)}))||!pv((function(){new gv(-1)}))||!mv((function(e){new gv,new gv(null),new gv(1.5),new gv(e)}),!0)||pv((function(){return 1!==new gv(new fv(2),1,void 0).length})),Ev=ve,Sv=Math.floor,Iv=Number.isInteger||function(e){return!Ev(e)&&isFinite(e)&&Sv(e)===e},vv=Lt,yv=RangeError,Av=function(e){var t=vv(e);if(t<0)throw yv("The argument can't be less than 0");return t},Rv=RangeError,Cv=function(e,t){var i=Av(e);if(i%t)throw Rv("Wrong offset");return i},bv=Vs,kv=_t,Nv=TypeError,Dv=function(e){var t=kv(e,"number");if("number"==typeof t)throw Nv("Can't convert number to bigint");return BigInt(t)},Ov=va,wv=Fe,Pv=oa,Lv=B,Mv=Gt,xv=ad,Vv=ed,Uv=Yl,Fv=function(e){var t=bv(e);return"BigInt64Array"==t||"BigUint64Array"==t},Bv=uv.aTypedArrayConstructor,Hv=Dv,jv=Vr,Gv=C,Wv=Fe,Jv=ke,zv=Tv,Kv=uv,Yv=uI,qv=Ns,Qv=Wi,Xv=Ki,$v=Iv,Zv=Ht,ey=QE,ty=Cv,iy=Tt,ny=G,ry=Vs,oy=ve,sy=Ye,ay=Di,cy=Ge,ly=vo,dy=nr.f,uy=function(e){var t,i,n,r,o,s,a,c,l=Pv(this),d=Lv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Vv(d);if(m&&!Uv(m))for(c=(a=xv(d,m)).next,d=[];!(s=wv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Ov(h,arguments[2])),i=Mv(d),n=new(Bv(l))(i),r=Fv(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?Hv(o):+o;return n},hy=rp.forEach,py=Cs,my=Is,_y=De,fy=ln,gy=lu,Ty=cn.get,Ey=cn.set,Sy=cn.enforce,Iy=_y.f,vy=fy.f,yy=Math.round,Ay=Gv.RangeError,Ry=Yv.ArrayBuffer,Cy=Ry.prototype,by=Yv.DataView,ky=Kv.NATIVE_ARRAY_BUFFER_VIEWS,Ny=Kv.TYPED_ARRAY_TAG,Dy=Kv.TypedArray,Oy=Kv.TypedArrayPrototype,wy=Kv.aTypedArrayConstructor,Py=Kv.isTypedArray,Ly="BYTES_PER_ELEMENT",My="Wrong length",xy=function(e,t){wy(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r},Vy=function(e,t){my(e,t,{configurable:!0,get:function(){return Ty(this)[t]}})},Uy=function(e){var t;return cy(Cy,e)||"ArrayBuffer"==(t=ry(e))||"SharedArrayBuffer"==t},Fy=function(e,t){return Py(e)&&!sy(t)&&t in e&&$v(+t)&&t>=0},By=function(e,t){return t=iy(t),Fy(e,t)?Qv(2,e[t]):vy(e,t)},Hy=function(e,t,i){return t=iy(t),!(Fy(e,t)&&oy(i)&&ny(i,"value"))||ny(i,"get")||ny(i,"set")||i.configurable||ny(i,"writable")&&!i.writable||ny(i,"enumerable")&&!i.enumerable?Iy(e,t,i):(e[t]=i.value,e)};Jv?(ky||(fy.f=By,_y.f=Hy,Vy(Oy,"buffer"),Vy(Oy,"byteOffset"),Vy(Oy,"byteLength"),Vy(Oy,"length")),jv({target:"Object",stat:!0,forced:!ky},{getOwnPropertyDescriptor:By,defineProperty:Hy}),NI.exports=function(e,t,i){var n=e.match(/\d+/)[0]/8,r=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=Gv[r],c=a,l=c&&c.prototype,d={},u=function(e,t){Iy(e,t,{get:function(){return function(e,t){var i=Ty(e);return i.view[o](t*n+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,r){var o=Ty(e);i&&(r=(r=yy(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0)}(this,t,e)},enumerable:!0})};ky?zv&&(c=t((function(e,t,i,r){return qv(e,l),gy(oy(t)?Uy(t)?void 0!==r?new a(t,ty(i,n),r):void 0!==i?new a(t,ty(i,n)):new a(t):Py(t)?xy(c,t):Wv(uy,c,t):new a(ey(t)),e,c)})),ly&&ly(c,Dy),hy(dy(a),(function(e){e in c||Xv(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,r){qv(e,l);var o,s,a,d=0,h=0;if(oy(t)){if(!Uy(t))return Py(t)?xy(c,t):Wv(uy,c,t);o=t,h=ty(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw Ay(My);if((s=p-h)<0)throw Ay(My)}else if((s=Zv(r)*n)+h>p)throw Ay(My);a=s/n}else a=ey(t),o=new Ry(s=a*n);for(Ey(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new by(o)});d<a;)u(e,d++)})),ly&&ly(c,Dy),l=c.prototype=ay(Oy)),l.constructor!==c&&Xv(l,"constructor",c),Sy(l).TypedArrayConstructor=c,Ny&&Xv(l,Ny,r);var h=c!=a;d[r]=c,jv({global:!0,constructor:!0,forced:h,sham:!ky},d),Ly in c||Xv(c,Ly,n),Ly in l||Xv(l,Ly,n),py(r)}):NI.exports=function(){},kI("Uint8",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var jy=aS,Gy=Dv,Wy=Vs,Jy=Fe,zy=i,Ky=uv.aTypedArray,Yy=uv.exportTypedArrayMethod,qy=c("".slice);Yy("fill",(function(e){var t=arguments.length;Ky(this);var i="Big"===qy(Wy(this),0,3)?Gy(e):+e;return Jy(jy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),zy((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var Qy=C,Xy=Fe,$y=uv,Zy=Gt,eA=Cv,tA=B,iA=i,nA=Qy.RangeError,rA=Qy.Int8Array,oA=rA&&rA.prototype,sA=oA&&oA.set,aA=$y.aTypedArray,cA=$y.exportTypedArrayMethod,lA=!iA((function(){var e=new Uint8ClampedArray(2);return Xy(sA,e,{length:1,0:3},1),3!==e[1]})),dA=lA&&$y.NATIVE_ARRAY_BUFFER_VIEWS&&iA((function(){var e=new rA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));cA("set",(function(e){aA(this);var t=eA(arguments.length>1?arguments[1]:void 0,1),i=tA(e);if(lA)return Xy(sA,this,i,t);var n=this.length,r=Zy(i),o=0;if(r+t>n)throw nA("Wrong length");for(;o<r;)this[t+o]=i[o++]}),!lA||dA);var uA=q.match(/firefox\/(\d+)/i),hA=!!uA&&+uA[1],pA=/MSIE|Trident/.test(q),mA=q.match(/AppleWebKit\/(\d+)\./),_A=!!mA&&+mA[1],fA=Ta,gA=i,TA=et,EA=p_,SA=hA,IA=pA,vA=ie,yA=_A,AA=uv.aTypedArray,RA=uv.exportTypedArrayMethod,CA=C.Uint16Array,bA=CA&&fA(CA.prototype.sort),kA=!(!bA||gA((function(){bA(new CA(2),null)}))&&gA((function(){bA(new CA(2),{})}))),NA=!!bA&&!gA((function(){if(vA)return vA<74;if(SA)return SA<67;if(IA)return!0;if(yA)return yA<602;var e,t,i=new CA(516),n=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,n[e]=e-2*t+3;for(bA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==n[e])return!0}));RA("sort",(function(e){return void 0!==e&&TA(e),NA?bA(this,e):EA(AA(this),function(e){return function(t,i){return void 0!==e?+e(t,i)||0:i!=i?-1:t!=t?1:0===t&&0===i?1/t>0&&1/i<0?1:-1:t>i}}(e))}),!NA||kA);var DA=Vr,OA=kc,wA=i,PA=je,LA=Ee,MA=da,xA=iu,VA=ir,UA=OA&&OA.prototype;if(DA({target:"Promise",proto:!0,real:!0,forced:!!OA&&wA((function(){UA.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=MA(this,PA("Promise")),i=LA(e);return this.then(i?function(i){return xA(t,e()).then((function(){return i}))}:e,i?function(i){return xA(t,e()).then((function(){throw i}))}:e)}}),LA(OA)){var FA=PA("Promise").prototype.finally;UA.finally!==FA&&VA(UA,"finally",FA,{unsafe:!0})}var BA=Cs,HA="ArrayBuffer",jA=uI[HA];Vr({global:!0,constructor:!0,forced:C[HA]!==jA},{ArrayBuffer:jA}),BA(HA);var GA=Qe,WA=TypeError,JA=Vr,zA=c,KA=et,YA=B,qA=Gt,QA=function(e,t){if(!delete e[t])throw WA("Cannot delete property "+GA(t)+" of "+GA(e))},XA=fu,$A=i,ZA=p_,eR=sp,tR=hA,iR=pA,nR=ie,rR=_A,oR=[],sR=zA(oR.sort),aR=zA(oR.push),cR=$A((function(){oR.sort(void 0)})),lR=$A((function(){oR.sort(null)})),dR=eR("sort"),uR=!$A((function(){if(nR)return nR<70;if(!(tR&&tR>3)){if(iR)return!0;if(rR)return rR<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++)oR.push({k:t+n,v:i})}for(oR.sort((function(e,t){return t.v-e.v})),n=0;n<oR.length;n++)t=oR[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));JA({target:"Array",proto:!0,forced:cR||!lR||!dR||!uR},{sort:function(e){void 0!==e&&KA(e);var t=YA(this);if(uR)return void 0===e?sR(t):sR(t,e);var i,n,r=[],o=qA(t);for(n=0;n<o;n++)n in t&&aR(r,t[n]);for(ZA(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:XA(t)>XA(i)?1:-1}}(e)),i=qA(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)QA(t,n++);return t}});var hR=Vr,pR=Wh,mR=c([].reverse),_R=[1,2];hR({target:"Array",proto:!0,forced:String(_R)===String(_R.reverse())},{reverse:function(){return pR(this)&&(this.length=this.length),mR(this)}}),kI("Float32",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var fR=Vr,gR=Fe,TR=c,ER=I,SR=Ee,IR=T,vR=pu,yR=fu,AR=nt,RR=Au,CR=qp,bR=_e("replace"),kR=TypeError,NR=TR("".indexOf);TR("".replace);var DR=TR("".slice),OR=Math.max,wR=function(e,t,i){return i>e.length?-1:""===t?i:NR(e,t,i)};fR({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=ER(this),u=0,h=0,p="";if(!IR(e)){if(vR(e)&&(i=yR(ER(RR(e))),!~NR(i,"g")))throw kR("`.replaceAll` does not allow non-global regexes");if(n=AR(e,bR))return gR(n,e,d,t)}for(r=yR(d),o=yR(e),(s=SR(t))||(t=yR(t)),a=o.length,c=OR(1,a),u=wR(r,o,0);-1!==u;)l=s?yR(t(o,u,r)):CR(o,r,u,[],void 0,t),p+=DR(r,h,u)+l,h=u+a,u=wR(r,o,u+c);return h<r.length&&(p+=DR(r,h)),p}});let PR=!0,LR=!0;function MR(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function xR(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 VR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(PR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function UR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(LR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function FR(){if("object"==typeof window){if(PR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function BR(e,t){LR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function HR(e){return"[object Object]"===Object.prototype.toString.call(e)}function jR(e){return HR(e)?Object.keys(e).reduce((function(t,i){const n=HR(e[i]),r=n?jR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function GR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?GR(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{GR(e,e.get(t),i)}))})))}function WR(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&&GR(e,i,r)}))})),r}const JR=FR;function zR(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=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),JR("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return JR("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=>Promise.reject(o(e))))))}}}function KR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function YR(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 xR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qR(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 QR(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 Promise(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function XR(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=>WR(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}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>WR(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?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function $R(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=>{if(this.getSenders().find((t=>t.track===e)))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 ZR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return $R(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=>{if(this.getSenders().find((t=>t.track===e)))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");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.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 eC(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 tC(e,t){xR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var iC=Object.freeze({__proto__:null,shimMediaStream:KR,shimOnTrack:YR,shimGetSendersWithDtmf:qR,shimGetStats:QR,shimSenderReceiverGetStats:XR,shimAddTrackRemoveTrackWithNative:$R,shimAddTrackRemoveTrack:ZR,shimPeerConnection:eC,fixNegotiationNeeded:tC,shimGetUserMedia:zR,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"))}});function nC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){BR("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 rC(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 oC(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(lN){if("TypeError"!==lN.name)throw lN;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function sC(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):Promise.resolve(new Map)}}function aC(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}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function cC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){BR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function lC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function dC(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 uC(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 hC(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?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function pC(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?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var mC=Object.freeze({__proto__:null,shimOnTrack:rC,shimPeerConnection:oC,shimSenderGetStats:sC,shimReceiverGetStats:aC,shimRemoveStream:cC,shimRTCDataChannel:lC,shimAddTransceiver:dC,shimGetParameters:uC,shimCreateOffer:hC,shimCreateAnswer:pC,shimGetUserMedia:nC,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,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function _C(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){this._localStreams||(this._localStreams=[]),this._localStreams.includes(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,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(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=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function fC(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=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});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 gC(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),Promise.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),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function TC(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(EC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function EC(e){return e&&void 0!==e.video?Object.assign({},e,{video:jR(e.video)}):e}function SC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(BR("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function IC(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 vC(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 yC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var AC=Object.freeze({__proto__:null,shimLocalStreamsAPI:_C,shimRemoteStreamsAPI:fC,shimCallbacksAPI:gC,shimGetUserMedia:TC,shimConstraints:EC,shimRTCIceServerUrls:SC,shimTrackEventTransceiver:IC,shimCreateOfferLegacy:vC,shimAudioContext:yC}),RC={},CC={get exports(){return RC},set exports(e){RC=e}};!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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<n.length;r++)i=n[r].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const r=n[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const n=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=o.length?t.parseFmtp(o[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[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 d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),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 t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(CC);var bC=RC,kC=e({__proto__:null,default:bC},[RC]);function NC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=bC.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,xR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function DC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xR(e,"icecandidate",(e=>{if(e.candidate){const t=bC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function OC(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=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(function(e){if(!e||!e.sdp)return!1;const t=bC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=bC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=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}(arguments[0]),i=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}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=bC.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>r}),this._sctp=o}return i.apply(this,arguments)}}function wC(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},xR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function PC(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 LC(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"!==e.trim())).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 MC(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?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xC(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 VC=Object.freeze({__proto__:null,shimRTCIceCandidate:NC,shimRTCIceCandidateRelayProtocol:DC,shimMaxMessageSize:OC,shimSendThrowTypeError:wC,shimConnectionState:PC,removeExtmapAllowMixed:LC,shimAddIceCandidateNullOrEmpty:MC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=FR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=MR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=MR(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=MR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:VC,extractVersion:MR,disableLog:VR,disableWarnings:UR,sdp:kC};switch(n.browser){case"chrome":if(!iC||!eC||!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=iC,MC(e,n),xC(e),zR(e,n),KR(e),eC(e,n),YR(e),ZR(e,n),qR(e),QR(e),XR(e),tC(e,n),NC(e),DC(e),PC(e),OC(e,n),wC(e),LC(e,n);break;case"firefox":if(!mC||!oC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=mC,MC(e,n),xC(e),nC(e,n),oC(e,n),rC(e),cC(e),sC(e),aC(e),lC(e),dC(e),uC(e),hC(e),pC(e),NC(e),PC(e),OC(e,n),wC(e);break;case"safari":if(!AC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=AC,MC(e,n),xC(e),SC(e),vC(e),gC(e),_C(e),fC(e),IC(e),TC(e),yC(e),NC(e),DC(e),OC(e,n),wC(e),LC(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var UC,FC=Object.create,BC=Object.defineProperty,HC=Object.defineProperties,jC=Object.getOwnPropertyDescriptor,GC=Object.getOwnPropertyDescriptors,WC=Object.getOwnPropertyNames,JC=Object.getOwnPropertySymbols,zC=Object.getPrototypeOf,KC=Object.prototype.hasOwnProperty,YC=Object.prototype.propertyIsEnumerable,qC=Reflect.get,QC=Math.pow,XC=(e,t,i)=>t in e?BC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,$C=(e,t)=>{for(var i in t||(t={}))KC.call(t,i)&&XC(e,i,t[i]);if(JC)for(var i of JC(t))YC.call(t,i)&&XC(e,i,t[i]);return e},ZC=(e,t)=>HC(e,GC(t)),eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tb=(e,t)=>{for(var i in t)BC(e,i,{get:t[i],enumerable:!0})},ib=(e,t,i)=>(i=null!=e?FC(zC(e)):{},((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of WC(t))!KC.call(e,r)&&r!==i&&BC(e,r,{get:()=>t[r],enumerable:!(n=jC(t,r))||n.enumerable});return e})(!t&&e&&e.__esModule?i:BC(i,"default",{value:e,enumerable:!0}),e)),nb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?jC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&BC(t,i,o),o},rb=(e,t,i)=>(XC(e,"symbol"!=typeof t?t+"":t,i),i),ob=(e,t,i)=>qC(zC(e),i,t),sb=(e,t,i)=>new Promise(((n,r)=>{var o=e=>{try{a(i.next(e))}catch(t){r(t)}},s=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),ab=eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,r,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},c.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,o),!0;case 6:return d.fn.call(d.context,t,i,r,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,r);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||r&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),cb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),lb=eb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))})(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=cb(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,s,r)}})),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}})),db=eb(((e,t)=>{var i=cb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?n.push(i[t.name][s]):n.push(i[t.names[o]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,r=t.innerOrder||a,c=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ub=eb((e=>{var t=lb(),i=db();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),hb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),pb=eb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))})(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=hb(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,s,r)}})),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}})),mb=eb(((e,t)=>{var i=hb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?n.push(i[t.name][s]):n.push(i[t.names[o]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,r=t.innerOrder||a,c=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),_b=eb((e=>{var t=pb(),i=mb();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),fb=ib(ab()),gb=((UC=gb||{})[UC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",UC[UC.INVALID_OPERATION=4097]="INVALID_OPERATION",UC[UC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",UC[UC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",UC[UC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",UC[UC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",UC[UC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",UC[UC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",UC[UC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",UC[UC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",UC[UC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",UC[UC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",UC[UC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",UC[UC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",UC[UC.CLIENT_BANNED=16448]="CLIENT_BANNED",UC[UC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",UC[UC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",UC[UC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",UC[UC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",UC[UC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",UC[UC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",UC[UC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",UC[UC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",UC[UC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",UC[UC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",UC[UC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",UC[UC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",UC[UC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",UC[UC.UNKNOWN=65535]="UNKNOWN",UC),Tb=gb,Eb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:n=Tb.UNKNOWN,extraCode:r=0,constraint:o}=e,s="<".concat(function(e){for(let t in Tb)if(Tb[t]===e)return t;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),rb(this,"code"),rb(this,"extraCode"),rb(this,"message"),rb(this,"originMessage"),rb(this,"name"),rb(this,"constraint"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Sb=Eb,Ib=((new Date).getTime(),0),vb=function(){return(new Date).getTime()+Ib},yb=function(){let e=new Date;return e.setTime(vb()),e.toLocaleString()},Ab={};tb(Ab,{bytes2ms:()=>ZD,convertObjectNumberToInt:()=>JO,copyProperties:()=>$D,deepClone:()=>PO,deepMerge:()=>wO,env:()=>Rb,fibonacci:()=>sO,formatedTime:()=>VO,getConstructorName:()=>SO,getContainerFromElement:()=>MO,getEnv:()=>HD,getInternalVersion:()=>RO,getLoggerUrl:()=>GD,getMuteStateFromFlag:()=>kO,getNetworkQuality:()=>NO,getNetworkType:()=>KD,getNumNetworkType:()=>QD,getOSType:()=>JD,getReconnectionTimeout:()=>aO,getStringByteLength:()=>BO,getSysInfo:()=>XD,getTerminalType:()=>WD,getTurnServer:()=>DO,getUint32Version:()=>WO,getValueType:()=>cO,getViewListFromView:()=>LO,glog:()=>nO,ipv4ToUint32:()=>OO,isArray:()=>_O,isAudioWorkletSupported:()=>IO,isBoolean:()=>pO,isConstructor:()=>EO,isEmpty:()=>bO,isFunction:()=>lO,isLangChinese:()=>rO,isMediaStreamTrack:()=>fO,isNumber:()=>hO,isObject:()=>mO,isOverseaSdkAppId:()=>jD,isPlainObject:()=>oO,isPortrait:()=>jO,isPromise:()=>TO,isRemoteTrack:()=>gO,isString:()=>uO,isUndefined:()=>dO,loadImage:()=>GO,logVisibilityState:()=>HO,ms2bytes:()=>tO,ms2samples:()=>iO,performanceNow:()=>yO,promiseAny:()=>vO,samples2ms:()=>eO,setNetworkType:()=>qD,stringify:()=>UO,stringifyIncludeValue:()=>FO});var Rb={};tb(Rb,{ANDROID_VERSION:()=>Ub,CHROME_MAJOR_VERSION:()=>Fk,CHROME_VERSION:()=>Bk,EDGE_VERSION:()=>Jb,EDG_MAJOR_VERSION:()=>Yb,EDG_VERSION:()=>Kb,FIREFOX_MAJOR_VERSION:()=>Gb,FIREFOX_VERSION:()=>jb,HUAWEI_VERSION:()=>kk,IE_VERSION:()=>ok,IOS_MAIN_VERSION:()=>zk,IOS_VERSION:()=>Jk,IPADQQB_VERSION:()=>fk,IS_ANDROID:()=>Vb,IS_ANDROID_WEBVIEW:()=>Wk,IS_ANY_SAFARI:()=>jk,IS_CHROME:()=>Vk,IS_CHROME_OS:()=>Sk,IS_CHROMIUM_BASE:()=>xk,IS_EDG:()=>zb,IS_EDGE:()=>Wb,IS_ELECTRON:()=>yk,IS_FIREFOX:()=>Hb,IS_HEADLESS_CHROME:()=>Uk,IS_HUAWEI:()=>bk,IS_HUAWEIBROWSER:()=>Ck,IS_IE:()=>rk,IS_IE8:()=>nk,IS_IOS:()=>xb,IS_IOS_13_OR_14:()=>qk,IS_IOS_15_1:()=>Yk,IS_IPAD:()=>wb,IS_IPADQQB:()=>_k,IS_IPAD_PRO:()=>Pb,IS_IPHONE:()=>Lb,IS_IPOD:()=>Mb,IS_LINUX:()=>Ek,IS_LOCAL:()=>Qk,IS_MAC:()=>Tk,IS_MACQQB:()=>pk,IS_MIBROWSER:()=>Ak,IS_MQQB:()=>lk,IS_NATIVE_ANDROID:()=>Bb,IS_OLD_ANDROID:()=>Fb,IS_OPPOBROWSER:()=>Ok,IS_SAFARI:()=>Hk,IS_SAFARI_15_1:()=>Kk,IS_SAMSUNGBROWSER:()=>Nk,IS_SOGOU:()=>Xb,IS_SOGOUM:()=>qb,IS_TBS:()=>Zb,IS_UCBROWSER:()=>vk,IS_VIVOBROWSER:()=>Pk,IS_WECHAT:()=>sk,IS_WIN:()=>gk,IS_WQQB:()=>uk,IS_WX:()=>Ik,IS_X5MQQB:()=>ck,IS_XWEB:()=>tk,MACQQB_VERSION:()=>mk,MI_VERSION:()=>Rk,MQQB_VERSION:()=>dk,OPPO_VERSION:()=>wk,SAFARI_VERSION:()=>Gk,SAMSUNG_VERSION:()=>Dk,SOGOUM_VERSION:()=>Qb,SOGOU_VERSION:()=>$b,TBS_VERSION:()=>ek,USER_AGENT:()=>Cb,VIVO_VERSION:()=>Lk,WECHAT_VERSION:()=>ak,WQQB_VERSION:()=>hk,XWEB_VERSION:()=>ik,browserInfo:()=>$k,getBrowserInfo:()=>Zk,getChromeMajorVersion:()=>Mk,getOSName:()=>nN,getOSString:()=>rN,getUserAgentData:()=>tN,isLocalStorageEnabled:()=>Xk});var Cb="undefined"==typeof navigator?"":navigator.userAgent,bb=e=>new RegExp(e,"i").test(Cb),kb=e=>{if(bb(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=Cb.match(t);if(i&&i[1])return i[1]}return""},Nb=e=>{if(bb(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=Cb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},Db=/AppleWebKit\/([\d.]+)/i.exec(Cb),Ob=Db?parseFloat(Db[1]):NaN,wb=bb("iPad"),Pb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&bb("Macintosh"),Lb=bb("iPhone")&&!wb,Mb=bb("iPod"),xb=Lb||wb||Mb||Pb,Vb=bb("Android"),Ub=function(){if(Vb){let e=Cb.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),Fb=Vb&&bb("webkit")&&Ub<2.3,Bb=Vb&&Ub<5&&Ob<537,Hb=bb("Firefox"),jb=kb("Firefox"),Gb=Nb("Firefox"),Wb=bb("Edge"),Jb=kb("Edge"),zb=bb("Edg"),Kb=kb("Edg"),Yb=Nb("Edg"),qb=bb("SogouMobileBrowser"),Qb=kb("SogouMobileBrowser"),Xb=bb("MetaSr\\s"),$b=kb("MetaSr\\s"),Zb=bb("TBS"),ek=kb("TBS"),tk=bb("XWEB"),ik=kb("XWEB"),nk=bb("MSIE\\s8\\.0"),rk=bb("MSIE\\/\\d+"),ok=function(){if(rk){let e=/MSIE\s(\d+)\.\d/.exec(Cb),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(Cb)&&/rv:11.0/.test(Cb)&&(t=11),t}return NaN}(),sk=bb("(micromessenger|webbrowser)"),ak=kb("MicroMessenger"),ck=!Zb&&bb("MQQBrowser")&&bb("COVC"),lk=!Zb&&bb("MQQBrowser")&&!bb("COVC"),dk=lk||ck?kb("MQQBrowser"):"",uk=!Zb&&bb(" QQBrowser"),hk=kb(" QQBrowser"),pk=!Zb&&bb("QQBrowserLite"),mk=kb("QQBrowserLite"),_k=!Zb&&bb("MQBHD"),fk=kb("MQBHD"),gk=bb("Windows"),Tk=!xb&&bb("MAC OS X"),Ek=!Vb&&bb("Linux"),Sk=bb("CrOS"),Ik=bb("MicroMessenger"),vk=bb("UCBrowser"),yk=bb("Electron"),Ak=bb("MiuiBrowser"),Rk=kb("MiuiBrowser"),Ck=bb("HuaweiBrowser"),bk=bb("Huawei"),kk=kb("HuaweiBrowser"),Nk=bb("SamsungBrowser"),Dk=kb("SamsungBrowser"),Ok=bb("HeyTapBrowser"),wk=kb("HeyTapBrowser"),Pk=bb("VivoBrowser"),Lk=kb("VivoBrowser"),Mk=()=>Nb("Chrome"),xk=bb("Chrome"),Vk=!Wb&&!Xb&&!qb&&!Zb&&!tk&&!zb&&!uk&&!Ak&&!Ck&&!Nk&&!Ok&&!Pk&&xk,Uk=bb("HeadlessChrome"),Fk=Mk(),Bk=kb("Chrome"),Hk=!xk&&!lk&&!ck&&!pk&&!_k&&bb("Safari"),jk=Hk||xb,Gk=kb("Version"),Wk=/Android.*(wv|.0.0.0)/.test(Cb),Jk=(()=>{if(Pb)return Gk;if(xb){let e=Cb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),zk=Number(Jk.split(".")[0]),Kk="15.1"===Gk,Yk="15.1"===Jk,qk=(()=>{let e=Number(Jk.split(".")[0]);return 14===e||13===e})(),Qk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Xk=(()=>{let e;return()=>{if(dO(e))try{e=!!window.localStorage}catch(GP){e=!1}return e}})(),$k=Zk();function Zk(){let e=new Map([[Hb,["Firefox",jb]],[zb,["Edg",Kb]],[Vk,["Chrome",Bk]],[Hk,["Safari",Gk]],[Zb,["TBS",ek]],[tk,["XWEB",ik]],[sk&&Lb,["WeChat",ak]],[uk,["QQ(Win)",hk]],[lk,["QQ(Mobile)",dk]],[ck,["QQ(Mobile X5)",dk]],[pk,["QQ(Mac)",mk]],[_k,["QQ(iPad)",fk]],[Ak,["MI",Rk]],[Ck,["HW",kk]],[Nk,["Samsung",Dk]],[Ok,["OPPO",wk]],[Pk,["VIVO",Lk]],[Wb,["EDGE",Jb]],[qb,["SogouMobile",Qb]],[Xb,["Sogou",$b]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var eN=null;function tN(){return sb(this,null,(function*(){if(eN)return eN;if(!navigator.userAgentData||!lO(navigator.userAgentData.getHighEntropyValues))return null;try{return eN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(qU){return null}}))}var iN=new Map([[Vb,"Android"],[xb,"iOS"],[gk,"Windows"],[Tk,"MacOS"],[Ek,"Linux"],[Sk,"ChromeOS"]]),nN=function(){return iN.get(!0)?iN.get(!0):eN?eN.platform:"unknown"},rN=()=>{let e=nN();return e+="/".concat($k.name,"/").concat(Hk?$k.version:$k.version.split(".")[0]),null!=eN&&eN.platformVersion&&(e+="/".concat(eN.platformVersion)),null!=eN&&eN.architecture&&(e+="/".concat(eN.architecture)),e},oN={};tb(oN,{AUDIO_MUTE_BIT:()=>JN,AUDIO_STAT_BIT:()=>WN,AUX_STAT_BIT:()=>GN,AUX_STREAM_MSID:()=>YN,BACKEND_ENV:()=>FN,BASE_DOC_URL:()=>IN,BASE_HOST:()=>gN,CAPABILITIES_KEYS:()=>FD,CLASS_NAME:()=>CD,CLOUD_CONSOLE_URL:()=>SN,DATA_FREEZE_TIMING:()=>ED,DOC_URL:()=>vN,DTLS_STATE_UNKNOWN:()=>rD,ENV_NAME:()=>bN,EXCHANGE_SDP_TIMEOUT:()=>mD,INTERVAL:()=>VD,IS_WORKER:()=>hN,IS_WORKLET:()=>pN,KIBANA_EVENT:()=>uD,LOCAL_STREAM_PUBLISH_STATE:()=>TD,LOGGER_CMD_TYPE:()=>CN,LOGGER_DOMAIN:()=>yN,LOGGER_DOMAIN_OVERSEA:()=>AN,LOG_LEVEL:()=>kN,LOG_LEVEL_NAME:()=>OD,MAIN_STREAM_MSID:()=>KN,MICROPHONE_COMMUNICATIONS:()=>DD,MICROPHONE_DEFAULT:()=>kD,NAME:()=>VN,NETWORK_TYPE:()=>ON,NOT_SUPPORTED_H264:()=>gD,PAUSED_RETRY_COUNT:()=>bD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>yD,PEER_CONNECTION_STATE:()=>oD,PEER_LEAVE_REASON:()=>wD,RAF:()=>xD,RECOVER_CAPTURE_INTERVAL:()=>LD,REMOTE_STREAM_TYPE_AUX:()=>QN,REMOTE_STREAM_TYPE_MAIN:()=>qN,RENDER_FREEZE_TIMING:()=>SD,RIC:()=>MD,SCHEDULE_DOMAIN:()=>AD,SCHEDULE_TIMEOUT:()=>RD,SDP_SEMANTICS_PLAN_B:()=>fD,SDP_SEMANTICS_UNIFIED_PLAN:()=>_D,SECOND_HOST:()=>TN,SIGNAL_PING_PONG_INTERVAL:()=>DN,SIGNAL_PING_TIMEOUT:()=>NN,SIGNAL_RECONNECTION_COUNT:()=>dD,SMALL_STAT_BIT:()=>jN,SPEAKER_DEFAULT:()=>ND,STORAGE_EXPIRES_TIME:()=>wN,STREAM_TYPE_BIG:()=>ID,STREAM_TYPE_SMALL:()=>vD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>PD,SYNC_USER_LIST_INTERVAL:()=>hD,Scene:()=>BN,Switch:()=>PN,THIRD_HOST:()=>EN,TIMEOUT:()=>UD,TRANSPORT_DIRECTION:()=>UN,TRTC_ERROR_ASSISTANCE:()=>RN,TRTC_QUALITY_BAD:()=>tD,TRTC_QUALITY_DISCONNECTED:()=>nD,TRTC_QUALITY_EXCELLENT:()=>$N,TRTC_QUALITY_GOOD:()=>ZN,TRTC_QUALITY_POOR:()=>eD,TRTC_QUALITY_UNKNOWN:()=>XN,TRTC_QUALITY_VERY_BAD:()=>iD,UPDATE_OFFER_TIMEOUT:()=>pD,VIDEO_MUTE_BIT:()=>zN,VIDEO_STAT_BIT:()=>HN,audioProfileMap:()=>LN,getRetryCount:()=>cD,getScriptDir:()=>mN,innerVersion:()=>sN,loggerProxy:()=>_N,screenProfileMap:()=>xN,setLoggerProxy:()=>fN,setRetryCount:()=>aD,setVersion:()=>cN,version:()=>aN,videoProfileMap:()=>MN});var sN="4.15.00.1600",aN="5.0.0";function cN(e){aN=e;let[t,i,n]=e.split(".").map((e=>parseInt(e,10)));sN="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,n),".").concat(i.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var lN,dN,uN,hN="undefined"!=typeof importScripts,pN="undefined"!=typeof registerProcessor,mN=()=>{let e=hN?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},_N="",fN=e=>_N=e,gN="web.sdk.qcloud.com",TN="web.sdk.tencent.cn",EN="web.sdk.cloud.tencent.cn",SN="https://console.cloud.tencent.com/trtc",IN="https://".concat(gN,"/trtc/webrtc/v5/doc"),vN="".concat(IN,"/zh-cn/"),yN="https://yun.tim.qq.com",AN="https://apisgp.my-imcloud.com",RN="trtc_error_assistance",CN={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},bN={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},kN=((uN=kN||{})[uN.TRACE=0]="TRACE",uN[uN.DEBUG=1]="DEBUG",uN[uN.INFO=2]="INFO",uN[uN.WARN=3]="WARN",uN[uN.ERROR=4]="ERROR",uN[uN.NONE=5]="NONE",uN),NN=18e3,DN=2e3,ON={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},wN=6048e5,PN=((dN=PN||{}).USEAINS="useAINS",dN.ENABLEDEBUG="enableDebug",dN.USEV2="useV2",dN.USEWT="useWt",dN),LN={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},MN={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},xN={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},VN={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},UN={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},FN={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},BN=((lN=BN||{}).LIVE="live",lN.RTC="rtc",lN),HN=1,jN=2,GN=4,WN=8,JN=64,zN=16,KN="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",YN="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",qN=VN.MAIN,QN=VN.AUXILIARY,XN=0,$N=1,ZN=2,eD=3,tD=4,iD=5,nD=6,rD="unknown",oD={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},sD=1/0;function aD(e){sD=e}function cD(){return sD}var lD,dD=30,uD={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},hD=1e4,pD=1e4,mD=1e4,_D="unified-plan",fD="plan-b",gD=1028,TD=((lD=TD||{})[lD.UNPUBLISH=-1]="UNPUBLISH",lD[lD.PUBLISHING=0]="PUBLISHING",lD[lD.PUBLISHED=1]="PUBLISHED",lD),ED=500,SD=1e3,ID=VN.BIG,vD=VN.SMALL,yD=1e4,AD={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},RD=2e3,CD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},bD=5,kD="default",ND=kD,DD="communications",OD=Object.keys(kN),wD=["normal leave","timeout leave","kick","role change"],PD=10,LD=2e3,MD="ric",xD="raf",VD="interval",UD="timeout",FD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],BD=1e8,HD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},jD=e=>Number(e)<14e8,GD=function(e,t){let i;i=_N||(jD(e)?AN:yN);let n=Math.floor(Math.random()*QC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function WD(){return Vb?4:Lb?2:wb?3:Tk?12:gk?5:Ek?13:1}function JD(){return Vb?"Android":Lb?"iPhone":wb?"iPad":Tk?"Mac":gk?"Windows":Ek?"Linux":"unknown"}var zD="unknown";function KD(){if("unknown"!==zD)return zD;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===r&&(r="2g"),n&&(zD=YD(n,r)),zD}function YD(e,t){if(ON[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function qD(e){zD=YD(e)}function QD(){return ON[KD()]}var XD=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:WD(),uint32_device_type:0,str_os_verion:JD(),uint32_link_type:1,str_client_version:sN,uint32_net_type:ON[KD()],ua:navigator.userAgent,version:""}}}};function $D(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,n)}return e}function ZD(e){return eO(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function eO(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function tO(e){return 4*iO(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function iO(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var nO="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},rO=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},oO=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function sO(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:sO(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function aO(e){return e>8?3e4:1e3*sO(e)}function cO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var lO=e=>"function"==typeof e,dO=e=>void 0===e,uO=e=>"string"==typeof e,hO=e=>"number"==typeof e,pO=e=>"boolean"==typeof e,mO=e=>"object"===cO(e),_O=e=>"array"===cO(e),fO=e=>cO(e)==="MediaStreamTrack".toLowerCase(),gO=e=>e.isRemote,TO=e=>"promise"===cO(e),EO=e=>lO(e)&&e.prototype.constructor===e,SO=e=>EO(e)?e.prototype.constructor.name:"",IO="undefined"!=typeof AudioWorkletNode;function vO(e){return new Promise(((t,i)=>{let n=[];e.forEach((r=>{r.then(t).catch((t=>{n.push(t),n.length===e.length&&i(n)}))}))}))}function yO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var AO=e=>+e<10?"0".concat(e):e,RO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),n=AO(i[1])+AO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(n)},CO=Object.prototype.hasOwnProperty;function bO(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(oO(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(CO.call(e,t))return!1;return!0}return!1}function kO(e,t){return{userId:t,hasAudio:!!(e&WN),hasVideo:!!(e&HN),hasAuxiliary:!!(e&GN),hasSmall:!!(e&jN),audioMuted:!!(e&JN),videoMuted:!!(e&zN),audioAvailable:!(!(e&WN)||e&JN),videoAvailable:!(!(e&HN)||e&zN)}}function NO(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}function DO(e){let t={urls:"turn:".concat(e.url)};return!dO(e.username)&&!dO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",dO(e.credentialType)||(t.credentialType=e.credentialType)),t}function OO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!uO(e))return 0;let i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var wO=function(e,t,i,n){if(!mO(e)||!mO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(r=s[a],!(dO(t[r])||i&&i.includes(r)))if(mO(e[r])&&mO(t[r]))o+=wO(e[r],t[r],i,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=PO(t[r]),o+=1)}return o};function PO(e){if(_O(e)){let t=[];return e.forEach(((e,i)=>{t[i]=PO(e)})),t}if(mO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=PO(e[i])})),t}return e}var LO=e=>{let t=[];if(_O(e))t=[...e];else if(uO(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},MO=e=>uO(e)?document.getElementById(e):e,xO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),VO=()=>xO.format(new Date);function UO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(_O(e))return"[".concat(e.map((e=>UO(e,{keysToInclude:i,keysToExclude:n}))).join(","),"]");if(!oO(e)||!_O(i)&&!_O(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach((s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=oO(e[s])||_O(e[s])?JSON.parse(UO(e[s],{keysToExclude:n,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(lD){return"{}"}}function FO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((n=>{t===e[n]&&i.push(n)})),UO(e,{keysToInclude:i})}function BO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var HO=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&ew.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{ew.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),jO=()=>{var e,t,i,n;return null!=(e=window.screen)&&e.orientation?!(null==(n=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)||!n.includes("portrait")):0===window.orientation||180===window.orientation},GO=e=>sb(void 0,null,(function*(){return new Promise(((t,i)=>{let n;if(uO(e))n=new Image,n.crossOrigin="anonymous",n.src=e;else if(n=e,n.complete)return void t(n);n.onload=()=>t(n),n.onerror=i}))})),WO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},JO=e=>(Object.keys(e).forEach((t=>{hO(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(oO(e[t])||_O(e[t]))&&JO(e[t])})),e);function zO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=r||5e3,o.open(n||"POST",t,!0),o.send(i)}))}function KO(e){return sb(this,null,(function*(){let t=yO(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let e=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),n=yield(yield(yield new Response(e)).blob()).arrayBuffer();return ew.debug("compressJSON ".concat(i.length," -> ").concat(n.byteLength," ").concat(yO()-t,"ms")),n}catch(lD){return i}}))}var YO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>sb(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},s=()=>{2!==m&&h<(lO(d)?d():d)?(h++,m=1,lO(r)&&r.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),lO(u)?u(h):u)):(t(),lO(o)&&o.call(this,f))};lO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},qO=class{constructor(e){rb(this,"userId"),rb(this,"remoteUserId"),rb(this,"id"),rb(this,"sdkAppId"),rb(this,"type"),rb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!pO(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),ew.log(e,t,dO(this.userId)||bO(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}},QO=new(ib(ab(),1).default),XO=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e))(XO||{}),$O=XO,ZO=!(xb||Vb||Uk),ew=new class{constructor(){rb(this,"_isEnableUploadLog",!0),rb(this,"_localJoinedUser",new Map),rb(this,"_queue",[]),rb(this,"_timeoutId",-1),rb(this,"_logLevel",1),rb(this,"_logLevelToUpload",2),!hN&&!pN&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){QO.on($O.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&kN[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),QO.on($O.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),QO.once($O.JOIN_FAILED,(()=>{this.startUpload()})),QO.on($O.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]})}));else if(uO(i.userId)&&hO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return sb(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:n,logs:r}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:yb(),sdkAppId:String(n),userId:i,version:aN,log:r.map((e=>e.log)).join("\n")}),n),r.forEach((e=>e.uploaded=!0))}}catch(dN){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return YO({retryFunction:()=>zO({url:GD(t,CN.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(vb());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(kN[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){dO(kN[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(uO(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(lN){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:n,sdkAppId:r,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=kN[e])?void 0:o.toLowerCase())||"info";ZO?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[s](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new qO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;kN[t]&&(this._logLevelToUpload=t)}},tw=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},iw=new class{constructor(){rb(this,"_prefix","TRTC"),rb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Xk()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(Xk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(GP){ew.warn(GP)}}getItem(e){if(!Xk())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(lN){ew.warn(lN)}}setItem(e,t){if(Xk())try{let i={expiresIn:Date.now()+wN,value:t};this._queue.set(this.getRealKey(e),i)}catch(lD){ew.warn(lD)}}deleteItem(e){if(!Xk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(lN){return ew.warn(lN),!1}}clear(){if(Xk())try{localStorage.clear()}catch(GP){ew.warn(GP)}}},nw={};tb(nw,{HTTPS_API:()=>Aw,IS_GET_CAPABILITIES_SUPPORTED:()=>Hw,IS_GET_SETTINGS_SUPPORTED:()=>Bw,IS_SEI_SUPPORTED:()=>jw,IS_SPC_SUPPORTED:()=>xw,basis:()=>Kw,checkSystemRequirementsInternal:()=>Iw,decodeSupportStatus:()=>Sw,encodeSupportStatus:()=>Ew,getBrowserInfo:()=>hw,getDisplayResolution:()=>Cw,isAddTransceiverSupported:()=>Mw,isBrowserSupported:()=>pw,isGetReceiversSupported:()=>ww,isGetSendersSupported:()=>Pw,isGetTransceiversSupported:()=>Lw,isGetUserMediaSupported:()=>bw,isMediaDevicesSupported:()=>_w,isMediaSessionSupported:()=>Jw,isMediaStreamTrackProcessorSupported:()=>Tw,isReplaceTrackSupported:()=>Uw,isScreenCaptureApiAvailable:()=>yw,isSelectedCandidatePair:()=>Rw,isSetParametersSupported:()=>Fw,isSmallStreamAPISupported:()=>Nw,isSmallStreamSupported:()=>Dw,isStopTransceiverSupported:()=>Vw,isTRTCSupported:()=>vw,isUnifiedPlanDefault:()=>Ow,isUsedInHttpProtocol:()=>gw,isWebAudioSupported:()=>kw,isWebCodecSupported:()=>Ww,isWebCodecsSupported:()=>mw,isWebRTCSupported:()=>Gw,isWebTransportSupported:()=>zw});var rw={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},ow={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(cO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(cO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:n}=e;return"failed to subscribe ".concat(i," ").concat(n," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:n,maxSizeInSecond:r}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(r," bytes"):n," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},sw=(e,t)=>t?"".concat(IN,"/").concat(e,"/").concat(t):"".concat(IN,"/").concat(e,"/index.html"),aw=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(RN);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n}}return{}};function cw(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o="",s="",a="";lO(ow[t])?o=ow[t](i):uO(ow[t])&&(o=ow[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=aw();n?a="".concat(n.className,".html#").concat(n.fnName):l&&l[t]&&(lO(l[t])?a=l[t](i):uO(l[t])&&(a=l[t]));let d=o;return rO()&&(c&&c[t]&&(lO(c[t])?s=c[t](i):uO(c[t])&&(s=c[t])),s&&(d=r?"".concat(s,"\n请查看文档: ").concat(sw("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),r&&(d+=" \nRefer to: ".concat(sw("en",a),"\n")),d}var lw=ib(ub(),1),dw={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},uw=new Map([[Hb,["Firefox",jb]],[zb,["Edg",Kb]],[Vk,["Chrome",Bk]],[Hk,["Safari",Gk]],[Zb,["TBS",ek]],[tk,["XWEB",ik]],[sk&&Lb,["WeChat",ak]],[uk,["QQ(Win)",hk]],[lk,["QQ(Mobile)",dk]],[ck,["QQ(Mobile X5)",dk]],[pk,["QQ(Mac)",mk]],[_k,["QQ(iPad)",fk]],[Ak,["MI",Rk]],[Ck,["HW",kk]],[Nk,["Samsung",Dk]],[Ok,["OPPO",wk]],[Pk,["VIVO",Lk]],[Wb,["EDGE",Jb]],[qb,["SogouMobile",Qb]],[Xb,["Sogou",$b]]]);function hw(){let e=uw.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var pw=function(){return!(vk||Wb||zb&&Yb<80||Hb&&Gb<56)},mw=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},_w=function(){if(!navigator.mediaDevices)return gw()||ew.error(ow.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},fw=!1;function gw(){return"http:"===location.protocol&&!Qk&&(fw||ew.error(cw({key:rw.NOT_SUPPORTED_HTTP})),fw=!0,!0)}var Tw=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},Ew=function(){return sb(this,null,(function*(){if(dw.detail.isH264EncodeSupported||dw.detail.isVp8EncodeSupported)return{isH264EncodeSupported:dw.detail.isH264EncodeSupported,isVp8EncodeSupported:dw.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection,r=document.createElement(VN.CANVAS);r.getContext("2d");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),dw.detail.isH264EncodeSupported=t,dw.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:dw.detail.isH264EncodeSupported,isVp8EncodeSupported:dw.detail.isVp8EncodeSupported}}catch(lD){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},Sw=function(){return sb(this,null,(function*(){if(dw.detail.isH264DecodeSupported&&dw.detail.isVp8DecodeSupported)return{isH264DecodeSupported:dw.detail.isH264DecodeSupported,isVp8DecodeSupported:dw.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection;return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(lD){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},Iw=function(){return sb(this,null,(function*(){if(dw.result)return dw;let e=pw(),t=Gw(),i=mw(),n=_w(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield Ew(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield Sw();if(!r||!o){let e=yield Ew();r=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(r&&s&&(Ok||Pk||Wk)&&!Zb&&Mk()<79){let{encode:e,decode:t}=yield function(){return sb(this,null,(function*(){return new Promise((e=>sb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let n=document.createElement("canvas"),r=n.getContext("2d");n.width=640,n.height=480;let o=setInterval((()=>{r.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),3e3);let c=n.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=lw.default.parse(h.sdp),m=p.media[0].rtp.findIndex((e=>"H264"===e.codec));p.media[0].rtp=[p.media[0].rtp[m]],p.media[0].fmtp=p.media[0].fmtp.filter((e=>e.payload===p.media[0].rtp[0].payload)),p.media[0].rtcpFb&&(p.media[0].rtcpFb=p.media[0].rtcpFb.filter((e=>e.payload===p.media[0].rtp[0].payload))),h.sdp=lw.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>sb(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let n=yield l.getStats(),r=yield d.getStats();t.encode||n.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===VN.VIDEO&&e.framesEncoded>0&&(t.encode=!0)})),t.decode||r.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===VN.VIDEO&&e.framesDecoded>0&&(t.decode=!0)}))}))),500)}catch(n){i(),ew.warn(n),e(t)}}))))}))}();r=e,s=t}return dw.result=e&&t&&n&&(r||o)&&(s||a),dw.detail.isBrowserSupported=e,dw.detail.isWebRTCSupported=t,dw.detail.isWebCodecsSupported=i,dw.detail.isMediaDevicesSupported=n,dw.detail.isScreenShareSupported=yw(),dw.detail.isSmallStreamSupported=Dw(),dw.detail.isH264EncodeSupported=r,dw.detail.isVp8EncodeSupported=o,dw.detail.isH264DecodeSupported=s,dw.detail.isVp8DecodeSupported=a,dw.result||ew.error("".concat(navigator.userAgent," ").concat(FO(dw.detail,!1))),iw.setItem(Yw,{ua:navigator.userAgent,checkResult:dw}),dw}))},vw=function(){return dw.result},yw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)};var Aw=(e,t,i)=>{"http:"===location.protocol&&!Qk&&(e[t]=()=>{throw new Sb({code:Tb.INVALID_OPERATION,message:ow.NOT_SUPPORTED_HTTP})})},Rw=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(pO(e.selected)&&!e.selected)};function Cw(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",i=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(i)}return e}function bw(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function kw(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function Nw(){return"captureStream"in HTMLCanvasElement.prototype}function Dw(){return!(sk||xb||Fk&&Fk<63)&&!(!pw()||!Nw())}var Ow=function(){if(dO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:_D}),e.addTransceiver(VN.AUDIO),t=!0}catch(lN){}return null==e||e.close(),t};function ww(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Pw(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Lw(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Mw(){return 11!==zk&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var xw=!(!Mw()||xk&&Fk<74);function Vw(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Uw(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Fw(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Pw()}var Bw=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Hw=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,jw="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Mk()>=86,Gw=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function Ww(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return dO(window.AudioDecoder)||(e.AudioDecoder=!0),dO(window.AudioEncoder)||(e.AudioEncoder=!0),dO(window.VideoDecoder)||(e.VideoDecoder=!0),dO(window.VideoEncoder)||(e.VideoEncoder=!0),dO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function Jw(){return"mediaSession"in navigator&&!dO(navigator.mediaSession.setActionHandler)}function zw(){return!dO(window.WebTransport)}function Kw(){let e={browser:"".concat($k.name,"/").concat($k.version),os:nN(),displayResolution:Cw(),isScreenShareSupported:yw(),isWebRTCSupported:Gw(),isGetUserMediaSupported:bw(),isWebAudioSupported:kw(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Ww(),isMediaSessionSupported:Jw(),isWebTransportSupported:zw()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var Yw="checkResult";!function(){gw();let e=iw.getItem(Yw);e&&e.ua===navigator.userAgent&&(dw=e.checkResult),Iw()}();var qw=ib(ab(),1),Qw=Symbol("instance"),Xw=Symbol("cacheResult"),$w=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,nP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Zw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var eP=new Map;function tP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=eP.get(n)||[];eP.has(n)||eP.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=rP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return i.sync?n[Xw]:Promise.resolve(n[Xw]);n.state instanceof $w&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;Array.isArray(e)?0==e.length?n.state instanceof $w&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Zw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e.join("|")))):e!==n.state&&(l=new Zw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=n.state,h=new $w(u,t,s);nP.call(n,h);let p=e=>{var r;return n[Xw]=e,h.aborted||(nP.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Xw])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return nP.call(n,u,e),d(new Zw(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var iP="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function nP(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(rP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var rP=class extends qw.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=rP.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Qw];n?this.name=n.name+"-"+n.count++:i[Qw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=eP.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);eP.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=rP.instances.get(e),t||rP.instances.set(e,t=new rP(e,void 0,Object.create(rP.prototype)))):(t=rP.instances2.get(e),t||rP.instances2.set(e,t=new rP(e.constructor.name,void 0,Object.create(rP.prototype)))),t}static getState(e){var t;return null===(t=rP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};iP(rP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){nP.call(this,e)}};rP.STATECHANGED="stateChanged",rP.UPDATEAFSM="updateAFSM",rP.INIT="[*]",rP.ON="on",rP.OFF="off",rP.instances=new Map,rP.instances2=new WeakMap;var oP=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},sP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},aP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),cP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:UD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=$C(e===VD?{delay:2e3,count:0,backgroundTask:!0}:e===MD?{delay:1e4,count:0}:e===xD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),mO(t)&&(i=$C($C({},i),t)),lO(e)&&(t=e,e=UD);let n=$C({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")])));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=yO(),n=()=>{if(t=yO()-i,t>=e.delay&&(i=yO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=oP(n,{timeout:e.delay})};return e.ricID=oP(n,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=yO(),n=()=>document.hidden&&e.backgroundTask?(t=yO()-i,i=yO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=yO()-i,t>=e.delay&&(i=yO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=yO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&aP(n),r&&sP(r),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};cP.taskMap=new Map,cP.currentTaskID=1;var lP=cP;VN.SEI_MESSAGE;var dP={LOADED_DATA:VN.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"},uP=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:aN,env:bN.QCLOUD,browserVersion:$k.name+$k.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r))}logSuccessEvent(e){Qk||!ew.isAbleToUpload||this._configs.env===bN.QCLOUD&&this.uploadEventToKibana(ZC($C({},e),{result:"success"}))}logFailedEvent(e){if(Qk||!ew.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:"failed",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||Tb.UNKNOWN};this._configs.env===bN.QCLOUD&&this.uploadEventToKibana(ZC($C({},o),{error:n}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:n}=e,r={timestamp:yb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:aN,log:t};n&&(r.errorInfo=n.message),this.sendRequest(GD(this._configs.sdkAppId,CN.LOG),r)}sendRequest(e,t){ew.isAbleToUpload?zO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},hP="trtc_autoplay",pP="".concat(hP,"_mask"),mP="".concat(hP,"_wrapper"),_P="".concat(hP,"_header"),fP="".concat(hP,"_content"),gP="".concat(hP,"_action_wrapper"),TP="".concat(hP,"_question"),EP="".concat(hP,"_collapse"),SP="".concat(hP,"_action_confirm"),IP="".concat(hP,"_detail"),vP="#2473E8",yP="dialog",AP="".concat(yP,"-show"),RP="".concat(yP,"-1"),CP="".concat(yP,"-2"),bP=!1,kP=()=>!!document.querySelector(".".concat(mP)),NP="".concat(IN,"/").concat(rO()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),DP="<br><a href='".concat(NP,"' target='_blank'>").concat(rO()?"其他方案?":"Any other solution?","</a>"),OP="".concat(rO()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(DP):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(DP)),wP=class{constructor(){if(rb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),rb(this,"_dialogNode",null),rb(this,"_bodyPosition",""),rb(this,"_showDetail",!1),rb(this,"_isCollapseClicked",!1),rb(this,"_isQuestionClicked",!1),rO()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!bP){let e=document.createElement("style");e.innerHTML=".".concat(pP,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(pP," div:not(.").concat(gP,"){display:block !important;}.").concat(mP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(mP," a{color:").concat(vP,";}.").concat(_P,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(fP,"{margin:8px 0;}.").concat(gP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(EP,"{margin-right:auto;cursor:pointer}.").concat(TP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(SP,"{margin-left:8px;color:#fff;background:").concat(vP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(SP,":hover{opacity:0.9;}.").concat(EP,",.").concat(SP,",.").concat(fP,",.").concat(TP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(mP,"{width:80vw;}}"),document.head.appendChild(e),bP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(pP,"\"><div class='").concat(mP,"'><div class='").concat(_P,"'>").concat(location.host,"</div><div class='").concat(fP,"'>").concat(this.content,"</div><div class='").concat(IP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(OP,"</div><div class='").concat(gP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=SP,t.innerText=rO()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=TP,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=EP,n.innerText="".concat(rO()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(".".concat(gP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r}addDiaLog(){kP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(mP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",ew.info("show autoplay dialog"),uP.uploadEvent({log:AP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){ew.warn("confirm clicked, try resume stream"),QO.emit($O.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(IP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||uP.uploadEvent({log:RP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(NP,"_blank"),this._isQuestionClicked||uP.uploadEvent({log:CP}),this._isQuestionClicked=!0}},PP={};tb(PP,{create:()=>MP,remove:()=>xP});var LP=new WeakMap;function MP(e,t){LP.has(e)||LP.set(e,[]);let i=LP.get(e),n={add:(e,r)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n}function xP(e){let t=LP.get(e);t&&(t.forEach((e=>e())),LP.delete(e))}var VP=class extends rP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,rb(this,"id"),rb(this,"element",null),rb(this,"track"),rb(this,"url"),rb(this,"attr"),rb(this,"muted"),rb(this,"_log"),rb(this,"_pausedRetryCount"),rb(this,"_isElementPlayingFired",!1),rb(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=bD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return sb(this,null,(function*(){if(!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(lN){let t=cw({key:rw.PLAY_FAILED,data:{media:this.kind,error:lN}});if(this.track&&!this.track.muted&&this._log.warn(lN),t.includes("NotAllowedError"))throw new Sb({code:Tb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),this.element.srcObject=null,this.element=null),this.handleStopped(VN.ENDED),this._interval>0&&lP.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Yk?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return MP(this.element,this.element).add(VN.PLAYING,e).add(VN.ENDED,e).add(VN.PAUSE,e).add(VN.ERROR,e).add(VN.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==PP||PP.create(this.track,this.track).add(VN.ENDED,e).add(VN.MUTE,e).add(VN.UNMUTE,e),this.track.readyState===VN.ENDED&&this.handleTrackEvent({type:VN.ENDED}),this.track.muted&&this.handleTrackEvent({type:VN.MUTE})}}bindAutoPlayEvent(){QO.on($O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&xP(this.track)}unbindEvents(){this.element&&xP(this.element),this.unbindTrackEvents(),QO.off($O.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case VN.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(VN.PLAYING),this._interval&&(lP.clearTask(this._interval),this._interval=-1);break;case VN.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(VN.ENDED);break;case VN.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(VN.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=Mk();this._pausedRetryCount>0&&(this.kind===VN.VIDEO&&!kP()||this.kind===VN.AUDIO&&(hO(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),xb&&(this._interval=lP.run(UD,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case VN.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),uP.uploadEvent({log:"stat-".concat(this.kind,"-").concat(uD.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case VN.LOADEDDATA:this.kind===VN.VIDEO&&this.emit(dP.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case VN.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(VN.ENDED);break;case VN.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(VN.MUTE);break;case VN.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(VN.UNMUTE)}}handlePlaying(e){this.emit(dP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(dP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(dP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};nb([tP([],"PLAYING",{sync:!0})],VP.prototype,"handlePlaying",1),nb([tP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],VP.prototype,"handlePaused",1),nb([tP([],"STOPPED",{sync:!0})],VP.prototype,"handleStopped",1);var UP=class extends VP{constructor(e){super(e,VN.VIDEO),rb(this,"viewMirror",!1),rb(this,"objectFit"),rb(this,"container"),rb(this,"canvas"),this.container=e.container,this.canvas=e.canvas,dO(e.viewMirror)||(this.viewMirror=e.viewMirror),dO(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(VN.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(VN.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(VN.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.viewMirror&&this.element){let e=this.element.style.transform;t===VN.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):t===VN.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t;null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){var e;this.setContainer(null),super.stop(),null==(e=this.canvas)||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(dP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}},FP=class{constructor(e){rb(this,"context"),rb(this,"blob_"),rb(this,"ready"),this.context=e.context,this.blob_=new Blob(['class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);'],{type:"application/javascript"}),this.ready=this.addModuleToContext()}addModuleToContext(){return sb(this,null,(function*(){try{yield this.context.audioWorklet.addModule(URL.createObjectURL(this.blob_)),ew.info("worklet addModule success")}catch(GP){ew.info("worklet addModule catch error. ".concat(GP.message))}}))}};"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var BP=new window.AudioContext({sampleRate:48e3}),HP=()=>{"suspended"===BP.state?(BP.resume(),document.addEventListener("click",HP)):"interrupted"===BP.state?BP.resume():document.removeEventListener("click",HP)};document.addEventListener("click",HP),BP.onstatechange=()=>{ew.info("context state: ".concat(BP.state)),HP()};var jP,GP,WP=e=>BP,JP=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=ew.createLogger({id:"kv"}),e&&(QO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===VN.AUDIO?KP.START_MICROPHONE:YP.START_CAMERA,cost:i})})),QO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===VN.AUDIO?KP.START_MICROPHONE:YP.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:WO(this.version||aN),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:n=!0}=e;var r;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(r=this.distributionMap)?void 0:r.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:n=100,useUV:r=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(hO(n))a=Math.floor(i/n);else for(let c=n.length-1;c>0;c--)if(i>n[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:n,split:r}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:n||t+100,value:i,split:r}):n||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let n=Tb.UNKNOWN;hO(i)?n=i:(!dO(i.extraCode)||!dO(i.code))&&(n=i.extraCode||i.code),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:n,useUV:!1})}},zP=((jP=zP||{})[jP.enterRoom=500700]="enterRoom",jP[jP.exitRoom=500701]="exitRoom",jP[jP.switchRole=500702]="switchRole",jP[jP.destroy=500703]="destroy",jP[jP.startLocalAudio=500704]="startLocalAudio",jP[jP.updateLocalAudio=500705]="updateLocalAudio",jP[jP.stopLocalAudio=500706]="stopLocalAudio",jP[jP.startLocalVideo=500707]="startLocalVideo",jP[jP.updateLocalVideo=500708]="updateLocalVideo",jP[jP.stopLocalVideo=500709]="stopLocalVideo",jP[jP.startScreenShare=500710]="startScreenShare",jP[jP.updateScreenShare=500711]="updateScreenShare",jP[jP.stopScreenShare=500712]="stopScreenShare",jP[jP.startRemoteVideo=500713]="startRemoteVideo",jP[jP.updateRemoteVideo=500714]="updateRemoteVideo",jP[jP.stopRemoteVideo=500715]="stopRemoteVideo",jP[jP.muteRemoteAudio=500716]="muteRemoteAudio",jP[jP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",jP),KP=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(KP||{}),YP=((GP=YP||{})[GP.START_CAMERA=511700]="START_CAMERA",GP),qP=new JP(!0),QP=new JP(!1),XP=qP,$P=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.preNodeReconnect(),this.reconnect(),XP.addSuccessEvent({key:502701})}catch(lD){ew.error(lD),XP.addFailedEvent({key:502701,error:lD})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),XP.addSuccessEvent({key:502702})}catch(lN){ew.error(lN),XP.addFailedEvent({key:502702,error:lN})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},ZP=class extends $P{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,n="M".concat(t,",").concat(i);for(let r=0;r<e.length;r++)i=e[r]/128*100/2,n+="L".concat(t,",").concat(i),t+=1;return n}},eL=class{constructor(){this.source=new $P,this.gain=new $P,this.destination=new $P}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t=nL.get(e);if(t)return t;let i=WP();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return nL.set(e,t),t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},tL=class extends eL{constructor(e){super(),this.context=e,this.denoiser=new $P,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}},iL=class{constructor(){this.audioContext=WP(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0,this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},nL=new WeakMap;var rL=new FP({context:WP()}),oL=class{constructor(e){rb(this,"_volume",0),rb(this,"_log"),rb(this,"_scriptProcessorNode",null),rb(this,"_audioWorkletNode",null),rb(this,"_interval",200),rb(this,"ready",this.preload());let{log:t}=e;this._log=t,QO.on($O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return rL.ready.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(rL.context,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(GP){uP.logFailedEvent({userId:this._log.userId,eventType:uD.LOAD_WORKLET,error:GP}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=WP().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let n=0;n<t.length;++n)i+=t[n]*t[n];this._volume=Math.sqrt(i/t.length)||0}}catch(GP){this._log.error("volumeMeter init script processor error: ".concat(GP))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,QO.off($O.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},sL=class extends $P{constructor(e){super(),rb(this,"_volumeMeter"),this._volumeMeter=new oL(e)}deleteNode(){this._volumeMeter.destroy(),super.deleteNode()}init(){return sb(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}},aL=class extends eL{constructor(e){super(),this.log=e,rb(this,"volumeMeter"),rb(this,"analyser",new ZP),this.volumeMeter=new sL({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},cL=class extends VP{constructor(e){super(e,VN.AUDIO),rb(this,"_outputDeviceId"),rb(this,"_volume",1),rb(this,"_destination",WP().createMediaStreamDestination()),rb(this,"pipeline"),rb(this,"volumeMeterMode","worklet"),this.pipeline=new aL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===Jk||"15.3"===Jk||"15.4"===Jk)&&this.muted)return void this._log.info("audioElement is muted.");let e=new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,this.bindElementEvents()}play(){return sb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(WP().createAnalyser()),this.setVolume(this._volume),ob(cL.prototype,this,"play").call(this)}))}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return sb(this,null,(function*(){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(i=(t=this.element).setSinkId)?void 0:i.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},lL=class extends cL{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(dP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},dL=class extends cL{constructor(e){super(e),rb(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(dP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),xP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}},uL=class extends rP{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,PlayerClass:o=(1===n?dL:UP)}=e;var s;super(),rb(this,"id",tw()),rb(this,"userId",""),rb(this,"isRemote"),rb(this,"mediaType"),rb(this,"room"),rb(this,"user"),rb(this,"_log"),rb(this,"_inputTrack"),rb(this,"_outputTrack"),rb(this,"isPlayCalled"),rb(this,"container",null),rb(this,"player"),rb(this,"subVideoPlayerMap"),rb(this,"muted",!1),rb(this,"abortCtrl"),rb(this,"objectFit","cover"),rb(this,"mirror"),rb(this,"isScreen",!1),rb(this,"manager"),rb(this,"trackSettings"),this.userId=t||"",this.mediaType=n,this._log=ew.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=r||this.room)?void 0:s.userId,remoteUserId:this instanceof FL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof FL}),this.player=new o({track:null,muted:!1,container:null,id:this.userId||this.id,log:this.log}),this.player.on(dP.PLAYER_STATE_CHANGED,(e=>{QO.emit($O.PLAYER_STATE_CHANGED,$C({track:this},e)),this.emit("player-state-changed",e)})),this.kind===VN.VIDEO&&(this.player.on(dP.LOADED_DATA,(()=>{QO.emit($O.VIDEO_LOADED_DATA,{track:this})})),this.player.on(dP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})))}get log(){return this._log||ew}get kind(){return 1===this.mediaType?VN.AUDIO:VN.VIDEO}get strMediaType(){return 4===this.mediaType?VN.VIDEO:2===this.mediaType?VN.SCREEN:VN.AUDIO}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}play(e,t){return sb(this,null,(function*(){let i=_O(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!dO(t.muted)&&this.setPlayerMute(t.muted),t&&!dO(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof UP&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),_O(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!dO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===VN.VIDEO)&&this.setPlayerMute(!0),t&&!dO(t.objectFit)&&(this.objectFit=t.objectFit),this.kind===VN.VIDEO&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof UP&&this.player.setContainer(i)),QO.emit($O.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),_O(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==VN.VIDEO||dO(e)||e===this.mirror)return;this.mirror=e;let i=this.player;if(t&&(i=t),pO(this.mirror))return i.setViewMirror(this.mirror),void(this.room&&(this.room.videoManager.mirror=!1));switch(this.mirror){case"view":this.room&&(this.room.videoManager.mirror=!1),i.setViewMirror(!0);break;case"publish":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!0);break;case"both":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return sb(this,null,(function*(){if(!this._outputTrack||this.kind===VN.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var n;e.find((e=>i===e))||(t.stop(),null==(n=this.subVideoPlayerMap)||n.delete(i))}));for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(dO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new UP({id:this.userId||this.id,track:this.playerMediaTrack,container:r,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return sb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),QO.emit(e?$O.TRACK_MUTED:$O.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new wP;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}getVideoFrame(){return this.kind===VN.VIDEO?this.player.getVideoFrame():""}};nb([tP([],rP.INIT,{sync:!0})],uL.prototype,"close",1);var hL=Object.prototype.hasOwnProperty;var pL=function(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(oO(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(let t in e)if(hL.call(e,t))return!1;return!0}return!1},mL=ib(ab(),1),_L=e=>t=>t.deviceId===e,fL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";rb(this,"kind"),rb(this,"type"),rb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&EL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(_L(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");ew.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(_L(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");ew.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},gL=class extends mL.EventEmitter{constructor(){super(),rb(this,"audioInputs",new fL(VN.AUDIO)),rb(this,"videoInputs",new fL(VN.VIDEO)),rb(this,"audioOutputs",new fL(VN.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||lP.run(VD,(()=>{this.update()}),{delay:1e4}))}init(){SL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield SL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},TL=pN||hN?null:new gL;function EL(e){return e.deviceId===e.groupId&&""===e.groupId}function SL(){return sb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(gw()||!_w())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{EL(e)&&(e.kind===VN.AUDIO_INPUT?i.audio=!0:e.kind===VN.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i)}catch(dN){ew.debug("capture before getDevices failed: ",dN)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let i={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&AL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function IL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return TL.update(e?1:0).then((e=>e.audioInputs.devices))}function vL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return TL.update(e?2:0).then((e=>e.videoInputs.devices))}function yL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return sb(this,null,(function*(){return TL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var AL=new Set;function RL(e,t){return sb(this,null,(function*(){let i=(yield IL()).find((e=>e.deviceId===kD));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var CL=YO({retryFunction:function(e){return sb(this,null,(function*(){let t=function(e){return{audio:kL(e),video:NL(e)}}(e);ew.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],n=[],r=["label","deviceId"];t.audio&&(i=yield IL(),ew.info("microphones: ".concat(UO(i,{keysToInclude:r})))),t.video&&(n=yield vL(),ew.info("cameras: ".concat(UO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return Hw&&e.getTracks().forEach((e=>{ew.info("".concat(e.kind," capabilities: ").concat(UO(e.getCapabilities(),{keysToInclude:FD})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&n&&0===n.length&&(t=cw({key:rw.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(t=cw({key:rw.MICROPHONE_NOT_FOUND}))),new Sb({code:Tb.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)):2===s?r[0].useDeviceIdOnly=!0:3===s&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&bL(r[0].microphoneId,!1),r[0].cameraId&&bL(r[0].cameraId,!0)},onRetrying:e=>{ew.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{uP.logFailedEvent({eventType:uD.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{uP.logSuccessEvent({eventType:uD.GET_USER_MEDIA_RETRY}),uP.uploadEvent({log:"stat-".concat(uD.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function bL(e,t){return sb(this,null,(function*(){let i=(t?yield vL():yield IL()).find((t=>t.deviceId===e));i&&lO(i.getCapabilities)&&ew.warn(UO(i.getCapabilities(),{keysToInclude:FD}))}))}function kL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!pL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(hO(e.channelCount)&&(t.channelCount=e.channelCount),pO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),pO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),pO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!pL(t)||t)}function NL(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.useDeviceIdOnly&&!pL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Hb&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Hb&&(i.height.max=e.height)),Hb&&Tk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!pL(i)||i)}var DL=CL;function OL(e){return PL(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return yield e.apply(this,n),t.apply(this,n)}))}))}function wL(e){return PL(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return e.call(this,t.apply(this,n))}))}))}function PL(e){return function(t,i,n){return n.value=e(n.value,i),n}}var LL=new WeakMap,ML=new WeakMap;function xL(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(LL.has(this)){let o=LL.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i})}else LL.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=LL.get(this);e&&(e.shift(),e[0]&&r($C({},e[0])))}))},i}}function VL(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return null==(t=LL.get(this))||t.forEach((e=>n.push(e))),null==(i=ML.get(this))||i.forEach((e=>e.forEach((e=>n.push(e))))),n.forEach((t=>{t.reject(new Sb({code:Tb.API_CALL_ABORTED,message:e}))})),LL.delete(this),ML.delete(this),r.apply(this,s)},n}}function UL(e){return function(t,i,n){let r=n.value,o=t=>hO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally((()=>{if(ML.has(n)&&ML.get(n).has(o(i))){let e=ML.get(n).get(o(i));e&&(e.shift(),e[0]&&s($C({},e[0])))}}))};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(ML.has(this))if(ML.get(this).has(o(t))){let n=ML.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i})}}else ML.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});else{let n=new Map;n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),ML.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i})}}))},n}}var FL=class extends uL{constructor(e,t){super({mediaType:e,PlayerClass:t}),rb(this,"isRemote",!1),rb(this,"deviceId"),rb(this,"groupId",""),rb(this,"label",""),rb(this,"_isRecapturing",!1),rb(this,"_lastRecaptureTime",0),rb(this,"_onMuteTimeoutId",-1),rb(this,"profile"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return"publish"===this.state}installTrackEvent(e){MP(e,e).add(VN.MUTE,this.onTrackMuted).add(VN.UNMUTE,this.onTrackUnmuted).add(VN.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===VN.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){xP(e)}setStateToCapture(){}capture(e){return sb(this,null,(function*(){var t;try{let i,n=yO();QO.emit($O.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield DL(e));let r=i.getTracks()[0];return yield this.setInputMediaStreamTrack(r),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),QO.emit($O.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:yO()-n}),i}catch(dN){throw QO.emit($O.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:dN}),this.log.error("getUserMedia error observed ".concat(dN)),dN}}))}setInputMediaStreamTrack(e){this.state===rP.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),QO.emit($O.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return sb(this,null,(function*(){if(this.mediaTrack&&Bw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return sb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==VN.AUDIO||t!==kD||(yield RL(n,r)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),SL().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===VN.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(VN.AUDIO_INPUT);return!!AL.has(i)}(this.mediaTrack)||this.kind===VN.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(VN.VIDEO_INPUT);return!!AL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&Tk&&Hk)}onTrackMuted(){if(HO(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<LD)return void setTimeout((()=>this.onTrackMuted()),LD);this._onMuteTimeoutId=setTimeout((()=>sb(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return sb(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<LD)return void setTimeout((()=>this.onTrackEnded()),LD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return sb(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield IL():yield vL()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return sb(this,null,(function*(){let e=this instanceof jL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(BL.get(t)||0)+1;if(BL.set(t,i),i>=3){let n=e?(yield vL()).find((e=>!BL.has(e.deviceId))):(yield IL()).find((e=>!BL.has(e.deviceId)));n&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(n.deviceId)),t=n.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};nb([tP(rP.INIT,"capture",{ignoreError:!0,sync:!0})],FL.prototype,"setStateToCapture",1),nb([xL()],FL.prototype,"capture",1),nb([tP("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),QO.emit($O.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===Tb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],FL.prototype,"publish",1),nb([PL((e=>function(){return sb(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),2===this.mediaType&&(this.mediaType=4)}))})),tP([],"capture",{sync:!0})],FL.prototype,"unpublish",1);var BL=new Map;QO.on($O.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&BL.delete(e.track.deviceId)}));var HL=class extends FL{constructor(e){super(1,lL),rb(this,"mediaType",1),rb(this,"volume",0),rb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),rb(this,"playerMuted",!0),rb(this,"pipeline"),this.manager=e,this.pipeline=new tL(e)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return sb(this,null,(function*(){yield ob(HL.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};XP.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),XP.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),XP.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:n}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:n}))),this.pipeline.replaceSource(e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:n=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:n,customSource:i})}switchDevice(e){return sb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==kD)return;if(yield RL(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),QO.emit($O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(lD){throw this.log.error("switch microphone failed ".concat(lD)),this.deviceId&&this.recapture(this.deviceId),lD}}}))}listenDeviceChange(){TL&&!TL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&TL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield IL();t[0]?this.recapture(t[0].deviceId):TL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return sb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!dO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!dO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!dO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&XP.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){XP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),TL.off("audioInputAdded",this.handleMicrophoneAdded,this),TL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}},jL=class extends FL{constructor(e){super(4,UP),rb(this,"mediaType",4),rb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),rb(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),rb(this,"small"),rb(this,"isNeedToSetBandwidth"),rb(this,"muteImage"),rb(this,"manager"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(ZC($C({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t)}get facingMode(){if(Bw&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}setMute(e){return sb(this,null,(function*(){var t,i,n;if(uO(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.deleteWatermark("mute"),yield null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,ob(jL.prototype,this,"setMute").call(this,!1)}else yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,ob(jL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:n=!1,customSource:r}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,customSource:r})}setProfile(e){let t=$C({},e),i=t.width>t.height;t.width*t.height<=19200&&Vb&&xk&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&qk&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(ZC($C({},this.profile),{width:1920,height:1080})))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:VN.VIDEO,videoType:VN.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Bw&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:jO()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return sb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),QO.emit($O.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(lD){throw this.log.error("switch camera failed ".concat(lD)),this.deviceId&&this.recapture(this.deviceId),lD}}))}listenDeviceChange(){TL&&!TL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&TL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield vL();t[0]?this.recapture(t[0].deviceId):TL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return sb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}play(e,t){return sb(this,null,(function*(){return dO(this.mirror)&&!this.isScreen&&this.setMirror("view"),ob(jL.prototype,this,"play").call(this,e,t)}))}close(){TL.off("videoInputAdded",this.handleCameraAdded,this),TL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}},GL=tw();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:GL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(qU){}var WL,JL=function(e){return sb(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Hk?{max:e.width}:{ideal:e.width,max:e.width},height:Hk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3}}return t}(e);ew.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===n.getAudioTracks().length&&(Vk&&Fk<74||Hk||Hb)&&ew.warn("Your browser not support capture system audio");let r=n.getVideoTracks()[0];if(r){if(e.frameRate)try{yield r.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){ew.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return sb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&lO(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==GL)return;let n=yield CropTarget.fromElement(t);yield e.cropTo(n)}catch(n){ew.warn("cropTo target failed ".concat(n))}}))}(r,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return dO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);ew.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0])}return n}))},zL=class extends jL{constructor(e){super(e),rb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),rb(this,"objectFit","contain"),rb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return sb(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:n,echoCancellation:r,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield JL({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:n,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof Sb?e:new Sb({code:Tb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return sb(this,null,(function*(){throw new Error("Method not implemented.")}))}},KL=class extends HL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var YL=class extends iL{constructor(e){super(),this.room=e,rb(this,"_localAudioTrack"),rb(this,"_localScreenAudioTrack"),rb(this,"log",ew.createLogger({id:"am"})),rb(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let n=[],r=[];null!=(t=this._localAudioPipline)&&t.source.node&&(n.push(this._localAudioPipline.source.node),r.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(n.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(n.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info("dump audio track ".concat(r,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<r.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(r[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=function(e){return sb(this,null,(function*(){let t=WP();WL||(WL=t.audioWorklet.addModule(URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield WL;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}(n).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){var t;if(e instanceof KL)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof HL)this._localAudioTrack=e,this.destination.channelCount=(null==(t=e.trackSettings)?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof XL)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof KL?delete this._localScreenAudioTrack:e instanceof HL&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}},qL=class extends uL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,rb(this,"tinyId"),rb(this,"isRemote",!0),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===qL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed:".concat(this.isSubscribed," hasFlag:").concat(this.hasFlag," hasTrack:").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},QL=qL;rb(QL,"STATE_SUBSCRIBE","subscribe"),nb([tP(rP.INIT,QL.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),QO.emit($O.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],QL.prototype,"subscribe",1),nb([tP(QL.STATE_SUBSCRIBE,rP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),QO.emit($O.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],QL.prototype,"unsubscribe",1);var XL=class extends QL{constructor(e,t){super(e,t,1),rb(this,"volume",0),rb(this,"mediaType",1),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},$L=class extends QL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),rb(this,"mediaType",4),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},ZL=class extends $L{constructor(e,t){super(e,t,2),rb(this,"mediaType",2),rb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function eM(){}var tM=e=>e(),iM=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,nM=1,rM=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new lM(e,this,this.streamId++);return dM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},oM=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=eM,this.error=eM,this.next=eM,this.dispose=eM,this.subscribe=eM,this.doDefer()}subscribe(e){return e instanceof rM?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(tM),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},sM=class extends oM{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}};function aM(e,t,i){if(iM()){let n=Object.defineProperties(Object.setPrototypeOf(e,rM.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:i,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});dM.create(n);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof rM&&dM.addSource(n,t)}return n}return e}function cM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var lM=class extends sM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{dM.defer(this.source,this.id)}))}next(e){dM.next(this.source,this.id,e),this.sink.next(e)}complete(){dM.complete(this.source,this.id),this.sink.complete()}error(e){dM.complete(this.source,this.id,e),this.sink.error(e)}},dM={addSource(e,t){cM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){cM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:n}=e;cM("subscribe",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){cM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){cM("defer",{id:e.id,streamId:t})},pipe(e){cM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){cM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=nM++),cM("create",{name:e.toString(),id:e.id})}},uM=class extends oM{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};var hM=function(e,t){return function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return i=>{if(i instanceof rM){let r=aM((t=>{let o=new e(t,...n);o.sourceId=r.id,o.subscribe(i)}),t,arguments);return r.source=i,dM.pipe(r),r}return t=>i(new e(t,...n))}}}(class extends sM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];i.reduce(((e,t)=>t(e)),e)}(function(e){return aM((t=>{let i=0,n=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(n)})),"interval"}),"interval",arguments)}(250),hM((()=>performance.now())),function(){return e=>{let t=new uM(e);if(e instanceof rM){let i=aM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,dM.pipe(i),i}return aM(t.add.bind(t),"share",arguments)}}());var pM=new Map;function mM(e,t){let i=ZC($C({},t),{timestamp:vb()});pM.has(e)?pM.get(e).push(i):pM.set(e,[i])}QO.on($O.JOIN_SUCCESS,(e=>{let{room:t}=e;mM(t.userId,{eventId:32788,eventDesc:"join room"})})),QO.on($O.LEAVE_START,(e=>{let{room:t}=e;mM(t.userId,{eventId:32789,eventDesc:"leave room"})})),QO.on($O.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),mM(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),QO.on($O.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),mM(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),QO.on($O.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===VN.AUDIO?mM(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):mM(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),QO.on($O.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===VN.AUDIO?mM(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):mM(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),QO.on($O.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&mM(t.room.userId,{eventId:32777,eventDesc:"".concat(VN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&mM(t.room.userId,{eventId:32776,eventDesc:"".concat(VN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&mM(t.room.userId,{eventId:32803,eventDesc:"".concat(VN.SUBSCRIBE," ").concat(VN.SMALL_VIDEO),remoteUserId:t.userId}))})),QO.on($O.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&mM(t.room.userId,{eventId:32779,eventDesc:"".concat(VN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&mM(t.room.userId,{eventId:32778,eventDesc:"".concat(VN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&mM(t.room.userId,{eventId:32804,eventDesc:"".concat(VN.UNSUBSCRIBE," ").concat(VN.SMALL_VIDEO),remoteUserId:t.userId}))})),QO.on($O.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&mM(t.room.userId,{eventId:t.kind===VN.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===VN.VIDEO?"camera":"microphone")})})),QO.on($O.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&mM(t.room.userId,{eventId:t.kind===VN.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),QO.on($O.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===r?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===r?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&mM(n.userId,{eventId:t,eventDesc:i})})),QO.on($O.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===r?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&mM(n.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var _M=ib(ab(),1),fM=class extends _M.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,rb(this,"userMap",new Map),rb(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n="peer leave [".concat(e,"]");dO(t)||(n+=":".concat(wD[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:r.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:n,userId:r,tinyId:o}=e,s=kO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:kO(0,r),muteState:s,flag:n})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var gM,TM=!0,EM={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"},SM={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},IM=((gM=IM||{})[gM.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",gM[gM.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",gM[gM.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",gM[gM.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",gM[gM.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",gM[gM.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",gM[gM.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",gM[gM.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",gM[gM.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",gM[gM.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",gM[gM.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",gM[gM.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",gM[gM.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",gM[gM.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",gM[gM.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",gM[gM.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",gM[gM.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",gM[gM.INVALID_OPERATION=5100]="INVALID_OPERATION",gM[gM.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",gM[gM.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",gM[gM.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",gM[gM.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",gM[gM.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",gM[gM.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",gM[gM.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",gM[gM.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",gM[gM.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",gM[gM.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",gM[gM.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",gM[gM.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",gM[gM.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",gM[gM.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",gM[gM.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",gM[gM.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",gM[gM.DEVICE_ERROR=5300]="DEVICE_ERROR",gM[gM.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",gM[gM.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",gM[gM.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",gM[gM.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",gM[gM.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",gM[gM.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",gM[gM.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",gM[gM.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",gM[gM.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",gM[gM.SERVER_ERROR=5400]="SERVER_ERROR",gM[gM.NEED_TO_BUY=5401]="NEED_TO_BUY",gM[gM.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",gM[gM.OPERATION_FAILED=5500]="OPERATION_FAILED",gM[gM.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",gM[gM.REJOIN_FAILED=5502]="REJOIN_FAILED",gM[gM.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",gM[gM.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",gM[gM.OPERATION_ABORT=5998]="OPERATION_ABORT",gM[gM.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",gM);var vM=ZC($C({},ow),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(cO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(cO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=yM(t),error:n}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function yM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var AM=class extends Error{constructor(e){let{code:t,extraCode:i,message:n="",messageParams:r,fnName:o="",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s="",a=IM[i];try{t=vM[a]}catch(o){t=vM.UNKNOWN_ERROR}return lO(t)?s=t(n):uO(t)&&(s=t),r&&(s+=" doc:"),s}({code:i||t,params:$C({fnName:o,error:s},r)}),super(c),rb(this,"name","RtcError"),rb(this,"code"),rb(this,"extraCode"),rb(this,"functionName"),rb(this,"message"),rb(this,"handler"),rb(this,"originError"),this.name=IM[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes("system"))&&(this.handler=()=>{let e=document.createElement("a");gk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):Tk&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let n=e;if(e instanceof Sb){let{stack:r}=e,o={code:SM.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case Tb.INVALID_PARAMETER:o.code=SM.INVALID_PARAMETER,o.message=e.message;break;case Tb.INVALID_OPERATION:o.code=SM.INVALID_OPERATION;break;case Tb.NOT_SUPPORTED:case Tb.NOT_SUPPORTED_H264:o.code=SM.ENV_NOT_SUPPORTED,e.getCode()===Tb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(ow.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Tb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case Tb.SERVER_TIMEOUT:case Tb.SWITCH_ROLE_FAILED:o.code=SM.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case Tb.API_CALL_ABORTED:o.code=SM.OPERATION_ABORT;break;case Tb.DEVICE_NOT_FOUND:case Tb.DEVICE_AUTO_RECOVER_FAILED:case Tb.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case Tb.UNKNOWN:break;default:o.code=SM.OPERATION_FAILED}n=new AM(o),r&&(n.stack+=r.substr(r.indexOf("\n")))}else{if(e instanceof AM)return e;n=new AM({code:SM.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};var RM=AM,CM={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},bM={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},kM={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(uO(e)&&!document.getElementById(e))throw new RM({code:SM.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},NM={name:"userId",required:!0,type:"string"},DM={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[EM.AUDIO_PROFILE_STANDARD,EM.AUDIO_PROFILE_STANDARD_STEREO,EM.AUDIO_PROFILE_HIGH,EM.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function OM(e,t){if(!e)throw new RM({code:SM.INVALID_OPERATION,extraCode:5101,fnName:t})}function wM(e,t,i){if(!e)throw new RM({code:SM.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var PM={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(e,t,i){if(this._room.isJoined)throw new RM({code:SM.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(uO(e.roomId))throw new RM({code:SM.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new RM({code:SM.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new RM({code:SM.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new RM({code:SM.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:kM,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:CM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&gw())throw new RM({code:SM.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},kM),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:CM}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:DM},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&gw())throw new RM({code:SM.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:DM}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:kM,publish:{type:"boolean"},option:bM},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&gw())throw new RM({code:SM.ENV_NOT_SUPPORTED,extraCode:5201});if(!yw())throw new RM({code:SM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:kM,publish:{type:"boolean"},option:bM}},muteRemoteAudio:[NM,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[NM,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:kM,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){OM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(wM(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new RM({code:SM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},kM),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,i){OM(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(wM(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new RM({code:SM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if("*"!==e.userId&&dO(e.streamType))throw new RM({code:SM.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){OM(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!jw)throw new RM({code:SM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new RM({code:SM.INVALID_OPERATION,messageParams:{key:rw.SEI_DISABLED}});if(e.byteLength>1e3)throw new RM({code:SM.INVALID_PARAMETER,messageParams:{key:rw.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new RM({code:SM.INVALID_PARAMETER,messageParams:{key:rw.SEI_EMPTY}});if(OM(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new RM({code:SM.INVALID_PARAMETER,messageParams:{key:rw.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},LM={TRTC:PM},MM=class extends Error{};function xM(e,t){let i=PO(e);for(let n=0;n<t.length;n++)wO(i[n],t[n]);return i}function VM(e){this._resolve=Promise.resolve(e)}function UM(e){this._reject=Promise.reject(e)}var FM=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=xM;let i=FM.instances.get(e);i?i.set(t,this):FM.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=FM.instances.get(e);return i&&i.get(t)||new FM(e,t)}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new MM("start failed")),null==(n=this.currentOp)||n.action(),t},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:VM,reject:UM};try{switch(this.state){case 1:if(0===e)throw new MM("already started");break;case 4:if(2===e)throw new MM("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(n,r)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new MM("already start");break;case 3:switch(e.type){case 2:throw new MM("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new MM("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new MM("keep stop");if(this.ops.slice(1).forEach((t=>t.reject(e))),this.ops=this.ops.slice(0,1),3===this.state)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new MM("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new MM("start not allowed after update");case 0:throw new MM("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new MM("keep start")),new MM("already start")}}e.promise=new Promise(((t,i)=>{e._resolve?e._resolve.then(t):e.resolve=t,e._reject?e._reject.catch(i):e.reject=i}));let{action:t}=e;return e.action=()=>t().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},BM=FM;BM.instances=new WeakMap;var HM=new WeakMap,jM=(e,t)=>{if(t instanceof MM){let{stack:i}=t;t=new RM({code:SM.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function GM(e,t){return PL(((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];let a=BM.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(jM.bind(null,n))}))}function WM(e,t){let{merge:i,debounce:n}=t||{};return PL(((t,r)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=BM.get(this,"string"==typeof e?e:e.call(this,...s));if(i&&(c.mergeUpdate=i.bind(this)),n&&n.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=n;return new Promise(((n,o)=>{var a,l;let d=null==(a=HM.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(jM.bind(null,r)).then(n,o)}),e);HM.has(this)?null==(l=HM.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):HM.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]))}))}return c.action(2,t.bind(this),s).catch(jM.bind(null,r))}))}function JM(e){return PL(((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return BM.get(this,"string"==typeof e?e:e.call(this,...r)).action(3,t.bind(this),r).catch(jM.bind(null,i))}))}var zM={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function KM(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function YM(e){return e===EM.QOS_PREFERENCE_CLEAR?"detail":e===EM.QOS_PREFERENCE_SMOOTH?"motion":""}function qM(e,t,i){return{room:e,assetsPath:i,innerEmitter:QO,constants:oN,environment:Rb,utils:Ab,eventLogger:uP,log:e.getLogger(),errorModule:t,kvStatManager:XP,clearStarted(t,i){let n=t.getAlias(),r=BM.instances.get(e);if(r)if(i){let e=r.get(n+i);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(n)&&(e.started=!1)}))}}}var QM=new WeakMap;function XM(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return PL(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{ZM.call(this,t,r,i,this._name)}catch(dN){return Promise.reject(dN)}return e.apply(this,r)}))}function $M(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return PL(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{ZM.call(this,t,r,i,this._name)}catch(dN){throw dN}return e.apply(this,r)}))}function ZM(e,t,i,n){if(_O(e))for(let r=0;r<e.length;r++)ex.call(this,{rule:e[r],value:t[r],key:e[r].name,fnName:i,className:n});else ex.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:n})}function ex(e){let{rule:t,value:i,key:n,fnName:r,className:o}=e;function s(e){return{code:SM.INVALID_PARAMETER,extraCode:e,fnName:r,messageParams:{key:n,rule:t,value:i}}}if(dO(i)){if(t.required)throw new RM(s(5001));if(dO(t.defaultValue))return void(lO(t.validate)&&t.validate.call(this,i,n,r,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let n=0;n<t.type.length;n++)null===t.type[n]&&null===i&&(e=!0),lO(t.type[n])&&i instanceof t.type[n]&&(e=!0),uO(t.type[n])&&cO(i)===t.type[n].toLowerCase()&&(e=!0);if(!e)throw new RM({code:SM.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:n,rule:{type:t.type.map((e=>EO(e)?SO(e):uO(e)?e:cO(e)))},value:i}})}else if(!dO(t.type)&&cO(i)!==t.type)throw new RM(s(5002));if(!1===t.allowEmpty){let e=hO(i)&&(0===i||Number.isNaN(i)),t=uO(i)&&""===i.trim();if(e||t)throw new RM(s(5003))}if(t.notLessThanZero&&hO(i)&&i<0)throw new RM(s(5006));if(!dO(t.min)&&hO(i)&&i<t.min)throw new RM(s(5007));if(!dO(t.max)&&hO(i)&&i>t.max)throw new RM(s(5008));if(uO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new RM(s(5004))}else if(lO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new RM(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new RM(s(5005));let{properties:a}=t;oO(a)&&mO(i)&&Object.keys(a).forEach((e=>{ex.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:r,className:o})}));let{arrayItem:c}=t;oO(c)&&_O(i)&&i.forEach(((e,t)=>{ex.call(this,{rule:c,value:e,key:"".concat(n,"[").concat(t,"]"),fnName:r,className:o})})),lO(t.validate)&&t.validate.call(this,i,n,r,o,this)}function tx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=(()=>""),getRemoteId:i=(()=>"")}=e;return PL(((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];function a(e,t,i){if(i&&i.includes(e))return"hided";if(t===o||e in o)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(cO(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(cO(t))}}let c=this._log||ew,l=t.call(this,...o),d=""!==l?"".concat(l,".").concat(n):n;o.length>0?c.info("".concat(d,"() ").concat(JSON.stringify(o,((e,t)=>a(e,t,["userSig","privateMapKey"]))))):c.info("".concat(d,"()"));try{let t=e.apply(this,o),n=yO();return TO(t)?t.then((e=>(c.info("".concat(d,"() success ").concat(i.call(this,...o))),XP.addSuccessEvent({key:zP[d],cost:yO()-n}),e))).catch((e=>{throw e=RM.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error("".concat(d,"() failed ").concat(i.call(this,...o)," ").concat(e," params: ").concat(JSON.stringify(o,a))),XP.addFailedEvent({key:zP[d],error:e}),e})):(XP.addSuccessEvent({key:zP[d]}),t)}catch(u){throw u=RM.convertFrom.call(this,u,d),c.error("".concat(d,"() failed ").concat(u," params: ").concat(JSON.stringify(o,a))),XP.addFailedEvent({key:zP[d],error:u}),u}}))}var ix=e=>PL(((t,i)=>function(n,r){return sb(this,null,(function*(){let o=this._plugins.get(n);if(o)return ZM.call(this,o.getValidateRule(e),[r],i,"TRTC"),t.call(this,o,r);this._log.warn("plugin ".concat(n," is not found"))}))})),nx=0,rx=class{constructor(e,t){rb(this,"player"),rb(this,"publisher"),rb(this,"mixInput"),this.mixInput=new tL(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}},ox=class{constructor(e){this.core=e,rb(this,"log"),rb(this,"mixedMusicMap",new Map),rb(this,"cacheMusicMap",new Map),nx+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(nx)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(nx)),this.core=e}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return ox.startValidateRule;case"update":return ox.updateValidateRule;case"stop":return ox.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:n}=e;if(this.mixedMusicMap.has(i))return;let r=this.cacheMusicMap.get(i);r?e.url?r.reset():(r.mixInput.replaceSource(e.track),r.mixInput.connect()):(r=new rx(e,t.audioManager),this.cacheMusicMap.set(i,r)),yield r.play(),this.mixedMusicMap.set(i,r),this.log.info("start mix audio track ".concat(i," success.")),XP.addEnum({key:502700,value:3})}))}update(e){return sb(this,null,(function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(dO(i)||(s.volume=i),dO(n)||(s.loop=n),dO(r)||s.setOperation(r),dO(o)||s.seek(o)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return sb(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},sx=ox;rb(sx,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],r=t.split(".").pop(),o=n.indexOf(r)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new RM({code:SM.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new RM({code:SM.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i})}}),rb(sx,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}}}),rb(sx,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var ax=e=>(e=Number(e))>0&&e<14e8,cx=0,lx=class{constructor(e){this.core=e,rb(this,"log"),rb(this,"ready"),rb(this,"audioContext",WP()),rb(this,"workletNode"),cx+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(cx)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(cx)),e.assetsPath&&(this.ready=this.audioContext.audioWorklet.addModule("".concat(e.assetsPath,"/denoiser-wasm.js")),this.ready.catch((t=>{this.log.error("Init assets from ".concat(e.assetsPath," failed! Reason: ").concat(t))})))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,n,r){if(!e.room.audioManager.hasAudioTrack)throw new RM({code:SM.INVALID_OPERATION,extraCode:5106,fnName:n})}}}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return lx.startValidateRule(this.core);case"update":return lx.updateValidateRule;case"stop":return lx.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core;if(this.ready||(this.ready=this.audioContext.audioWorklet.addModule("".concat(e.assetsPath,"/denoiser-wasm.js")),this.ready.catch((t=>{this.log.error("Init assets from ".concat(e.assetsPath," failed! Reason: ").concat(t))}))),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield function(e){return sb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e="https://".concat(function(e){let t;return t=ax(e)?ux.MAIN_OVERSEA:ux.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(n,"&timestamp=").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(ZC($C({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new RM({code:SM.INVALID_PARAMETER,message:o});yield this.ready,this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:t,sign:n,status:r}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return sb(this,null,(function*(){}))}stop(){return sb(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){}},dx=lx;rb(dx,"updateValidateRule",{type:"object"}),rb(dx,"stopValidateRule",{type:"object"});var ux={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var hx=0,px=new Set,mx=null;cN("5.5.0-beta.9");var _x=class extends fb.EventEmitter{constructor(e,t){super(),rb(this,"_room"),rb(this,"_eventListened",new Set),rb(this,"_localVideoTrack",null),rb(this,"_localAudioTrack",null),rb(this,"_localScreenTrack",null),rb(this,"_localScreenAudioTrack",null),rb(this,"_localVideoConfig",null),rb(this,"_localScreenConfig",null),rb(this,"_localAudioConfig",null),rb(this,"_remoteVideoConfigMap",new Map),rb(this,"_remoteAudioConfigMap",new Map),rb(this,"_remoteAudioMuteMap",new Map),rb(this,"_mediaTrackMap",new WeakMap),rb(this,"_log",ew.createLogger({id:"t".concat(++hx)})),rb(this,"_plugins",new Map),rb(this,"_networkQuality",null),rb(this,"_speakerId"),this._room=new e($C({logger:this._log,frameWorkType:_x.frameWorkType},t)),this._log.debug(JSON.stringify(t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}});let i={RtcError:RM,ErrorCode:SM,ErrorCodeDictionary:IM};t.plugins&&t.plugins.forEach((e=>{let n=new e(qM(this._room,i,t.assetsPath));this._plugins.set(n.getName(),n)}));let n=new sx(qM(this._room,i,t.assetsPath));this._plugins.set(n.getName(),n);let r=new dx(qM(this._room,i,t.assetsPath));this._plugins.set(r.getName(),r),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(zM.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{let{reason:t,error:i}=e;this._log.error(new RM({code:SM.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];try{return n.apply(e,o)}catch(i){let n=cw({key:rw.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return ew.warn("".concat(n,"\n\n").concat(i.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;TM&&(TM=!1,5!==ew.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(IN,"/en/index.html")),console.info("* Changelog: ".concat(IN,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),ew.info("TRTC Web SDK Version:",aN),ew.info("UA:",navigator.userAgent),ew.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),tN().then((e=>{if(e){let t="UAData: ".concat(e.platform,"/").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=" ".concat(e.architecture,"/").concat(e.bitness)),e.mobile&&(t+=" mobile"),e.model&&(t+=" model: ".concat(e.model)),e.fullVersionList&&(t+=" ".concat(e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(","))),ew.info(t)}})));let n=new _x(e,t||{});return px.add(n),n}_listenEvents(){MP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(zM.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(zM.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(zM.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(zM.ERROR,RM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(zM.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(zM.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{MP(t,t).add("player-state-changed",(i=>{let n=ZC($C({},i),{userId:e.userId});t.kind===VN.VIDEO&&(n.streamType=KM(t.streamType)),this.emit(t.kind===VN.AUDIO?zM.AUDIO_PLAY_STATE_CHANGED:zM.VIDEO_PLAY_STATE_CHANGED,n)})).add("error",(e=>{e.getCode()===Tb.PLAY_NOT_ALLOWED&&this.emit(zM.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{xP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i,r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete("".concat(n,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(n,"_","sub")),r!==s&&(this.emit(s?zM.REMOTE_AUDIO_AVAILABLE:zM.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),s?this._onAudioAvailable({userId:n}):this._onAudioUnavailable({userId:n})),o!==a&&(this.emit(a?zM.REMOTE_VIDEO_AVAILABLE:zM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"}),a?this._onVideoAvailable({userId:n,streamType:"main"}):this._onVideoUnavailable({userId:n,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?zM.REMOTE_VIDEO_AVAILABLE:zM.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:n,streamType:"sub"}):this._onVideoUnavailable({userId:n,streamType:"sub"}))})).add("firewall-restriction",(()=>{this.emit(zM.ERROR,new RM({code:SM.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(zM.SEI_MESSAGE,ZC($C({},e),{streamType:KM(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,n,r,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/BD},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/BD},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(zM.STATISTICS,l)})),MP(this,TL).add("audioInputAdded",(e=>{this.emit(zM.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(zM.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(zM.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(zM.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>sb(this,null,(function*(){if(this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),mx&&mx.deviceId===ND){let e=(yield yL()).find((e=>e.deviceId===ND));e&&mx.groupId!==e.groupId&&(mx=e,this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>sb(this,null,(function*(){this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield yL())[0];t&&mx&&(mx.deviceId===e.deviceId||mx.deviceId===ND&&mx.groupId!==t.groupId)&&(mx=t,this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}enterRoom(e){return sb(this,null,(function*(){var t,i;let{scene:n="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!uO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,pO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),yield this._room.join(a,n,_x.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return sb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return sb(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){xP(this),this.removeAllListeners(),this._room.destroy(),px.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>e.destroy()))}startLocalAudio(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:n,option:r}=t,o=new HL(e._room.audioManager),s={},a={muted:!0};r&&(dO(r.microphoneId)?dO(r.audioTrack)||(s.customSource=r.audioTrack):s.deviceId=r.microphoneId,r&&hO(r.captureVolume)&&o.setCaptureVolume(r.captureVolume),dO(r.profile)||(uO(r.profile)?LN[r.profile]&&o.setProfile(LN[r.profile]):o.setProfile(r.profile)),hO(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),dO(r.echoCancellation)||(o.profile.echoCancellation=r.echoCancellation),dO(r.noiseSuppression)||(o.profile.noiseSuppression=r.noiseSuppression),dO(r.autoGainControl)||(o.profile.autoGainControl=r.autoGainControl)),o.on("5",(t=>{e.emit(zM.ERROR,new RM({code:SM.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(zM.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=RM.convertFrom(t.error)),e.emit(zM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),dO(n)||o.setMute(n),MP(o,o).add("player-state-changed",(t=>{e.emit(zM.AUDIO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=ZC($C({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return sb(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):dO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),dO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),dO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!dO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),dO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),wO(this._localAudioConfig,e)}))}stopLocalAudio(){return sb(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),xP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:n=!0,mute:r,option:o}=t,s=new jL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:dO(o.useFrontCamera)?dO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?VN.FACING_MODE_USER:VN.FACING_MODE_ENVIRONMENT,dO(o.profile)||(uO(o.profile)?MN[o.profile]&&s.setProfile(MN[o.profile]):s.setProfile(o.profile)),dO(o.fillMode)||(c.objectFit=o.fillMode),dO(o.mirror)||(c.mirror=o.mirror),dO(o.small)||(Dw()?uO(o.small)?s.small=MN[o.small]:!0===o.small?s.small=MN["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(zM.ERROR,new RM({code:SM.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(zM.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=RM.convertFrom(t.error)),e.emit(zM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),dO(r)||(yield s.setMute(r)),(null==o?void 0:o.qosPreference)&&s.mediaTrack){let e=YM(o.qosPreference);s.mediaTrack.contentHint=e}MP(s,s).add("player-state-changed",(t=>{e.emit(zM.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"main"}))})),n&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=ZC($C({},t),{view:i,publish:n}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return sb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r){if(dO(r.profile)||(uO(r.profile)?MN[r.profile]&&this._localVideoTrack.setProfile(MN[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&dO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):dO(r.useFrontCamera)?dO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?VN.FACING_MODE_USER:VN.FACING_MODE_ENVIRONMENT),dO(r.fillMode)||(o.objectFit=r.fillMode),dO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack){let e=YM(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(r.small){let e=!this._localVideoTrack.small;Dw()?(!0===r.small?this._localVideoTrack.small=MN["120p"]:uO(r.small)?this._localVideoTrack.small=MN[r.small]:this._localVideoTrack.small=r.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===r.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!dO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),dO(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),wO(this._localVideoConfig,e)}))}stopLocalVideo(){return sb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),xP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:n=!0,option:r}=t,o=new zL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=RM.convertFrom(t.error)),e.emit(zM.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null;o.setMediaType(2);let a={},c={};r&&(dO(r.profile)||(uO(r.profile)?xN[r.profile]&&o.setProfile(xN[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),dO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack),r.captureElement&&(a.captureElement=r.captureElement),r.preferDisplaySurface&&(a.preferDisplaySurface=r.preferDisplaySurface));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=YM(r.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(VN.ENDED,(()=>{e._stopScreenShare(),e.emit(zM.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new KL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),MP(o,o).add("player-state-changed",(t=>{e.emit(zM.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=ZC($C({},t),{view:i,publish:n}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return sb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(dO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=YM(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!dO(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),wO(this._localScreenConfig,e)}))}stopScreenShare(){return sb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return sb(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),r&&(dO(r.fillMode)||(a.objectFit=r.fillMode),dO(r.mirror)||(a.mirror=r.mirror),"main"===n&&!dO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),r&&!dO(r.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:r.receiveWhenViewVisible,viewRoot:null==r?void 0:r.viewRoot})}))}updateRemoteVideo(e){return sb(this,null,(function*(){var t,i;let{view:n,userId:r,streamType:o,option:s}=e,a="".concat(r,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};s&&(dO(s.fillMode)||(l.objectFit=s.fillMode),dO(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(r);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!dO(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:n,playOption:l,track:d,prevConfig:h}),wO(h,e);let p=dO(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=dO(n)?h.view:n,_=dO(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return sb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;"main"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let r=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return sb(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return sb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return sb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return sb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let n,r="main";if(uO(e)?n=e:(n=e.userId,e.streamType&&(r=e.streamType)),!n)return"sub"===r?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(n);if(e)return e.remoteAudioTrack.mediaTrack}return null}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return sb(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(dO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o})}catch(OU){throw this._remoteAudioConfigMap.delete(t),OU}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.get(i.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return sb(this,arguments,(function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(n.setMirror(i.mirror),dO(t)&&r&&r.view&&!bO(i)){let e=LO(r.view);e.length>0&&(yield n.play(e,i))}if(!dO(t)){let e=LO(t);e.length>0?yield n.play(e,i):n.stop()}}()}))}_updateAudioPlayOption(e){return sb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(uN){}dO(t.muted)||i.setPlayerMute(t.muted),dO(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e)))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit(zM.TRACK,{userId:t,streamType:KM(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:n=!1,viewRoot:r}=e;if(dO(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(KM(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||_O(i)&&0===i.length||!n)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==r)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:r}));let l=new Set(LO(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return sb(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{xP(e.remoteAudioTrack),xP(e.remoteVideoTrack),xP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return sb(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),xP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return sb(this,null,(function*(){if(mx&&!EL(mx))this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"active",device:mx});else{let e=yield yL();if(e[0]&&!EL(e[0]))mx=e[0],this.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!mx||EL(mx))&&(this._initActiveSpeaker(),QO.off("102",this._initActiveSpeaker))};QO.on("102",e)}}}))}_onAudioAvailable(e){let{userId:t}=e;!this._room.autoReceiveAudio||this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(t)||this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let n=this._room.remotePublishedUserMap.get(t);if(n){let e="main"===i?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}static setLogLevel(e,t){ew.setLogLevel(e),dO(t)||(t?ew.enableUploadLog():ew.disableUploadLog())}static isSupported(){return Iw()}static getCameraList(){return vL(!0)}static getMicrophoneList(){return IL(!0)}static getSpeakerList(){return yL(!0)}static setCurrentSpeaker(e){return sb(this,null,(function*(){(yield yL()).forEach((t=>{t.deviceId===e&&(px.forEach((i=>{i.setCurrentSpeaker(e),i.emit(zM.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),mx=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:n,base:r,useUV:o,version:s}=e;switch(s&&(QP.version=s),t){case"count":QP.addCount({key:i,useUV:o});break;case"enum":QP.addEnum({key:i,value:n,useUV:o});break;case"number":QP.addNumber({key:i,value:n,split:r})}}},fx=_x;rb(fx,"_loggerManager",ew),rb(fx,"EVENT",zM),rb(fx,"ERROR_CODE",SM),rb(fx,"TYPE",EM),rb(fx,"frameWorkType",30),nb([XM(LM.TRTC.enterRoom),GM("room",((e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId})),PL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),tx()],fx.prototype,"enterRoom",1),nb([tx()],fx.prototype,"exitRoom",1),nb([XM(LM.TRTC.switchRole),WM("room",{merge:(e,t)=>t}),tx()],fx.prototype,"switchRole",1),nb([tx()],fx.prototype,"destroy",1),nb([XM(LM.TRTC.startLocalAudio),GM("audio",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId)})),tx()],fx.prototype,"startLocalAudio",1),nb([XM(LM.TRTC.updateLocalAudio),WM("audio",{debounce:{delay:200,getKey:()=>"".concat(hx,"-localAudio"),isNeedToDebounce:e=>{var t;return!dO(null==(t=e.option)?void 0:t.captureVolume)}}}),tx()],fx.prototype,"updateLocalAudio",1),nb([JM("audio"),tx()],fx.prototype,"stopLocalAudio",1),nb([XM(LM.TRTC.startLocalVideo),GM("video",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId)})),tx()],fx.prototype,"startLocalVideo",1),nb([XM(LM.TRTC.updateLocalVideo),WM("video"),tx()],fx.prototype,"updateLocalVideo",1),nb([JM("video"),tx()],fx.prototype,"stopLocalVideo",1),nb([XM(LM.TRTC.startScreenShare),GM("screen",(()=>!0)),tx()],fx.prototype,"startScreenShare",1),nb([XM(LM.TRTC.updateScreenShare),WM("screen"),tx()],fx.prototype,"updateScreenShare",1),nb([tx()],fx.prototype,"stopScreenShare",1),nb([XM(LM.TRTC.startRemoteVideo),GM((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),tx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],fx.prototype,"startRemoteVideo",1),nb([XM(LM.TRTC.updateRemoteVideo),WM((e=>"v".concat(e.userId).concat(e.streamType))),tx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],fx.prototype,"updateRemoteVideo",1),nb([XM(LM.TRTC.stopRemoteVideo),PL((e=>function(t){return sb(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_","main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_","sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),tx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],fx.prototype,"stopRemoteVideo",1),nb([JM((e=>"v".concat(e.userId).concat(e.streamType)))],fx.prototype,"_stopRemoteVideo",1),nb([XM(...LM.TRTC.muteRemoteAudio),tx({getRemoteId:e=>e})],fx.prototype,"muteRemoteAudio",1),nb([$M(...LM.TRTC.setRemoteAudioVolume),function(e,t){return PL(((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];var s,a;let c=null==(s=QM.get(this))?void 0:s.get(t(...r));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,r)}),e);QM.has(this)?null==(a=QM.get(this))||a.set(t(...r),l):QM.set(this,new Map([[t(...r),l]]))}))}(200,(e=>e)),tx({getRemoteId:e=>e})],fx.prototype,"setRemoteAudioVolume",1),nb([ix("start"),GM(((e,t)=>e.getAlias()+e.getGroup(t))),tx({namePrefix:e=>e.getName()})],fx.prototype,"startPlugin",1),nb([ix("update"),WM(((e,t)=>e.getAlias()+e.getGroup(t))),tx({namePrefix:e=>e.getName()})],fx.prototype,"updatePlugin",1),nb([ix("stop"),JM(((e,t)=>e.getAlias()+e.getGroup(t))),tx({namePrefix:e=>e.getName()})],fx.prototype,"stopPlugin",1),nb([$M(...LM.TRTC.enableAudioVolumeEvaluation)],fx.prototype,"enableAudioVolumeEvaluation",1),nb([tx()],fx.prototype,"setCurrentSpeaker",1),nb([GM((e=>"a".concat(e.userId)),(()=>!0))],fx.prototype,"_startRemoteAudio",1),nb([PL((e=>function(t){return sb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(ZC($C({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),JM((e=>"a".concat(e.userId)))],fx.prototype,"_stopRemoteAudio",1),nb([JM("room")],fx.prototype,"_exitRoom",1),nb([JM("screen")],fx.prototype,"_stopScreenShare",1),nb([XM(LM.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return PL(((e,r)=>{let o=new Map;return QO.on($O.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],fx.prototype,"sendSEIMessage",1),nb([tx()],fx.prototype,"getVideoSnapshot",1),nb([XM(LM.TRTC.create)],fx,"_create",1);var gx=fx,Tx=class{constructor(){this._set=new Set,QO.on($O.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(n)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(n)}getKey(e,t,i,n){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(n)}isJoined(e){let{userId:t,roomId:i,sdkAppId:n,room:r}=e;return"rtc"!==r.scene&&this._set.has(this.getKey(t,i,n,r.useStringRoomId))}};function Ex(){return sb(this,null,(function*(){let e,t;try{let t=yield IL();e=t&&t.length}catch(u){}try{let e=yield vL();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:n,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=nw.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:n,h264Decode:o,vp8Encode:r,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};uP.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),uP.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var Sx=ib(ab(),1),Ix=Symbol("instance"),vx=Symbol("cacheResult"),yx=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,kx.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Ax=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Rx=new Map;function Cx(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Rx.get(n)||[];Rx.has(n)||Rx.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=Nx.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return n[vx];n.state instanceof yx&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;if(Array.isArray(e)?0==e.length?n.state instanceof yx&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Ax(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not in from config"))):e!==n.state&&(l=new Ax(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=n.state,u=new yx(d,t,s);kx.call(n,u);let h=e=>{var r;return n[vx]=e,u.aborted||(kx.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[vx])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(kx.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new Ax(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var bx="undefined"!=typeof window&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function kx(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Nx.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Nx=class extends Sx.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Nx.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Ix];n?this.name=n.name+"-"+n.count++:i[Ix]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Rx.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);Rx.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=Nx.instances.get(e),t||Nx.instances.set(e,t=new Nx(e,void 0,Object.create(Nx.prototype)))):(t=Nx.instances2.get(e),t||Nx.instances2.set(e,t=new Nx(e.constructor.name,void 0,Object.create(Nx.prototype)))),t}static getState(e){var t;return null===(t=Nx.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};bx(Nx.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){kx.call(this,e)}};Nx.STATECHANGED="stateChanged",Nx.UPDATEAFSM="updateAFSM",Nx.INIT="[*]",Nx.ON="on",Nx.OFF="off",Nx.instances=new Map,Nx.instances2=new WeakMap;var Dx=ib(ab()),Ox="1",wx="5",Px="2",Lx="3",Mx="4",xx={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158},Vx=[xx.UPDATE_REMOTE_MUTE_STAT,xx.UPLINK_NETWORK_STATS,xx.USER_LIST_RES,xx.MUTE_RESULT],Ux={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report"},Fx="publish_change",Bx="join",Hx="leave",jx="quality_report",Gx="mute_uplink",Wx="publish",Jx="publish_state_change",zx="unpublish",Kx="subscribe",Yx="unsubscribe",qx="subscribe_change",Qx="start_publishing",Xx="stop_publishing",$x="start_push_user_cdn",Zx="stop_push_user_cdn",eV="start_mcu_mix",tV="stop_mcu_mix",iV="get_user_list",nV="change_role",rV="update_constraint_config",oV="rebuild_pc",sV="join/v2",aV="publish/v2",cV="subscribe/v3",lV="ability_status_report",dV="reconnect",uV=new WeakMap;function hV(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=YO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,(()=>{var t;null!=(t=uV.get(e))&&t.has(o)?r():s(n)}),s,a)},onRetrying(t,i){var r;lO(n)&&n.call(this,t,i),null!=(r=uV.get(e))&&r.has(o)&&(uV.get(e).get(o).stopRetry=i)},onRetryFailed:r});return s.value=function(){let t=uV.get(e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return t?t.set(o,{args:n}):uV.set(e,new Map([[o,{args:n}]])),a.apply(this,n).finally((()=>{var t;return null==(t=uV.get(e))?void 0:t.delete(o)}))},s}}function pV(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(r=uV.get(e))&&r.has(t)){let{stopRetry:r,args:s}=uV.get(e).get(t),a=!0;if(n)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),r&&r(),null==(o=uV.get(e))||o.delete(t))}return s.apply(this,c)},o}}var mV=null,_V=!0;function fV(e){pO(e)&&e!==_V&&(_V=e,ew.info("setIsNeedToSchedule ".concat(e)))}function gV(e){return sb(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:n,roomId:r,userSig:o,version:s,frameWorkType:a}=e;return function*(){if(!_V&&mV)return{isCached:!0,result:mV};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(n)),c.append("groupId",String(r)),c.append("sdkVersion",s),c.append("userSig",String(o)),a&&c.append("frameWorkType",String(a));let l=yO(),d=yield function(e,t,i){return new Promise(((n,r)=>{let o=null;vO([vV((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n()}))(SV(i,VN.MAIN),e,{get timeout(){return 1e3*sO(2+t.count[0])}}),vV((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n()}))(SV(i,VN.BACKUP),e,{get timeout(){return 1e3*sO(2+t.count[1])}})]).then((e=>{o=e,n(o)})).catch(r)}))}(c,e,i);d.config&&(d.config.loggerDomain&&fN(d.config.loggerDomain),pO(d.config.scheduleCache)&&fV(!d.config.scheduleCache)),e.delta=yO()-l;let u=function(e,t,i){let n=performance.getEntriesByType("resource"),r=SV(e,VN.MAIN),o=SV(e,VN.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?VN.MAIN:VN.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];uP.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=ZC($C({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,l);return mV=d,{isCached:!1,result:d,detailCost:u}}catch(c){let e=_O(c)?c[0]:c,t=hO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),n=new Sb({code:Tb.SCHEDULE_FAILED,extraCode:t,message:cw({key:rw.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw ew.error(i,t),n}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(AD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),QO.on("28",(()=>fV(!0))),QO.on("63",(()=>fV(!0))),QO.on("84",(()=>fV(!0))),QO.on("201",(e=>{"RECONNECTING"===e.state&&fV(!0)})),QO.on("202",(e=>{"RECONNECTING"===e.state&&fV(!0)}));var TV={main:"",backup:""};function EV(e){_O(e)?(TV.main=e[0],TV.backup=e[1]):TV.main=e}function SV(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:VN.MAIN;return t=jD(e)?i===VN.MAIN?AD.MAIN_OVERSEA:AD.BACKUP_OVERSEA:i===VN.MAIN?AD.MAIN:AD.BACKUP,"https://".concat(TV[i]||t,"/api/v1/config")}function IV(e,t,i){return new Promise(((n,r)=>{zO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg})})).catch(r)}))}var vV=(e,t)=>YO({retryFunction:IV,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var yV=new Set;var AV=class extends Dx.default{constructor(e){var t,i;super(),rb(this,"room"),rb(this,"url"),rb(this,"backupUrl"),rb(this,"race"),rb(this,"_socketInUse"),rb(this,"_socket"),rb(this,"_backupSocket"),rb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_seq",0),rb(this,"_log"),rb(this,"_lastMessageTime",-1),rb(this,"_connnectStartTime",-1),rb(this,"_stopConnectRetry"),rb(this,"bytesSent",0),rb(this,"bytesReceived",0),rb(this,"keepAlive",!1),this.room=e.room,this.race=!!dO(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-yV.size>0&&this.room.enableSPC&&(this.keepAlive=!0,yV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=ew.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=yO();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield vO(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?VN.BACKUP:VN.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:n}=e,r=new WebSocket(t);this.bindSocket(r),n?this._socket=r:this._backupSocket=r;let o=-1;return new Promise(((e,t)=>{r.onclose=t,r.onerror=t,r.onopen=()=>e(r),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(n?VN.MAIN:VN.BACKUP),t(new Sb({code:Tb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{r.onclose=null,r.onerror=null,r.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===VN.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(lD){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(lD){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||1e3!==e.code)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?VN.MAIN:VN.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),e.target===this._socketInUse&&(this.unbindAndCloseSocket(VN.MAIN),this.unbindAndCloseSocket(VN.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=BO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(xx),o=Object.keys(xx)[r.indexOf(i)],s=Ux[o];switch(Vx.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case xx.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&function(e){Ib=e-(new Date).getTime();let t=new Date;t.setTime(e),ew.info("baseTime from server: ".concat(t," offset: ").concat(Ib))}(n.svrTime),this._log.info("ChannelSetup Success"),XP.addSuccessEvent({key:521701,cost:yO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(Ox,{signalInfo:this._signalInfo});else{let e=new Sb({code:Tb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:cw({key:rw.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),XP.addFailedEvent({key:521701,error:e}),this.emit(wx,e)}break;case xx.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return sb(this,null,(function*(){try{fV(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(lN){}}))}reconnect(){return sb(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:n,relayPort:r}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:dV,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:i,relayPort:r},responseCommand:Ux.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),XP.addSuccessEvent({key:521702,cost:yO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(XP.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(lN){this._log.error(lN),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=BO(n),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(r,l);let e=new Sb({code:Tb.API_CALL_TIMEOUT,message:cw({key:rw.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t))};this.on(r,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return YO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(n,"]"))},settings:{retries:n,timeout:r},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),yV.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(VN.MAIN),this.unbindAndCloseSocket(VN.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof yx&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(Nx.STATECHANGED,i))};this.room.on(Nx.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(Px,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e&&this.emit(Lx))}};nb([hV({settings:{retries:1/0,timeout:2e3},onError(e,t){this.room.isDestroyed||t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,this.room.isDestroyed&&t())}})],AV.prototype,"connect",1);var RV=ib(ab()),CV=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],n=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let r=6;r<this.dataView.buffer.byteLength;r++){let i=this.dataView.getUint8(r);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),n=new DataView(i);for(let r=0;r<i.byteLength;r++,t++)n.setInt8(r,this.dataView.getInt8(t));return n}},bV=class{constructor(e,t){this._singlePC=e,this._log=t,rb(this,"_seiMessageList",[]),rb(this,"_smallSeiMessageList",[]),rb(this,"_seiPayloadType",243),rb(this,"_seiAbortMap",new Map),rb(this,"_nonSeiAbortMap",new Map),rb(this,"onSEIMessage",null)}isRunning(e){return this._seiAbortMap.has(e)}start(e){let t=e.direction===VN.TRANSCEIVER_DIRECTION_SENDONLY,i=(t?e.sender:e.receiver).createEncodedStreams(),n=i.readable,r=i.writable,o=new TransformStream({transform:t?(t,i)=>this.encodeVideoFrame(t,i,e):(t,i)=>this.decodeVideoFrame(t,i,e)}),s=new AbortController;n.pipeThrough(o).pipeTo(r,s).catch((e=>{this._log.warn(e)})),this._seiAbortMap.set(e,s)}restart(e){this.stop(e),this.start(e)}stop(e){var t;null==(t=this._seiAbortMap.get(e))||t.abort(),this._seiAbortMap.delete(e)}destroy(){this._seiAbortMap.forEach((e=>e.abort())),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach((e=>e.abort())),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach(((e,t)=>{var i,n;if("inactive"!==e.direction&&e.mid)if(t<4)1===t||2===t?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let r=(t-4)%3==1,o=(t-4)%3==2;(null==(n=null==(i=e.receiver)?void 0:i.track)?void 0:n.kind)===VN.VIDEO&&(r||o)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}}))}catch(GP){this._log.warn(GP)}}pipeSenderOrReceiver(e){let t=e.direction===VN.TRANSCEIVER_DIRECTION_SENDONLY?e.sender:e.receiver,{readable:i,writable:n}=t.createEncodedStreams(),r=new AbortController;this._nonSeiAbortMap.set(e,r),i.pipeTo(n,r).catch((()=>{}))}push(e,t){var i,n;t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==(n=null==(i=this._singlePC.getPeerConnection())?void 0:i.getSenders()[2])?void 0:n.track)&&this._smallSeiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0,n=new DataView(e);for(let r=0;r<e.byteLength;r++)switch(n.getUint8(r)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encodeVideoFrame(e,t,i){try{let t=2===Number(i.mid)?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&t.length>0&&!this.isEmptyFrame(e)){let i=9-this.getNaluCount(e.data);if(i<=0)return;let n=t.splice(0,i).reverse().map(this.encodeSEINalu.bind(this)),r=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(r+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<n.length;e++)for(let t=0;t<n[e].dataView.byteLength;t++)s.setInt8(c++,n[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));e.data=o,this._log.debug("".concat(n.length," sei sent"))}}catch(dN){this._log.warn(dN)}t.enqueue(e)}decodeVideoFrame(e,t,i){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],n=new DataView(e.data),r=0,o=-1,s=-1;for(let i=0;i<e.data.byteLength;i++){let a=n.getUint8(i);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=i-r;if(-1===o?o=a:-1===s&&(s=a,t.push(new CV(new DataView(n.buffer.slice(o,s)))),o=a,s=-1),6!==n.getUint8(i+1)){e.data=new DataView(n.buffer.slice(a)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),lO(this.onSEIMessage)&&t.reverse().forEach((e=>{let t=Number(i.mid);this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,mid:t,streamType:(t-4)%3==2?"auxiliary":"main"})}))}}catch(dN){this._log.warn(dN)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)r.push(255);r.push(n);let o=new DataView(e);return r.push(...new Uint8Array(o.buffer)),r.push(128),new CV(new DataView(new Uint8Array(r).buffer),!0)}},kV=0,NV=!1,DV=new Set,OV=!1,wV=class{constructor(e){rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_isErrorObserved",!1),rb(this,"_waitForPeerConnectionConnectedPromise"),rb(this,"_waitForPeerConnectionConnectedPromiseReject",null),rb(this,"_peerConnection",null),rb(this,"_emitter",new RV.default),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_reconnectionCount",0),rb(this,"_reconnectionTimer",-1),rb(this,"_isFirstConnection",!0),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),rb(this,"_localAddress"),rb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=ew.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&jw&&(this._sei=new bV(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=yO())}afterConnect(e){return sb(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,XP.addSuccessEvent({key:521705,cost:Math.min(yO()-this._prevTime,3e4)})):this._isReconnecting&&XP.addSuccessEvent({key:521706,cost:yO()-this._prevTime}),this._prevTime=-1}catch(lN){throw this._isFirstConnection?(this._isFirstConnection=!1,QO.emit($O.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:lN}),XP.addFailedEvent({key:521705,error:lN})):this._isReconnecting&&this._reconnectionCount>=3&&(XP.addFailedEvent({key:521706,error:lN}),QO.emit($O.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:lN})),lN}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&jw,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),DV.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new Sb({code:Tb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return rD;let e=null;if(this._isUplink){if(!Pw()||0===this._peerConnection.getSenders().length)return rD;e=this._peerConnection.getSenders()[0].transport}else{if(!ww()||0===this._peerConnection.getReceivers().length)return rD;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:rD}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===oD.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===oD.FAILED||e.target.connectionState===oD.CLOSED){let n="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),r=new Sb({message:n,code:Tb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",r)}(e.target.connectionState===oD.CONNECTED||e.target.connectionState===oD.COMPLETED)&&(this.logSelectedCandidate(),uP.logSuccessEvent({userId:this._room.userId,eventType:uD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(kV=0,NV=!1,OV=!0,DV.add(this)):DV.delete(this),QO.emit($O.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(Rw(t)){let i=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{QO.off($O.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{r();let e=new Sb({code:Tb.API_CALL_TIMEOUT,message:"connection timeout"});var i;kV+=1,i=this._signalChannel.isConnected,kV>2&&!NV&&0===DV.size&&i&&(this._log.warn("firewall restrition"),NV=!0,this._emitter.emit("firewall-restriction")),t(e)}),yD);QO.on($O.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Lx,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=cD()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new Sb({code:this._isUplink?Tb.UPLINK_RECONNECTION_FAILED:Tb.DOWNLINK_RECONNECTION_FAILED,message:cw({key:this._isUplink?rw.UPLINK_RECONNECTION_FAILED:rw.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Lx,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},PV=ib(_b()),LV=function(e){return PV.default.parse(e)},MV=function(e){return PV.default.write(e)};function xV(e){return Object.keys(e).filter((t=>e[t]))}var VV=class extends wV{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,auxiliary:0}),rb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new XL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new $L(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ZL(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return kO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===VN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===KN?VN.MAIN:VN.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=VN.AUDIO;i.kind===VN.VIDEO&&(r=n===VN.MAIN?VN.VIDEO:VN.AUXILIARY);let o=this.remoteAudioTrack;r===VN.VIDEO?o=this.remoteVideoTrack:r===VN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let n=[...i];for(let r=0;r<n.length;r++){let[e,i]=n[r];t.splice(e+r,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=LV(e);return t.media.forEach((e=>{e.type===VN.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),MV(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=LV(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),MV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===oD.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===oD.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(uN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(uN.message," ").concat(JSON.stringify(this.muteState))),new Sb({code:Tb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):uN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(n," stream already unsubscribed"));let e=$C({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let r="subscribe_change";Object.values(e).find((e=>!0===e))||(r="unsubscribe"),t._log.info("".concat("unsubscribe"===r?r:"subscribe"," ").concat(n," [").concat(xV(e),"]")),yield t.sendSubscription(r,e),"unsubscribe"===r&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Yx,r=Ux.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=qx,r=Ux.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new Sb({code:i.code,message:cw({key:rw.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(lD){throw e.closePeerConnection(!0),lD}}()}))}exchangeSDP(e){return sb(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:Kx,commandDesc:"exchange sdp",data:n,responseCommand:Ux.SUBSCRIBE_RESULT,timeout:mD});if(!this._peerConnection){let e=new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(r),this._isSDPExchanging=!1}catch(lD){throw this._isSDPExchanging=!1,lD}}))}createOffer(){return sb(this,null,(function*(){let e={voiceActivityDetection:!1};Mw()&&this._sdpSemantics===_D?(this._peerConnection.addTransceiver(VN.AUDIO,{direction:UN.RECVONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:UN.RECVONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:UN.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield Sw();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=LV(e);return t.media.forEach((e=>{var t,i;if(e.type===VN.VIDEO){let n=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&n.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t)}));let r=e=>{let{payload:t}=e;return!n.has(t)};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!n.has(Number(e)))).join(" ")}})),MV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=LV(e);return t.media.forEach((e=>{e.type===VN.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),MV(t)}(t.sdp),this._sdpSemantics===_D&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return sb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===gD)throw new Sb({code:Tb.NOT_SUPPORTED_H264,message:cw({key:rw.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new Sb({code:t,message:cw({key:rw.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",ZC($C({},e),{userId:this.userId}))}),this.updateSSRC(r)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{LV(e).media.forEach((e=>{if(e.ssrcs)if(e.type===VN.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(KN)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(KN)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(YN)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(lD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return sb(this,null,(function*(){if(!(ob(VV.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(lD){let t=aO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}},UV=VV;nb([PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],UV.prototype,"subscribe",1),nb([wL(wV.prototype.afterConnect),OL(wV.prototype.beforeConnect)],UV.prototype,"connect",1);var FV=UV,BV={voiceActivityDetection:!1},HV=class extends wV{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Lw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===VN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),Mw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==n?void 0:n.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||VN.AUDIO,{direction:UN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?VN.VIDEO:s||VN.VIDEO,{direction:UN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||VN.VIDEO,{direction:UN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||VN.VIDEO,{direction:UN.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:VN.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:VN.VIDEO,videoType:o?VN.AUXILIARY:VN.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:VN.VIDEO,videoType:VN.SMALL}),e.push(2))}yield t.setTransceiverDirection(UN.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==n||n.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info("publish by addtrack");let e=null==n?void 0:n.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream;e.addTrack(r),t._peerConnection.addTrack(r,e)}yield t.connect()}()}))}enableSmall(e){return sb(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(UN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(UN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!Lw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent("DISCONNECTED",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(UN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Jx,data:t,responseCommand:Ux.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:zx,commandDesc:"unpublish",responseCommand:Ux.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Tb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Bw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:rV,data:this._mediaSettings,responseCommand:Ux.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?VN.AUXILIARY:VN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),Mw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===VN.AUDIO)yield n[0].sender.replaceTrack(e.outMediaTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===UN.INACTIVE&&(yield this.setTransceiverDirection(UN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Lw()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===VN.VIDEO&&e instanceof jL&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===fD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=LV(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===VN.VIDEO)return!0;return!1}removeSender(e){let t=null;Lw()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&lO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?VN.AUXILIARY:VN.MAIN," stream")),Mw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===VN.AUDIO)yield i[0].sender.replaceTrack(null);else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(UN.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Hb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(UN.INACTIVE,"|").concat(UN.RECVONLY,"|").concat(UN.SENDONLY,")")))&&o++,t.includes(o)){if(e===UN.INACTIVE&&i.includes("a=".concat(UN.RECVONLY)))return n=!0,"a=".concat(e);if(e===UN.SENDONLY&&i.includes("a=".concat(UN.INACTIVE)))return n=!0,"a=".concat(UN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===VN.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===VN.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===VN.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=Mw()?e.kind===VN.AUDIO?n[0]:n[1]:n.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(r?VN.AUXILIARY:VN.MAIN," stream")),e.kind===VN.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===VN.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return sb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(BV);Hb&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===VN.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:Fx,data:r,responseCommand:Ux.UPDATE_OFFER_RESULT,timeout:pD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(dN){throw this._log.error(dN),dN}}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!Fw())return o?n===VN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(Mw()){let t=0;n===VN.VIDEO&&(t=r===VN.SMALL?2:r===VN.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===n));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(r||"").concat(n," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return n===VN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let n="AS";Hb&&(n="TIAS",t*=1e3);let r=0,o=-1;return i===VN.SMALL?r=1:i===VN.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===r?"".concat(e,"b=").concat(n,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return Hb&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return sb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(lN){throw this.closePeerConnection(!0),this.uninstallEvents(),lN}}))}exchangeSDP(){return sb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(lN){throw lN}}))}createOffer(){return sb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(BV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(lN){throw lN}}))}doExchangeSDP(){let e={command:Wx,responseCommand:Ux.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof zL||this.localAuxVideoTrack instanceof zL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",n=LV(e);return n.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),MV(n)}acceptAnswer(e){return sb(this,null,(function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?VN.AUXILIARY:VN.BIG;s=yield this.setBandwidth({bandwidth:e,type:VN.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:VN.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:VN.VIDEO,videoType:VN.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(OU){throw this._log.error("failed to accept remote answer ".concat(OU)),OU}}))}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info("send muted state: ".concat(JSON.stringify(r))),this._signalChannel.send(Gx,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return sb(this,null,(function*(){if(!(ob(HV.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:zx,responseCommand:Ux.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(lD){let t=aO(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&QO.emit($O.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{LV(e).media.forEach(((e,t)=>{if(e.type===VN.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===fD&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(lD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:VN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===VN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===VN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===VN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===VN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===gD?(this._log.error(ow.NOT_SUPPORTED_H264ENCODE),new Sb({code:Tb.NOT_SUPPORTED_H264,message:cw({key:rw.NOT_SUPPORTED_H264ENCODE})})):new Sb({code:Tb.UNKNOWN,message:cw({key:rw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ux.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},jV=HV;nb([PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],jV.prototype,"publish",1),nb([wL(wV.prototype.afterConnect),OL(wV.prototype.beforeConnect)],jV.prototype,"connect",1);var GV=jV,WV=class{constructor(e,t){this.room=e,rb(this,"_log"),rb(this,"_prevReportTime"),rb(this,"_prevReport",{}),rb(this,"_prevEncoderImplementation"),rb(this,"_prevQualityLimitationReason"),rb(this,"_prevAuxQualityLimitationReason"),rb(this,"_prevDecoderImplementationMap",new Map),rb(this,"totalBytesSent",0),rb(this,"totalBytesReceived",0),rb(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return sb(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var r;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===VN.VIDEO){let r,o;if(i.ssrc===n.video?(r=VN.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=VN.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=VN.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,dO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),dO(i.nackCount)||(t[r].nackCount=i.nackCount),dO(i.pliCount)||(t[r].pliCount=i.pliCount),dO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),dO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),dO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!dO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!dO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!dO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?Rw(i)&&hO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===VN.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===VN.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(VN.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(VN.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!dO(i.audioLevel)&&(null==(r=e.localMainAudioTrack)?void 0:r.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!dO(i.frameWidth)){let r=VN.SMALL;i.trackIdentifier===e.getVideoTrackId(VN.VIDEO)||i.ssrc===n.video?r=VN.VIDEO:(i.trackIdentifier===e.getVideoTrackId(VN.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=VN.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(r){this._log.warn("failed to getStats on sender connection ".concat(r))}return t}))}getReceiverStats(e){return sb(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===VN.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,i.jitterBufferDelay&&(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount),t.hasAudio=!0}else{if(Hb&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===n.auxiliary&&r.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&Rw(i)&&hO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);dO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!dO(i.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&i.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(dN){this._log.warn("failed to getStats on receiver connection ".concat(dN))}return t}))}getStats(e,t){return sb(this,null,(function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&r.push(e))),this._spcStats=r}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e)}return{senderStats:i,receiverStats:n}}))}getDifferenceValue(e,t){if(pL(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!pL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*BD,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*BD);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e)}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r}}let{statInterval:r}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=n.get("".concat(e.userId,"_").concat(qN)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=n.get("".concat(e.userId,"_").concat(QN)),r=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),gk&&115===Mk()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),dO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),dO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),dO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),dO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),dO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),dO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r))}));let a=o.msg_down_stream_info;return i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid)))),i.msg_down_stream_info.forEach((e=>{let t=a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(pL(e.msg_audio_status)||pL(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status,o=this.getDifferenceValue(n.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(n.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/o)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/r),i.uint32_audio_total_bitrate=Math.round(8*a/r)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r)}))}})),i}getStatsReport(e){return sb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,n);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},JV=ib(ab()),zV=class extends JV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_log"),rb(this,"_uplinkRTT",0),rb(this,"_uplinkLoss",0),rb(this,"_downlinkRTT",0),rb(this,"_downlinkLoss",0),rb(this,"_downlinkPrevStatMap",new Map),rb(this,"_downlinkLossAndRTTMap",new Map),rb(this,"_interval",-1),rb(this,"_uplinkNetworkQuality",0),rb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=ew.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(Ux.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(Px,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return sb(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===oD.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r<t.length;r++){let e=t[r].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:n,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=n-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[r].getUserId(),audioDelay:t[r].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[r].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i)}))}getStat(e){return sb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!ww())return t;let i=e.getReceivers();try{for(let e=0;e<i.length;e++)(yield i[e].getStats()).forEach((e=>{"candidate-pair"===e.type&&hO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===VN.AUDIO||e.mediaType===VN.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(n){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==oD.DISCONNECTED&&e.connectionState!==oD.FAILED&&e.connectionState!==oD.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=lP.run(MD,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];QO.emit($O.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(zV.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(lP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r})}}))}},KV=zV;rb(KV,"EVENT_NETWORK_QUALITY","0");var YV=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=ew.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&lO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];let o=t.apply(i,n);return TO(o)?o.catch((e=>ew.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(lD){ew.error("".concat(t.name,"() error observed ").concat(lD))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=lP.run(MD,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:aN,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,tN().then((e=>{this._basicInfo.string_os_version=rN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),QO.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent($O.JOIN_START,this.handleJoinStart).addEvent($O.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent($O.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent($O.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent($O.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent($O.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent($O.JOIN_SUCCESS,this.handleJoinSuccess).addEvent($O.JOIN_FAILED,this.handleJoinFailed).addEvent($O.LEAVE_START,this.handleLeaveStart).addEvent($O.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent($O.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent($O.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent($O.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent($O.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent($O.PUBLISH_START,this.handlePublishStart).addEvent($O.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent($O.SUBSCRIBE_START,this.handleSubscribeStart).addEvent($O.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent($O.PLAY_TRACK_START,this.handlePlayStart).addEvent($O.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent($O.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:n}=e;!gO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(n===VN.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent($O.NETWORK_QUALITY,this.handleNetworkQuality).addEvent($O.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent($O.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent($O.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(n.userId,"auxiliary")})).addEvent($O.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)}))}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach(((e,t)=>QO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),lP.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(dO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),dO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),dO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof Sb?Number(i.getExtraCode()||i.getCode()):Tb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let n="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:ZC($C({},QV),{msg_user_info:new XV({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(n,r)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new XV({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===n?(i.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!gO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!gO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/BD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/BD,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n="".concat(r,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*QC(10,6)))}})),i){let e="".concat(r,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/BD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/BD,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof Sb?i.getExtraCode()||i.getCode():Tb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&HN))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&WN))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&GN))>=0}hitTest(e){return e===this._room}checkStorage(){return sb(this,null,(function*(){try{let e=iw.getItem(this._storageKey);e&&(yield this.upload(e),iw.deleteItem(this._storageKey))}catch(GP){this._log.warn(GP)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&iw.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,VN.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,VN.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,qV);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>qV&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+qV):this._pathMainAudioMap.delete(t)})),this._pathMainVideoMap.forEach(((e,t)=>{this.hasVideoFlag(e.userId)?e.statsToReport.uint64_render_first_frame_time-e.statsToReport.uint64_start_enter_time>qV&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+qV):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>qV&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+qV)}getReportData(){this._basicInfo.uint32_networkType=QD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new XV({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:OO(this._signalInfo.relayIp),uint32_client_ip:OO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*QC(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map((e=>e.statsToReport)),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map((e=>e.statsToReport)),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map((e=>e.statsToReport)),uint32_info_client_ip:OO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return JO(e),e}report(){return sb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),iw.deleteItem(this._storageKey),this.initData()}catch(GP){this._log.warn(GP)}}))}upload(e){return sb(this,null,(function*(){if(Qk&&!yk||0===e.msg_path_enter_room.uint64_start_time||[gN,TN,EN].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=yield KO(e),n=i instanceof ArrayBuffer,r="".concat(GD(t,CN.KEY_POINT),"&gzip=").concat(+n),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,i)),o||zO({url:r,body:i}),this.uploadKVStat(XP),this.uploadKVStat(QP)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return sb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=ZC($C({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield KO(t),n="".concat(GD(+this._room.sdkAppId,CN.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),r=!1;navigator.sendBeacon&&(r=navigator.sendBeacon(n,i)),r||zO({url:n,body:i})}))}};nb([hV({settings:{timeout:500,retries:3}})],YV.prototype,"upload",1);var qV=5e3,QV={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},XV=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},$V=YV,ZV=class{constructor(){rb(this,"_startTime"),rb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=yO())}stop(){0===this._endTime&&(this._endTime=yO())}getDuration(){return 0===this._endTime?yO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},eU=class{constructor(e){rb(this,"_room",null),rb(this,"_durationMap"),rb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set($O.SUBSCRIBE_SUCCESS,this.handleSubscribed).set($O.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set($O.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),VN.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),VN.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),VN.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,VN.AUDIO,"main"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,VN.VIDEO,"main"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,VN.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>QO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>QO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);if(n.muteState.hasAudio&&"main"===i)if(n.remoteAudioTrack.isSubscribed){let e=new ZV,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,VN.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new ZV,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,VN.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDurationItem(o,VN.AUDIO),this.stopDurationItem(o,VN.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let n="".concat(e,"_").concat(i),r=new ZV,o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===VN.AUDIO?[r]:[],video:t===VN.AUDIO?[]:[r]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},tU=class{constructor(e){rb(this,"_room"),rb(this,"_renderFreezeMap",new Map),rb(this,"_isVideoPlayingEventFiredMap",new Map),rb(this,"_dataFreezeMap",new Map),rb(this,"_monitorFreezeData",new Map),rb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set($O.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set($O.PLAY_TRACK_START,this.onPlayTrackStart).set($O.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDataFreeze({key:o,userId:r,type:i})})).set($O.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e="main",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}if(i.hasAuxiliary&&!n.hasAuxiliary){let e="auxiliary",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}})).set($O.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:n,type:r}=e;if(gO(t)&&this.hitTest(t.room)&&r===VN.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}n===VN.MUTE?this.onVideoTrackMuted(t):n===VN.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set($O.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>QO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>QO.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i),r=this._dataFreezeMap.get(n),o=new ZV;r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i);this.stopDataFreeze({key:n,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:n}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>ED?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return sb(this,arguments,(function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e="".concat(i,"_").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=yO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=yO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!gO(t)||!this.hitTest(t.room)||t.kind!==VN.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<ED&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,n=0;if(t)if(t.isFreeze){let e=yO()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),n=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},iU=ib(ab(),1),nU=[-1,-1,1,-1,-1,1,1,1],rU=[0,0,1,0,0,1,1,1],oU=class extends rP{constructor(e,t){if(super(),this.context=e,rb(this,"name"),rb(this,"input"),rb(this,"output"),rb(this,"texture"),rb(this,"image"),rb(this,"ctx2d",null),rb(this,"fbo"),rb(this,"width",0),rb(this,"height",0),rb(this,"x",0),rb(this,"y",0),rb(this,"program"),rb(this,"vertexShader"),rb(this,"fragmentShader"),rb(this,"totalFrames",0),rb(this,"dropFrames",0),rb(this,"matchInputSize",!0),rb(this,"texCoordBuffer"),rb(this,"positionBuffer"),rb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),rb(this,"cost",0),rb(this,"_canvas",null),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof fU){if(e.ctx&&t.create2d){let e=document.createElement("canvas"),t="function"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext("2d"),this.image=t,this._canvas=t}}else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(rU),this.positionBuffer=this.createBuffer(nU),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(dN){this.context.destroy(dN)}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof _U&&this.render(e)||this.context instanceof fU&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof _U){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:c,fps:l,name:s,cost:a},$C({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};nb([tP(rP.INIT,"connected",{sync:!0})],oU.prototype,"connect",1),nb([tP("connected",rP.INIT,{ignoreError:!0,sync:!0})],oU.prototype,"disconnect",1),nb([tP([],"closed",{sync:!0})],oU.prototype,"close",1);var sU=[0,1,1,1,0,0,1,0],aU=class extends oU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),rb(this,"_intervalId",0),rb(this,"_sequence",0),rb(this,"checkGLError",!1),e instanceof fU?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(sU)}start(e){this._intervalId=lP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(lP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof _U){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),lP.clearTask(this._intervalId)}},cU=class extends aU{constructor(e,t){super(e,t),rb(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,n)},n=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,n)};e instanceof _U&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},lU=class extends cU{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},dU=class extends cU{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;ew.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>r?i=n/r:(ew.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},uU=class extends oU{constructor(e,t,i){super(e,$C({name:"imageSource"},i)),this.image=t,rb(this,"_image"),rb(this,"_totalFrames",0),rb(this,"_autoResize",!1),this._autoResize=!1!==(null==i?void 0:i.autoResize)}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(lO(this.image.getVideoPlaybackQuality)&&!jk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:i,videoHeight:n}=this.image),this.image.width=i,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);if(!this._autoResize)return!0;if(this.width===i&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},hU=class extends uU{constructor(e,t,i){let n=document.createElement("video");n.setAttribute("playsinline","playsinline"),n.setAttribute("muted",""),super(e,n,i),this._videoTrack=t,rb(this,"_mediaStream"),this.name="videoTrackSource",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play())}close(){var e;super.close(),null==(e=this._mediaStream)||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}},pU=class extends rP{constructor(e){super(),rb(this,"frameRate"),rb(this,"_canvas"),rb(this,"log"),rb(this,"hasAlpha",!1),rb(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e){return new hU(this,e)}createVideoTrackDestination(e){return new cU(this,e)}createVideoImageSource(e,t){return new uU(this,e,t)}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},mU={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_U=class extends pU{constructor(){super(...arguments),rb(this,"defaultProgam"),rb(this,"defaultVShader"),rb(this,"defaultFShader"),rb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",mU),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}createProgram(e,t){let i=this.ctx,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),i.getProgramParameter(n,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(n)),n}};nb([tP(rP.INIT,"created",{sync:!0})],_U.prototype,"create",1),nb([tP("created",rP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],_U.prototype,"destroy",1);var fU=class extends pU{constructor(){super(...arguments),rb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};nb([tP(rP.INIT,"created",{sync:!0})],fU.prototype,"create",1),nb([tP("created",rP.INIT,{ignoreError:!0,sync:!0})],fU.prototype,"destroy",1);var gU=[1,0,0,0,1,1,0,1],TU=class extends oU{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof _U)try{this.setTexBuffer(gU)}catch(lN){e.destroy(lN)}else this.ctx2d&&setTimeout((e=>{e.scale(-1,1),e.translate(-this.width,0)}),0,this.ctx2d)}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},EU=class{constructor(e,t){this.node=e,this.layout=t,rb(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},SU=class extends oU{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),rb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new EU(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context instanceof _U&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:n,height:r,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:s,fps:a,name:o},$C({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof _U))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(n){}}))}},IU=class{constructor(e,t){this.createMediapipeSolutionsWasm=t,rb(this,"canvas"),rb(this,"locateFile"),rb(this,"_glName"),rb(this,"_solutionWasm"),rb(this,"ctx"),rb(this,"pl",{onResults:e=>this.onResults(e.get(0).glName)}),this.locateFile=t=>"".concat(e,"/").concat(t)}bindTexture(){var e;null==(e=this.ctx)||e.activeTexture(this.ctx.TEXTURE0),this.bindTexture2d(this._glName)}initialize(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"selfie_segmentation_landscape.tflite";return sb(this,null,(function*(){yield this.createMediapipeSolutionsWasm(this),this.canvas=e,this.createContext(e,!0,!0,{}),this._glName=this.createTexture(),this._solutionWasm=new this.SolutionWasm;let i=new this.StringList;i.push_back("segmentation_mask");let n=this.PacketListener.implement(this.pl);this._solutionWasm.attachMultiListener(i,n),i.delete(),this._solutionWasm.loadGraph(yield fetch(this.locateFile("selfie_segmentation.binarypb")).then((e=>e.arrayBuffer()))),this._solutionWasm.overrideFile("third_party/mediapipe/modules/selfie_segmentation/selfie_segmentation_landscape.tflite",yield fetch(this.locateFile(t)).then((e=>e.arrayBuffer())));let r=new this.GraphOptionChangeRequestList;return r.push_back({calculatorIndex:1,calculatorName:"",calculatorType:"GlScalerCalculator",fieldName:"flip_horizontal",valueBoolean:!1,valueNumber:0,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value",valueBoolean:!1,valueNumber:1,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"InferenceCalculator",calculatorName:"",fieldName:"use_cpu_inference",valueBoolean:!1,valueNumber:0,valueString:""}),this._solutionWasm.changeOptions(r),this}))}send(e,t){let i=new this.PacketDataList;i.pushTexture2d({stream:"input_frames_gpu",timestamp:1e3*performance.now(),glName:this._glName,width:e,height:t}),this._solutionWasm.send(i),i.delete()}close(){var e,t,i;null==(e=this.canvas)||delete e.getContext,delete this.readyPromiseResolve,delete this.readyPromiseReject,this.pl.onResults=null,delete this.onResults,null==(t=this.deleteTexture)||t.call(this,this._glName),null==(i=this._solutionWasm)||i.delete();for(let n of Object.keys(this))delete this[n]}},vU=class extends hU{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0}),rb(this,"ready",!1),rb(this,"_bgTexture"),rb(this,"_waterMarkTexture"),rb(this,"_lastMaskTexture"),rb(this,"_textureValid",!1),rb(this,"_selfieTextureValid",!1),rb(this,"_selfieSegmentation"),rb(this,"wasm"),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return sb(this,null,(function*(){let t=yield e.Wasm(),i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:n,height:r}=e.waterMark;this.wasm.setWaterMark(t,i,n,r)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._selfieSegmentation=yield e.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.ready=!0}))}onPredict(e){let t=this.context.ctx;this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image)),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,0==(1&this.totalFrames)?this._lastMaskTexture:this.texture),t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,this.width,this.height),this.useProgram(),this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.activeTexture(t.TEXTURE4),t.bindTexture(t.TEXTURE_2D,0!=(1&this.totalFrames)?this._lastMaskTexture:this.texture),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality&&!jk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:n}=this.image;this.image.width=i,this.image.height=n;let r=!1;if(this.totalFrames)this._selfieSegmentation.bindTexture(),r=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),r=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===n&&r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&this._selfieSegmentation.send(i,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),null==(e=this.wasm)||e.close()}},yU=class extends iU.EventEmitter{constructor(e){super(),this.room=e,rb(this,"videoContext"),rb(this,"_glVideoContext"),rb(this,"_2dVideoContext"),rb(this,"destination"),rb(this,"smallVideoContext"),rb(this,"smallDestination"),rb(this,"smallTrackSource"),rb(this,"smallImageSource"),rb(this,"_isMirror",!1),rb(this,"cameraTrack"),rb(this,"cameraNode"),rb(this,"mirrorNode"),rb(this,"mixNode"),rb(this,"screenTrack"),rb(this,"screenNode"),rb(this,"selfModel",!1),rb(this,"blurRadius",3),rb(this,"Wasm"),rb(this,"waterMarkNode"),rb(this,"_waterMarkOption"),rb(this,"watermarkImageList",[]),rb(this,"_isMixScreen",!1),rb(this,"_virualBackground"),rb(this,"_bgAssetPath"),rb(this,"log",ew.createLogger({id:"vm"})),rb(this,"_checkId",0),rb(this,"_use2d",!1),rb(this,"_autoSwitchRenderMode",!0),rb(this,"_selfieSegmentation"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new fU({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirualBg(){return!!this._virualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new fU({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new _U({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(lN){this.emit("error",{reason:"create",error:lN}),this.sendCreateResult("videoCtxGl",lN)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=lP.run(VD,(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}destroy(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),lP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirualBg}get active(){return(jk||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?XP.addFailedEvent({key:t,error:e}):XP.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){if(!this._selfieSegmentation){let t=new IU(e.assetPath||"./selfie_segmentation",e.createMediapipeSolutionsWasm),i=this.getGlVideoContext();return i.available?this._selfieSegmentation=t.initialize(i._canvas,"selfie_segmentation_landscape.tflite"):Promise.reject(new Error("init virtual background failed, reason: video context unavailable"))}return this._selfieSegmentation}_setMainOutput(e){var t;let i=this.cameraTrack,{small:n,settings:r,player:o}=i;return n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new dU(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=r.width,this.smallTrackSource.height=r.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),jk&&o.setCanvas(e),i.setOutputMediaStreamTrack(e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack)}update(){return sb(this,null,(function*(){var e,t;if(this.cameraTrack&&this.cameraTrack.mediaTrack){if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this._use2d||!this._selfieSegmentation?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new lU(this.videoContext,{name:"mainDestination"})),this.cameraNode=new vU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate}if(this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new TU(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new SU(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)}}))}changeInput(e){return this.log.info("change input"),e instanceof zL?this.setScreenTrack(e):e instanceof jL?this.setCameraTrack(e):e instanceof $L?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){var t;e instanceof zL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof jL&&(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource))}setCameraTrack(e){return sb(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return sb(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let n=i.getContext("2d");return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:r,width:o,height:s}=e;n.drawImage(t,i,r,o,s)})),GO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setWatermark(e){return sb(this,null,(function*(){let t;try{t=yield GO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new Sb({code:Tb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:n=0,width:r=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:n,width:r,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return sb(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return sb(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let n=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:n.width,height:n.height,image:n},this.update()}))}setVirtualBackground(e){return sb(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virualBackground=yield GO(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virualBackground=e.type)}else this._virualBackground=void 0;this.log.info("".concat(this._virualBackground?"start":"stop"," visual background, ").concat((null==e?void 0:e.type)||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},AU=0,RU=class extends rP{constructor(e){super("room"),this.seq=++AU,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=ew.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,pO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),pO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),pO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new $V({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new eU({room:this}),this.badCaseDetector=new tU({room:this}),this.audioManager=new YL(this),this.videoManager=new yU(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return sb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return sb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return sb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(uO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(oO(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(EV([o,o]),fN("https://".concat(o))):(n&&fN(n),r&&EV(r))}QO.once($O.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:TV.main,sched_back_domain:TV.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return sb(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let n="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ow.INVALID_DESTROY),new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,QO.emit($O.ROOM_DESTROY,{room:this})}schedule(e,t){return sb(this,null,(function*(){var i,n;let r=yO();try{let{isCached:o,result:s,detailCost:a}=yield gV({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:aN,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(UO(s,{keysToExclude:["username","credential"]}))),o&&QO.once($O.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=$C($C({},this.scheduleResult),s),hO(null==(i=s.config)?void 0:i.retryCount)&&aD(s.config.retryCount),uO(null==(n=s.config)?void 0:n.loggerDomain)&&fN(s.config.loggerDomain),QO.emit($O.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),XP.addSuccessEvent({key:521700,cost:yO()-r,split:50})}catch(o){throw XP.addFailedEvent({key:521700,error:o}),o}}))}},CU=ib(ab()),bU=ib(_b()),kU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=LV(n),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:VN.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:VN.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(NU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),r&&s.media.push(o.media.find((e=>"dc"===e.mid))),MV(s)},NU=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:VN.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:VN.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;a<i.video.codecs.length;a++)DU(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));DU(s,i.video.codecs[e])}else if(o)for(let a=0;a<n.video.codecs.length;a++)DU(s,n.video.codecs[a]);else DU(s,n.video.codecs[0]);return s.payloads=s.payloads.trim(),s},DU=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var OU,wU=e=>{let t=bU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===VN.AUDIO||e.type===VN.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===VN.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===VN.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),bU.default.write(t)},PU=((OU=PU||{}).TRACK="track",OU.DATA_CHANNEL_MESSAGE="data_channel_msg",OU[OU.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",OU[OU.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",OU.RECONNECTED="spc-reconnected",OU.RECONNECT_FAILED="spc-reconnect-failed",OU.ERROR="error",OU.SEI_MESSAGE="sei-message",OU),LU=0,MU=!1,xU=new Set,VU=1,UU=class extends CU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),rb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),rb(this,"currentState","DISCONNECTED"),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_peerConnection",null),rb(this,"_datachannel",null),rb(this,"_enableCustomMessage"),rb(this,"_log"),rb(this,"_downlinkMIDMap",new Map),rb(this,"_downlinkMIDUserIDMap",new Map),rb(this,"_reconnectionTimer",-1),rb(this,"reconnectionCount",0),rb(this,"_clientAbility",null),rb(this,"_serverAbility",null),rb(this,"addDownlinkQueue",new Set),rb(this,"removeDownlinkQueue",new Set),rb(this,"_parsedAnswer",null),rb(this,"_updateSDPPromise",null),rb(this,"_waitForPCConnectedPromise"),rb(this,"_waitForPCConnectedPromiseReject",null),rb(this,"_isSDPLogged",!1),rb(this,"seiCodec",null),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=ew.createLogger({id:"spc".concat(VU++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&jw&&(this._log.info("create sei codec"),this.seiCodec=new bV(this,this._log),this.seiCodec.onSEIMessage=e=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(e.mid),data:e.data,seiPayloadType:e.seiPayloadType,streamType:e.streamType})})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return null!=(e=this._serverAbility)&&e.useVp8?"vp8":"h264"}get isUsingH264(){return"h264"===this.videoCodec}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=LV(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var n;if(e.ssrcs&&!dO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return sb(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&jw,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new BU(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(VN.AUDIO,{direction:VN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:VN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:VN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:VN.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=((e,t)=>{var i,n;let r=LV(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||"",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||""),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||"";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(lN){throw this._log.error("initialize failed ".concat(lN)),lN}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return sb(this,null,(function*(){var i;try{if("CONNECTED"===this.currentState)return;let n=yO(),r={type:"answer",sdp:kU({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||XP.addSuccessEvent({key:521703,cost:yO()-n}),null==(i=this.seiCodec)||i.handleEncodedStreams()}catch(n){let t=n instanceof Sb&&n.code===Tb.API_CALL_ABORTED;throw t||this._log.error("connect failed: ".concat(n),e),this.reset(),!t&&!this.isReconnecting&&(XP.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}}))}reconnect(){return sb(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(Lx,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:oV,responseCommand:Ux.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new Sb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),XP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),QO.emit($O.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(lN){if(!this.isReconnecting)return;if(null!=lN&&lN.message.includes("timeout")){let e=aO(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(null==lN?void 0:lN.code," ").concat(lN)),XP.addFailedEvent({key:521704,error:lN}),this.reconnectionCount>=cD()&&this._log.warn("SDK has tried reconnect for ".concat(cD()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return sb(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Lx,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===oD.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(i)),e.target.connectionState===oD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===oD.FAILED||e.target.connectionState===oD.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===oD.CONNECTED||e.target.connectionState===oD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),QO.emit($O.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return rD;let e=null;return Pw()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,ww()&&0!==this._peerConnection.getReceivers().length&&e?e.state:rD):rD}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(PU.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(Rw(i)){let t=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&qD(t.networkType)),n&&this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{QO.off($O.LEAVE_SUCCESS,n,this),this.off(PU.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{r();let e=new Sb({code:Tb.API_CALL_TIMEOUT,message:"connection timeout"});var i;LU+=1,i=this._signalChannel.isConnected,LU>2&&!MU&&0===xU.size&&i&&(this._log.warn("firewall restrition"),MU=!0,this.emit(PU.FIREWALL_RESTRICTION)),t(e)}),yD);QO.on($O.LEAVE_SUCCESS,n,this),this.on(PU.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return sb(this,null,(function*(){var t;if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),null==(t=this.seiCodec)||t.handleEncodedStreams(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(dN){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=VN.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(VN.AUDIO,{direction:VN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:VN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(VN.VIDEO,{direction:VN.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=LV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=NU({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:LV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}r.direction=VN.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(n)},{id:t.audio,attribute:"msid",value:"".concat(n,"-").concat(VN.MAIN," ").concat(n,"-audio")}],o.direction=VN.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(n)},{id:t.video,attribute:"msid",value:"".concat(n,"-").concat(VN.MAIN," ").concat(n,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(n)},{id:t.videoRtx,attribute:"msid",value:"".concat(n,"-").concat(VN.MAIN," ").concat(n,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],s.direction=VN.TRANSCEIVER_DIRECTION_SENDONLY;let c="".concat(n,"-aux");s.ssrcs=[{id:t.auxiliary,attribute:"cname",value:c},{id:t.auxiliary,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(VN.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(c," ").concat(n,"-aux").concat(VN.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(VN.VIDEO)}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[r.mid,o.mid,s.mid]),this._downlinkMIDUserIDMap.set(r.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i)}removeDownlink(e,t){return sb(this,null,(function*(){if(!this._downlinkMIDMap.has(t)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let e=this._downlinkMIDMap.get(t),i=!1;this._peerConnection.getTransceivers().forEach((t=>{null!=e&&e.includes(Number(t.mid))&&(i=!0,t.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=LV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((t=>{null!=e&&e.includes(Number(t.mid))&&(i=!0,t.direction="inactive",t.ssrcs=[],t.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(t),null==e||e.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(t,") done"))}))}setBandwidth(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(Fw()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&n?o=n:3===s&&r&&(o=r),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),r&&e[3].track&&(o=this.setStartBitrate(3,r)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth".concat(o))}}))}setStartBitrate(e,t){var i,n;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=LV(this._peerConnection.remoteDescription.sdp)),null==(n=this._parsedAnswer.media[e])||!n.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=LV(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=LV(this._peerConnection.remoteDescription.sdp));let s=Hb?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:Hb?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:Hb?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:Hb?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:Hb?1e3*i:i}]),n&&(o.media[2].bandwidth=[{type:s,limit:Hb?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:Hb?1e3*n:n}]),r&&(o.media[3].bandwidth=[{type:s,limit:Hb?1e3*r:r}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:Hb?1e3*r:r}]);let a={type:"offer",sdp:MV(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=MV(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,n)=>sb(this,null,(function*(){var r,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(OU){this._log.error(OU),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(r=this._peerConnection.localDescription)?void 0:r.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,n(OU)}})))),this._updateSDPPromise}filterSDPDirection(){return LV(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:wU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var i;null==(i=this.seiCodec)||i.push(e,t)}};nb([VL("reconnect")],UU.prototype,"startReconnection",1),nb([xL()],UU.prototype,"updateSDP",1);var FU=class{constructor(e){rb(this,"tag"),rb(this,"len"),rb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},BU=class{constructor(e){rb(this,"tinyId"),rb(this,"data");let t=new DataView(e),i=0,n=[];for(;i<t.byteLength;){let r=t.getUint16(i+2),o=new FU(new Uint8Array(e).slice(i,i+2+2+r).buffer);n.push(o),i+=4+r}n.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},HU=new Set;function jU(){let e=Math.floor(4294967296*Math.random());return HU.has(e)?jU():(HU.add(e),e)}var GU=ib(ab()),WU=class extends GU.default{constructor(e){super(),rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_currentState","DISCONNECTED"),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=ew.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&jw&&(this._sei=new bV(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(QO.emit($O.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},JU=class extends WU{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Lw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===VN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new Sb({code:Tb.NOT_SUPPORTED_H264,message:cw({key:rw.NOT_SUPPORTED_H264ENCODE})});Vb&&115===Mk()&&n.profile.width*n.profile.height<=230400&&(t._log.warn("fallback video to 480p"),n.setProfile(MN["480p_2"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n,r?(h.auxVideo=!0,p.auxVideo=n.muted):(h.bigVideo=!0,p.bigVideo=n.muted)}if(t._isPublishingAux=r,n&&!r&&n.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponse({command:aV,responseCommand:Ux.SPC_PUBLISH_RESULT,data:ZC($C({},t.singlePC.uplinkSSRC),{state:h,muteState:p})}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:u,isAuxiliary:r}),null==(e=t.singlePC.seiCodec)||e.handleEncodedStreams(),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r)n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i);else{if(n){t.localMainVideoTrack=n;let{scaleResolutionDownBy:e}=n;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(o=t.localMainAudioTrack)?void 0:o.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(l=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:l.bitrate,auxVideo:null==(d=t.localAuxVideoTrack)?void 0:d.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;if(!Mw())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e)}let d=this.setTransceiverDirection(UN.SENDONLY,l);return c.push(d),Promise.all(c)}enableSmall(e){return sb(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(UN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(UN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(UN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:Jx,data:t,responseCommand:Ux.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:zx,commandDesc:"unpublish",responseCommand:Ux.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Tb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Bw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:rV,data:this._mediaSettings,responseCommand:Ux.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?VN.AUXILIARY:VN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),Lw()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===VN.AUDIO)yield n[0].sender.replaceTrack(e.outMediaTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===UN.INACTIVE&&(yield this.setTransceiverDirection(UN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?VN.AUXILIARY:VN.MAIN," stream")),Lw()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===VN.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(UN.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Hb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(UN.INACTIVE,"|").concat(UN.RECVONLY,"|").concat(UN.SENDONLY,")")))&&o++,t.includes(o)){if(e===UN.INACTIVE&&i.includes("a=".concat(UN.RECVONLY)))return n=!0,"a=".concat(e);if(e===UN.SENDONLY&&i.includes("a=".concat(UN.INACTIVE)))return n=!0,"a=".concat(UN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!n||i.find((e=>e.track===n)))return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(n.kind," track on ").concat(r?VN.AUXILIARY:VN.MAIN," stream")),n.kind===VN.AUDIO&&i[0]&&(yield i[0].replaceTrack(n)),n.kind===VN.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(n)),r&&i[3]&&(yield i[3].replaceTrack(n)))}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===VN.AUDIO?e.audio=i:"big"===r?e.bigVideo=i:"small"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:Gx,responseCommand:Ux.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&QO.emit($O.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:VN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===VN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===VN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===VN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===VN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===gD?(this._log.error(ow.NOT_SUPPORTED_H264ENCODE),new Sb({code:Tb.NOT_SUPPORTED_H264,message:cw({key:rw.NOT_SUPPORTED_H264ENCODE})})):new Sb({code:Tb.UNKNOWN,message:cw({key:rw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ux.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return sb(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};function zU(e){return Object.keys(e).filter((t=>e[t]))}var KU=class extends WU{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new XL(this._room,this),this.remoteVideoTrack=new $L(this._room,this),this.remoteAuxiliaryTrack=new ZL(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return kO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===VN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=VN.AUDIO;i.kind===VN.VIDEO&&(r=n===VN.MAIN?VN.VIDEO:VN.AUXILIARY);let o=this.remoteAudioTrack;r===VN.VIDEO?o=this.remoteVideoTrack:r===VN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info("subscribe ".concat(t," ").concat(zU(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e)}catch(dN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(dN.message," ").concat(JSON.stringify(this.muteState))),new Sb({code:Tb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):dN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(n," stream already unsubscribed"));let r=$C({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1}}));let o="subscribe_change";Object.values(r).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(n," [").concat(zU(r),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Yx,r=Ux.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=qx,r=Ux.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new Sb({code:i.code,message:cw({key:rw.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:jU(),bigVideoSsrc:jU(),bigVideoRtxSsrc:jU(),auxVideoSsrc:jU(),auxVideoRtxSsrc:jU()},{audioSsrc:r,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:r,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let n=yield e._signalChannel.sendWaitForResponseWithRetry({command:cV,responseCommand:Ux.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==n.data.code)throw new Sb({code:n.data.code,message:n.data.message})}catch(n){throw yield e.removeDownlink(),n}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return sb(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};nb([PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this.off("closed",r),n(new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.CONNECTION_ABORTED,data:e})}))};this.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this.off("closed",r)}))}))}))],KU.prototype,"subscribe",1);var YU=KU;var qU,{isString:QU,isPlainObject:XU,isUndefined:$U,getNetworkType:ZU,getTerminalType:eF,isEmpty:tF}=Ab,iF=class extends RU{constructor(e){super(e),this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this._signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=xw,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new WV(this,this._log),this.userManager=new fM(this.userId,this._log),this._version=aN,this.sdpSemantics=fD,$U(e.sdpSemantics)?nw.isUnifiedPlanDefault()&&(this.sdpSemantics=_D):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(ZU())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!$U(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!$U(e.enableSPC)&&xw&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return sb(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var n in e)KC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&JC)for(var n of JC(e))t.indexOf(n)<0&&YC.call(e,n)&&(i[n]=e[n]);return i})(e,[]);QO.emit($O.REMOTE_PUBLISH_STATE_CHANGED,$C({room:this},t)),this.emit("remote-publish-state-changed",$C({},t))})),this._joinOptions=e,new Promise(((t,i)=>sb(this,null,(function*(){this._joinReject=i;try{this.checkDestroy();let[,i]=yield Promise.all([this.initialize(),this.initSinglePC()]);yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(n){i(n)}this._joinReject=null}))))}))}initSinglePC(){return sb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new UU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(lN){this.singlePC.close(),this.singlePC=null}}}))}doJoin(e,t){return new Promise(((i,n)=>sb(this,null,(function*(){var r,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(wx,(e=>{this.clearJoinTimeout(),QO.emit($O.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),n(e)})),pO(null==(o=null==(r=this.scheduleResult)?void 0:r.config)?void 0:o.singlePC)&&xw&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:eF(),netType:QD(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{n(new Sb({code:Tb.JOIN_ROOM_FAILED,message:cw({key:rw.JOIN_ROOM_TIMEOUT})}))}),c),QO.emit($O.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?sV:Bx,a),this._signalChannel.once(Ux.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:r,data:o,tinyId:s}=e.data;QO.emit($O.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(r)),n(new Sb({code:Tb.JOIN_ROOM_FAILED,extraCode:t,message:cw({key:rw.JOIN_ROOM_FAILED,data:{error:r,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),i.push(this._signalChannel.connect())),yield Promise.all(i),yield this.doJoin(ZC($C({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey}),t),this._log.warn("reJoin success"),uP.logSuccessEvent({userId:this.userId,eventType:uD.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(PU.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof JU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(PU.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof GV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(lD){this._log.warn("reJoin fail ".concat(lD)),this.reset(),uP.logFailedEvent({userId:this.userId,eventType:uD.REJOIN,error:lD}),this.emit("error",new Sb({code:Tb.JOIN_ROOM_FAILED,message:cw({key:rw.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return sb(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...yV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new AV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._networkQuality||(this._networkQuality=new KV({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(KV.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),MP(this,this._signalChannel).add(Px,(e=>{QO.emit($O.SIGNAL_CONNECTION_STATE_CHANGED,$C({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(Mx,(e=>{this.reset(),this.emit("error",e)})).add(Ux.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n})})).add(Ux.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(Ux.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(Ux.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(uP.uploadEvent({log:"stat-banned:".concat(i),userId:this.userId}),"user_time_out"===i)return this._log.warn("".concat(i," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),this.reset(),this.emit("banned",{reason:i})})),this._signalChannel.once(Ox,(e=>{this.tinyId=e.signalInfo.tinyId,QO.emit($O.JOIN_SIGNAL_CONNECTION_END,{room:this})})),QO.emit($O.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n&&QO.emit($O.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this._signalChannel=e,e||xP(this)}leave(){return sb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(lD){}this._log.info("leave() => leaving room"),QO.emit($O.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(Hx)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=lP.run(MD,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),lP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return sb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if(pM.has(e)){let t=pM.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return pM.delete(e),t}return[]}(this.userId):[],r=$C({str_sdk_version:sN,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:QD()},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);QO.emit($O.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(jx,r),this.emit("heartbeat-report",ZC($C({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n}}));QO.emit($O.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:n}=e,r=new(this.singlePC?YU:FV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit("remote-published",r)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==Tb.ICE_TRANSPORT_ERROR&&(i===Tb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",ZC($C({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=lP.run(MD,this.syncUserList.bind(this)))}stopSyncUserListInterval(){lP.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this._signalChannel)&&e.isConnected?this._signalChannel.sendWaitForResponse({command:iV,responseCommand:Ux.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n}}));throw cw({key:rw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ux.USER_LIST_RES,code:i,message:n}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!OV)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===oD.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof wV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===oD.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return sb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),uP.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(!1),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new GV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach((e=>{let t=new FV({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return sb(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:nV,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:Ux.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this._signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:n}=t.data;if(0!==i)throw new Sb({code:Tb.SWITCH_ROLE_FAILED,message:cw({key:rw.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e})).catch((e=>{throw e instanceof Sb&&e.getCode()===Tb.API_CALL_TIMEOUT&&(e=new Sb({code:Tb.SWITCH_ROLE_FAILED,message:cw({key:rw.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof HL&&(t instanceof KL?i.audio=t:e.audio=t),t instanceof jL&&(t instanceof zL&&2===t.mediaType?i.video=t:e.video=t)}));let n=tF(e),r=tF(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new JU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new GV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",ZC($C({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Tb.ICE_TRANSPORT_ERROR&&(t===Tb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");n||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),r||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof HL&&(t instanceof KL?i.audio=t:e.audio=t),t instanceof jL&&(t instanceof zL&&2===t.mediaType?i.video=t:e.video=t))}));try{let n=t.map((e=>e.kind)).join(",");tF(e)||(this._log.info("unpublish() => main ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),tF(i)||(this._log.info("unpublish() => aux ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(n){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&Uw()?this.uplinkConnection.replaceTrack(e).then((t=>{QO.emit($O.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return sb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return sb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:VN.VIDEO,videoType:VN.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let r=$C({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),QO.emit($O.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info("subscribe() => ".concat(e," ").concat(n," [").concat(xV(r),"] prev: [").concat(xV(i.subscribeState),"]")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),QO.emit($O.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}catch(uN){let i=uN instanceof Sb?uN.getCode():Tb.UNKNOWN,r=uN;throw uN instanceof Sb?i===Tb.REMOTE_STREAM_NOT_EXIST&&(r=new Sb({code:Tb.API_CALL_ABORTED,message:cw({key:rw.API_CALL_ABORTED,data:{message:uN.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new Sb({code:i,message:cw({key:rw.SUBSCRIBE_FAILED,data:{message:uN.message,userId:e,streamType:n}})}),this._log.error(r)),r}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n})}catch(uN){this._log.warn("unsubscribe() => failed ".concat(uN))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),QO.emit($O.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void lP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),QO.emit($O.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&lP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=lP.run(xD,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit("audio-volume",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return sb(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return sb(this,null,(function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)"main"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),"auxiliary"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Ab.getTurnServer(e)))):Ab.isPlainObject(e)&&i.push(Ab.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:eV,data:e,timeout:5e3,responseCommand:Ux.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:tV,data:e,timeout:5e3,responseCommand:Ux.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?Qx:$x,data:e,timeout:5e3,responseCommand:t?Ux.START_PUBLISH_TENCENT_CDN_RES:Ux.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this._signalChannel.sendWaitForResponse({command:t?Xx:Zx,data:e,timeout:5e3,responseCommand:t?Ux.STOP_PUBLISH_TENCENT_CDN_RES:Ux.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:lV,data:e,timeout:5e3,responseCommand:Ux.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Ab.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this._signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return sb(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:n,hasVideo:r}}=e;if(!n&&!r||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&n)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!n&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(PD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=PD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(PD-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:PD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(QU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!$U(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new Sb({code:Tb.INVALID_PARAMETER,message:cw({key:rw.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!$U(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new Sb({code:Tb.INVALID_PARAMETER,message:cw({key:rw.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!$U(e.userDefinePushArgs)){if(!(QU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new Sb({code:Tb.INVALID_PARAMETER,message:cw({key:rw.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}tF(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}};return nb([Cx(["left",Nx.INIT],"joined"),hV({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),fV(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),PL((e=>{let t=new Tx;return function(i,n,r){return sb(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new Sb({code:Tb.INVALID_OPERATION,message:cw({key:rw.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),QO.emit($O.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield nw.checkSystemRequirementsInternal(),this.checkDestroy();let s=Ab.getEnv();s||(s=bN.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(FN.OLD_CLOUD_LADDER)?s=bN.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(FN.WEBRTC)&&(s=bN.WEBRTC))),uP.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Ex.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!nw.isWebRTCSupported()||!a&&!c)throw new Sb({code:Tb.NOT_SUPPORTED,message:cw({key:rw.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ab.getEnv()&&(yield this.schedule(o,r));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Ab.performanceNow(),QO.emit($O.JOIN_SUCCESS,{room:this}),uP.uploadEvent({log:"stat-conv-".concat(Number(Qk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),QO.emit($O.JOIN_FAILED,{room:this,error:l}),l}}))}}))],iF.prototype,"join",1),nb([Cx("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),PL((e=>function(){return sb(this,null,(function*(){QO.emit($O.LEAVE_START,{room:this}),yield e.call(this),QO.emit($O.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),VL("leave room"),pV({fnName:"publish",validateArgs:!1}),pV({fnName:"unsubscribe",validateArgs:!1})],iF.prototype,"leave",1),nb([xL(),PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;QO.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),hV({settings:{retries:cD,timeout:e=>aO(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),QO.emit($O.PUBLISH_FAILED,{room:this}))}})],iF.prototype,"publish",1),nb([pV({fnName:"publish"}),(qU="api-call",function(e,t,i){let n=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=LL.get(this);if(r){let e=r.filter(((e,i)=>{if(0===i)return!0;let n=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(n=!1)})),!n||(e.reject(new Sb({code:Tb.API_CALL_ABORTED,message:qU})),!1)}));LL.set(this,e)}return n.apply(this,t)},i}),xL(),PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>e.unpublish())),r}))],iF.prototype,"unpublish",1),nb([UL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),PL((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(r))),r})),hV({settings:{retries:cD,timeout:e=>aO(e)},onError(e,t,i,n){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),QO.emit($O.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}))}})],iF.prototype,"subscribe",1),nb([pV({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.singlePC||t.forEach((e=>{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close("you unsubscribed")}))}}),UL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],iF.prototype,"unsubscribe",1),gx.create=gx._create.bind(gx,iF),gx}));