trtc-sdk-v5 5.13.2-wasm.5 → 5.14.0-beta.1

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.
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(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=function(e){return e&&e.Math===Math&&e},r=t("object"==typeof globalThis&&globalThis)||t("object"==typeof window&&window)||t("object"==typeof self&&self)||t("object"==typeof e&&e)||t("object"==typeof e&&e)||function(){return this}()||Function("return this")(),i={},o=function(e){try{return!!e()}catch(t){return!0}},n=!o((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),a=!o((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),s=a,c=Function.prototype.call,l=s?c.bind(c):function(){return c.apply(c,arguments)},d={},u={}.propertyIsEnumerable,h=Object.getOwnPropertyDescriptor,p=h&&!u.call({1:2},1);d.f=p?function(e){var t=h(this,e);return!!t&&t.enumerable}:u;var m,f,_=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},g=a,E=Function.prototype,v=E.call,y=g&&E.bind.bind(v,v),T=g?y:function(e){return function(){return v.apply(e,arguments)}},I=T,A=I({}.toString),S=I("".slice),R=function(e){return S(A(e),8,-1)},b=o,w=R,C=Object,D=T("".split),N=b((function(){return!C("z").propertyIsEnumerable(0)}))?function(e){return"String"===w(e)?D(e,""):C(e)}:C,k=function(e){return null==e},O=k,M=TypeError,L=function(e){if(O(e))throw new M("Can't call method on "+e);return e},P=N,x=L,U=function(e){return P(x(e))},V="object"==typeof document&&document.all,F=void 0===V&&void 0!==V?function(e){return"function"==typeof e||e===V}:function(e){return"function"==typeof e},B=F,H=function(e){return"object"==typeof e?null!==e:B(e)},W=r,j=F,G=function(e,t){return arguments.length<2?(r=W[e],j(r)?r:void 0):W[e]&&W[e][t];var r},z=T({}.isPrototypeOf),K=r.navigator,q=K&&K.userAgent,Y=q?String(q):"",J=r,X=Y,$=J.process,Q=J.Deno,Z=$&&$.versions||Q&&Q.version,ee=Z&&Z.v8;ee&&(f=(m=ee.split("."))[0]>0&&m[0]<4?1:+(m[0]+m[1])),!f&&X&&(!(m=X.match(/Edge\/(\d+)/))||m[1]>=74)&&(m=X.match(/Chrome\/(\d+)/))&&(f=+m[1]);var te=f,re=te,ie=o,oe=r.String,ne=!!Object.getOwnPropertySymbols&&!ie((function(){var e=Symbol("symbol detection");return!oe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&re&&re<41})),ae=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,se=G,ce=F,le=z,de=Object,ue=ae?function(e){return"symbol"==typeof e}:function(e){var t=se("Symbol");return ce(t)&&le(t.prototype,de(e))},he=String,pe=function(e){try{return he(e)}catch(t){return"Object"}},me=F,fe=pe,_e=TypeError,ge=function(e){if(me(e))return e;throw new _e(fe(e)+" is not a function")},Ee=ge,ve=k,ye=function(e,t){var r=e[t];return ve(r)?void 0:Ee(r)},Te=l,Ie=F,Ae=H,Se=TypeError,Re={exports:{}},be=r,we=Object.defineProperty,Ce=function(e,t){try{we(be,e,{value:t,configurable:!0,writable:!0})}catch(r){be[e]=t}return t},De=r,Ne=Ce,ke="__core-js_shared__",Oe=Re.exports=De[ke]||Ne(ke,{});(Oe.versions||(Oe.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Me=Re.exports,Le=Me,Pe=function(e,t){return Le[e]||(Le[e]=t||{})},xe=L,Ue=Object,Ve=function(e){return Ue(xe(e))},Fe=Ve,Be=T({}.hasOwnProperty),He=Object.hasOwn||function(e,t){return Be(Fe(e),t)},We=T,je=0,Ge=Math.random(),ze=We(1..toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ze(++je+Ge,36)},qe=Pe,Ye=He,Je=Ke,Xe=ne,$e=ae,Qe=r.Symbol,Ze=qe("wks"),et=$e?Qe.for||Qe:Qe&&Qe.withoutSetter||Je,tt=function(e){return Ye(Ze,e)||(Ze[e]=Xe&&Ye(Qe,e)?Qe[e]:et("Symbol."+e)),Ze[e]},rt=l,it=H,ot=ue,nt=ye,at=function(e,t){var r,i;if("string"===t&&Ie(r=e.toString)&&!Ae(i=Te(r,e)))return i;if(Ie(r=e.valueOf)&&!Ae(i=Te(r,e)))return i;if("string"!==t&&Ie(r=e.toString)&&!Ae(i=Te(r,e)))return i;throw new Se("Can't convert object to primitive value")},st=TypeError,ct=tt("toPrimitive"),lt=function(e,t){if(!it(e)||ot(e))return e;var r,i=nt(e,ct);if(i){if(void 0===t&&(t="default"),r=rt(i,e,t),!it(r)||ot(r))return r;throw new st("Can't convert object to primitive value")}return void 0===t&&(t="number"),at(e,t)},dt=lt,ut=ue,ht=function(e){var t=dt(e,"string");return ut(t)?t:t+""},pt=H,mt=r.document,ft=pt(mt)&&pt(mt.createElement),_t=function(e){return ft?mt.createElement(e):{}},gt=_t,Et=!n&&!o((function(){return 7!==Object.defineProperty(gt("div"),"a",{get:function(){return 7}}).a})),vt=n,yt=l,Tt=d,It=_,At=U,St=ht,Rt=He,bt=Et,wt=Object.getOwnPropertyDescriptor;i.f=vt?wt:function(e,t){if(e=At(e),t=St(t),bt)try{return wt(e,t)}catch(r){}if(Rt(e,t))return It(!yt(Tt.f,e,t),e[t])};var Ct={},Dt=n&&o((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Nt=H,kt=String,Ot=TypeError,Mt=function(e){if(Nt(e))return e;throw new Ot(kt(e)+" is not an object")},Lt=n,Pt=Et,xt=Dt,Ut=Mt,Vt=ht,Ft=TypeError,Bt=Object.defineProperty,Ht=Object.getOwnPropertyDescriptor,Wt="enumerable",jt="configurable",Gt="writable";Ct.f=Lt?xt?function(e,t,r){if(Ut(e),t=Vt(t),Ut(r),"function"==typeof e&&"prototype"===t&&"value"in r&&Gt in r&&!r[Gt]){var i=Ht(e,t);i&&i[Gt]&&(e[t]=r.value,r={configurable:jt in r?r[jt]:i[jt],enumerable:Wt in r?r[Wt]:i[Wt],writable:!1})}return Bt(e,t,r)}:Bt:function(e,t,r){if(Ut(e),t=Vt(t),Ut(r),Pt)try{return Bt(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Ft("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var zt=Ct,Kt=_,qt=n?function(e,t,r){return zt.f(e,t,Kt(1,r))}:function(e,t,r){return e[t]=r,e},Yt={exports:{}},Jt=n,Xt=He,$t=Function.prototype,Qt=Jt&&Object.getOwnPropertyDescriptor,Zt=Xt($t,"name"),er={EXISTS:Zt,PROPER:Zt&&"something"===function(){}.name,CONFIGURABLE:Zt&&(!Jt||Jt&&Qt($t,"name").configurable)},tr=F,rr=Me,ir=T(Function.toString);tr(rr.inspectSource)||(rr.inspectSource=function(e){return ir(e)});var or,nr,ar,sr=rr.inspectSource,cr=F,lr=r.WeakMap,dr=cr(lr)&&/native code/.test(String(lr)),ur=Ke,hr=Pe("keys"),pr=function(e){return hr[e]||(hr[e]=ur(e))},mr={},fr=dr,_r=r,gr=H,Er=qt,vr=He,yr=Me,Tr=pr,Ir=mr,Ar="Object already initialized",Sr=_r.TypeError,Rr=_r.WeakMap;if(fr||yr.state){var br=yr.state||(yr.state=new Rr);br.get=br.get,br.has=br.has,br.set=br.set,or=function(e,t){if(br.has(e))throw new Sr(Ar);return t.facade=e,br.set(e,t),t},nr=function(e){return br.get(e)||{}},ar=function(e){return br.has(e)}}else{var wr=Tr("state");Ir[wr]=!0,or=function(e,t){if(vr(e,wr))throw new Sr(Ar);return t.facade=e,Er(e,wr,t),t},nr=function(e){return vr(e,wr)?e[wr]:{}},ar=function(e){return vr(e,wr)}}var Cr={set:or,get:nr,has:ar,enforce:function(e){return ar(e)?nr(e):or(e,{})},getterFor:function(e){return function(t){var r;if(!gr(t)||(r=nr(t)).type!==e)throw new Sr("Incompatible receiver, "+e+" required");return r}}},Dr=T,Nr=o,kr=F,Or=He,Mr=n,Lr=er.CONFIGURABLE,Pr=sr,xr=Cr.enforce,Ur=Cr.get,Vr=String,Fr=Object.defineProperty,Br=Dr("".slice),Hr=Dr("".replace),Wr=Dr([].join),jr=Mr&&!Nr((function(){return 8!==Fr((function(){}),"length",{value:8}).length})),Gr=String(String).split("String"),zr=Yt.exports=function(e,t,r){"Symbol("===Br(Vr(t),0,7)&&(t="["+Hr(Vr(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!Or(e,"name")||Lr&&e.name!==t)&&(Mr?Fr(e,"name",{value:t,configurable:!0}):e.name=t),jr&&r&&Or(r,"arity")&&e.length!==r.arity&&Fr(e,"length",{value:r.arity});try{r&&Or(r,"constructor")&&r.constructor?Mr&&Fr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(o){}var i=xr(e);return Or(i,"source")||(i.source=Wr(Gr,"string"==typeof t?t:"")),e};Function.prototype.toString=zr((function(){return kr(this)&&Ur(this).source||Pr(this)}),"toString");var Kr=Yt.exports,qr=F,Yr=Ct,Jr=Kr,Xr=Ce,$r=function(e,t,r,i){i||(i={});var o=i.enumerable,n=void 0!==i.name?i.name:t;if(qr(r)&&Jr(r,n,i),i.global)o?e[t]=r:Xr(t,r);else{try{i.unsafe?e[t]&&(o=!0):delete e[t]}catch(a){}o?e[t]=r:Yr.f(e,t,{value:r,enumerable:!1,configurable:!i.nonConfigurable,writable:!i.nonWritable})}return e},Qr={},Zr=Math.ceil,ei=Math.floor,ti=Math.trunc||function(e){var t=+e;return(t>0?ei:Zr)(t)},ri=ti,ii=function(e){var t=+e;return t!=t||0===t?0:ri(t)},oi=ii,ni=Math.max,ai=Math.min,si=function(e,t){var r=oi(e);return r<0?ni(r+t,0):ai(r,t)},ci=ii,li=Math.min,di=function(e){var t=ci(e);return t>0?li(t,9007199254740991):0},ui=di,hi=function(e){return ui(e.length)},pi=U,mi=si,fi=hi,_i=function(e){return function(t,r,i){var o=pi(t),n=fi(o);if(0===n)return!e&&-1;var a,s=mi(i,n);if(e&&r!=r){for(;n>s;)if((a=o[s++])!=a)return!0}else for(;n>s;s++)if((e||s in o)&&o[s]===r)return e||s||0;return!e&&-1}},gi={includes:_i(!0),indexOf:_i(!1)},Ei=He,vi=U,yi=gi.indexOf,Ti=mr,Ii=T([].push),Ai=function(e,t){var r,i=vi(e),o=0,n=[];for(r in i)!Ei(Ti,r)&&Ei(i,r)&&Ii(n,r);for(;t.length>o;)Ei(i,r=t[o++])&&(~yi(n,r)||Ii(n,r));return n},Si=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ri=Ai,bi=Si.concat("length","prototype");Qr.f=Object.getOwnPropertyNames||function(e){return Ri(e,bi)};var wi={};wi.f=Object.getOwnPropertySymbols;var Ci=G,Di=Qr,Ni=wi,ki=Mt,Oi=T([].concat),Mi=Ci("Reflect","ownKeys")||function(e){var t=Di.f(ki(e)),r=Ni.f;return r?Oi(t,r(e)):t},Li=He,Pi=Mi,xi=i,Ui=Ct,Vi=function(e,t,r){for(var i=Pi(t),o=Ui.f,n=xi.f,a=0;a<i.length;a++){var s=i[a];Li(e,s)||r&&Li(r,s)||o(e,s,n(t,s))}},Fi=o,Bi=F,Hi=/#|\.prototype\./,Wi=function(e,t){var r=Gi[ji(e)];return r===Ki||r!==zi&&(Bi(t)?Fi(t):!!t)},ji=Wi.normalize=function(e){return String(e).replace(Hi,".").toLowerCase()},Gi=Wi.data={},zi=Wi.NATIVE="N",Ki=Wi.POLYFILL="P",qi=Wi,Yi=r,Ji=i.f,Xi=qt,$i=$r,Qi=Ce,Zi=Vi,eo=qi,to=function(e,t){var r,i,o,n,a,s=e.target,c=e.global,l=e.stat;if(r=c?Yi:l?Yi[s]||Qi(s,{}):Yi[s]&&Yi[s].prototype)for(i in t){if(n=t[i],o=e.dontCallGetSet?(a=Ji(r,i))&&a.value:r[i],!eo(c?i:s+(l?".":"#")+i,e.forced)&&void 0!==o){if(typeof n==typeof o)continue;Zi(n,o)}(e.sham||o&&o.sham)&&Xi(n,"sham",!0),$i(r,i,n,e)}},ro={};ro[tt("toStringTag")]="z";var io="[object z]"===String(ro),oo=F,no=R,ao=tt("toStringTag"),so=Object,co="Arguments"===no(function(){return arguments}()),lo=io?no:function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(r){}}(t=so(e),ao))?r:co?no(t):"Object"===(i=no(t))&&oo(t.callee)?"Arguments":i},uo=lo,ho=String,po=function(e){if("Symbol"===uo(e))throw new TypeError("Cannot convert a Symbol value to a string");return ho(e)},mo=Kr,fo=Ct,_o=function(e,t,r){return r.get&&mo(r.get,t,{getter:!0}),r.set&&mo(r.set,t,{setter:!0}),fo.f(e,t,r)},go=to,Eo=n,vo=T,yo=He,To=F,Io=z,Ao=po,So=_o,Ro=Vi,bo=r.Symbol,wo=bo&&bo.prototype;if(Eo&&To(bo)&&(!("description"in wo)||void 0!==bo().description)){var Co={},Do=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Ao(arguments[0]),t=Io(wo,this)?new bo(e):void 0===e?bo():bo(e);return""===e&&(Co[t]=!0),t};Ro(Do,bo),Do.prototype=wo,wo.constructor=Do;var No="Symbol(description detection)"===String(bo("description detection")),ko=vo(wo.valueOf),Oo=vo(wo.toString),Mo=/^Symbol\((.*)\)[^)]+$/,Lo=vo("".replace),Po=vo("".slice);So(wo,"description",{configurable:!0,get:function(){var e=ko(this);if(yo(Co,e))return"";var t=Oo(e),r=No?Po(t,7,-1):Lo(t,Mo,"$1");return""===r?void 0:r}}),go({global:!0,constructor:!0,forced:!0},{Symbol:Do})}var xo=r,Uo={},Vo=tt;Uo.f=Vo;var Fo=xo,Bo=He,Ho=Uo,Wo=Ct.f,jo=function(e){var t=Fo.Symbol||(Fo.Symbol={});Bo(t,e)||Wo(t,e,{value:Ho.f(e)})};jo("asyncIterator");var Go=R,zo=Array.isArray||function(e){return"Array"===Go(e)},Ko=TypeError,qo=R,Yo=T,Jo=function(e){if("Function"===qo(e))return Yo(e)},Xo=ge,$o=a,Qo=Jo(Jo.bind),Zo=function(e,t){return Xo(e),void 0===t?e:$o?Qo(e,t):function(){return e.apply(t,arguments)}},en=zo,tn=hi,rn=function(e){if(e>9007199254740991)throw Ko("Maximum allowed index exceeded");return e},on=Zo,nn=function(e,t,r,i,o,n,a,s){for(var c,l,d=o,u=0,h=!!a&&on(a,s);u<i;)u in r&&(c=h?h(r[u],u,t):r[u],n>0&&en(c)?(l=tn(c),d=nn(e,t,c,l,d,n-1)-1):(rn(d+1),e[d]=c),d++),u++;return d},an=nn,sn=T,cn=o,ln=F,dn=lo,un=sr,hn=function(){},pn=G("Reflect","construct"),mn=/^\s*(?:class|function)\b/,fn=sn(mn.exec),_n=!mn.test(hn),gn=function(e){if(!ln(e))return!1;try{return pn(hn,[],e),!0}catch(t){return!1}},En=function(e){if(!ln(e))return!1;switch(dn(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _n||!!fn(mn,un(e))}catch(t){return!0}};En.sham=!0;var vn=!pn||cn((function(){var e;return gn(gn.call)||!gn(Object)||!gn((function(){e=!0}))||e}))?En:gn,yn=zo,Tn=vn,In=H,An=tt("species"),Sn=Array,Rn=function(e){var t;return yn(e)&&(t=e.constructor,(Tn(t)&&(t===Sn||yn(t.prototype))||In(t)&&null===(t=t[An]))&&(t=void 0)),void 0===t?Sn:t},bn=function(e,t){return new(Rn(e))(0===t?0:t)},wn=an,Cn=Ve,Dn=hi,Nn=ii,kn=bn;to({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,t=Cn(this),r=Dn(t),i=kn(t,0);return i.length=wn(i,t,t,r,0,void 0===e?1:Nn(e)),i}});var On={},Mn=Ai,Ln=Si,Pn=Object.keys||function(e){return Mn(e,Ln)},xn=n,Un=Dt,Vn=Ct,Fn=Mt,Bn=U,Hn=Pn;On.f=xn&&!Un?Object.defineProperties:function(e,t){Fn(e);for(var r,i=Bn(t),o=Hn(t),n=o.length,a=0;n>a;)Vn.f(e,r=o[a++],i[r]);return e};var Wn,jn=G("document","documentElement"),Gn=Mt,zn=On,Kn=Si,qn=mr,Yn=jn,Jn=_t,Xn="prototype",$n="script",Qn=pr("IE_PROTO"),Zn=function(){},ea=function(e){return"<"+$n+">"+e+"</"+$n+">"},ta=function(e){e.write(ea("")),e.close();var t=e.parentWindow.Object;return e=null,t},ra=function(){try{Wn=new ActiveXObject("htmlfile")}catch(t){}ra="undefined"!=typeof document?document.domain&&Wn?ta(Wn):function(){var e,t=Jn("iframe"),r="java"+$n+":";return t.style.display="none",Yn.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write(ea("document.F=Object")),e.close(),e.F}():ta(Wn);for(var e=Kn.length;e--;)delete ra[Xn][Kn[e]];return ra()};qn[Qn]=!0;var ia=Object.create||function(e,t){var r;return null!==e?(Zn[Xn]=Gn(e),r=new Zn,Zn[Xn]=null,r[Qn]=e):r=ra(),void 0===t?r:zn.f(r,t)},oa=tt,na=ia,aa=Ct.f,sa=oa("unscopables"),ca=Array.prototype;void 0===ca[sa]&&aa(ca,sa,{configurable:!0,value:na(null)});var la=function(e){ca[sa][e]=!0},da=gi.includes,ua=la;to({target:"Array",proto:!0,forced:o((function(){return!Array(1).includes()}))},{includes:function(e){return da(this,e,arguments.length>1?arguments[1]:void 0)}}),ua("includes");var ha,pa,ma,fa={},_a=!o((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),ga=He,Ea=F,va=Ve,ya=_a,Ta=pr("IE_PROTO"),Ia=Object,Aa=Ia.prototype,Sa=ya?Ia.getPrototypeOf:function(e){var t=va(e);if(ga(t,Ta))return t[Ta];var r=t.constructor;return Ea(r)&&t instanceof r?r.prototype:t instanceof Ia?Aa:null},Ra=o,ba=F,wa=H,Ca=Sa,Da=$r,Na=tt("iterator"),ka=!1;[].keys&&("next"in(ma=[].keys())?(pa=Ca(Ca(ma)))!==Object.prototype&&(ha=pa):ka=!0);var Oa=!wa(ha)||Ra((function(){var e={};return ha[Na].call(e)!==e}));Oa&&(ha={}),ba(ha[Na])||Da(ha,Na,(function(){return this}));var Ma={IteratorPrototype:ha,BUGGY_SAFARI_ITERATORS:ka},La=Ct.f,Pa=He,xa=tt("toStringTag"),Ua=function(e,t,r){e&&!r&&(e=e.prototype),e&&!Pa(e,xa)&&La(e,xa,{configurable:!0,value:t})},Va=Ma.IteratorPrototype,Fa=ia,Ba=_,Ha=Ua,Wa=fa,ja=function(){return this},Ga=function(e,t,r,i){var o=t+" Iterator";return e.prototype=Fa(Va,{next:Ba(+!i,r)}),Ha(e,o,!1),Wa[o]=ja,e},za=T,Ka=ge,qa=H,Ya=function(e){return qa(e)||null===e},Ja=String,Xa=TypeError,$a=function(e,t,r){try{return za(Ka(Object.getOwnPropertyDescriptor(e,t)[r]))}catch(i){}},Qa=H,Za=L,es=function(e){if(Ya(e))return e;throw new Xa("Can't set "+Ja(e)+" as a prototype")},ts=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=$a(Object.prototype,"__proto__","set"))(r,[]),t=r instanceof Array}catch(i){}return function(r,i){return Za(r),es(i),Qa(r)?(t?e(r,i):r.__proto__=i,r):r}}():void 0),rs=to,is=l,os=F,ns=Ga,as=Sa,ss=ts,cs=Ua,ls=qt,ds=$r,us=fa,hs=er.PROPER,ps=er.CONFIGURABLE,ms=Ma.IteratorPrototype,fs=Ma.BUGGY_SAFARI_ITERATORS,_s=tt("iterator"),gs="keys",Es="values",vs="entries",ys=function(){return this},Ts=function(e,t,r,i,o,n,a){ns(r,t,i);var s,c,l,d=function(e){if(e===o&&f)return f;if(!fs&&e&&e in p)return p[e];switch(e){case gs:case Es:case vs:return function(){return new r(this,e)}}return function(){return new r(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[_s]||p["@@iterator"]||o&&p[o],f=!fs&&m||d(o),_="Array"===t&&p.entries||m;if(_&&(s=as(_.call(new e)))!==Object.prototype&&s.next&&(as(s)!==ms&&(ss?ss(s,ms):os(s[_s])||ds(s,_s,ys)),cs(s,u,!0)),hs&&o===Es&&m&&m.name!==Es&&(ps?ls(p,"name",Es):(h=!0,f=function(){return is(m,this)})),o)if(c={values:d(Es),keys:n?f:d(gs),entries:d(vs)},a)for(l in c)(fs||h||!(l in p))&&ds(p,l,c[l]);else rs({target:t,proto:!0,forced:fs||h},c);return p[_s]!==f&&ds(p,_s,f,{name:o}),us[t]=f,c},Is=function(e,t){return{value:e,done:t}},As=U,Ss=la,Rs=fa,bs=Cr,ws=Ct.f,Cs=Ts,Ds=Is,Ns=n,ks="Array Iterator",Os=bs.set,Ms=bs.getterFor(ks),Ls=Cs(Array,"Array",(function(e,t){Os(this,{type:ks,target:As(e),index:0,kind:t})}),(function(){var e=Ms(this),t=e.target,r=e.index++;if(!t||r>=t.length)return e.target=null,Ds(void 0,!0);switch(e.kind){case"keys":return Ds(r,!1);case"values":return Ds(t[r],!1)}return Ds([r,t[r]],!1)}),"values"),Ps=Rs.Arguments=Rs.Array;if(Ss("keys"),Ss("values"),Ss("entries"),Ns&&"values"!==Ps.name)try{ws(Ps,"name",{value:"values"})}catch(xG){}var xs=ge,Us=Ve,Vs=N,Fs=hi,Bs=TypeError,Hs="Reduce of empty array with no initial value",Ws=function(e){return function(t,r,i,o){var n=Us(t),a=Vs(n),s=Fs(n);if(xs(r),0===s&&i<2)throw new Bs(Hs);var c=e?s-1:0,l=e?-1:1;if(i<2)for(;;){if(c in a){o=a[c],c+=l;break}if(c+=l,e?c<0:s<=c)throw new Bs(Hs)}for(;e?c>=0:s>c;c+=l)c in a&&(o=r(o,a[c],c,n));return o}},js={left:Ws(!1),right:Ws(!0)},Gs=o,zs=function(e,t){var r=[][e];return!!r&&Gs((function(){r.call(null,t||function(){return 1},1)}))},Ks=r,qs=Y,Ys=R,Js=function(e){return qs.slice(0,e.length)===e},Xs=Js("Bun/")?"BUN":Js("Cloudflare-Workers")?"CLOUDFLARE":Js("Deno/")?"DENO":Js("Node.js/")?"NODE":Ks.Bun&&"string"==typeof Bun.version?"BUN":Ks.Deno&&"object"==typeof Deno.version?"DENO":"process"===Ys(Ks.process)?"NODE":Ks.window&&Ks.document?"BROWSER":"REST",$s="NODE"===Xs,Qs=js.left;to({target:"Array",proto:!0,forced:!$s&&te>79&&te<83||!zs("reduce")},{reduce:function(e){var t=arguments.length;return Qs(this,e,t,t>1?arguments[1]:void 0)}});var Zs=js.right;to({target:"Array",proto:!0,forced:!$s&&te>79&&te<83||!zs("reduceRight")},{reduceRight:function(e){return Zs(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var ec=to,tc=zo,rc=T([].reverse),ic=[1,2];ec({target:"Array",proto:!0,forced:String(ic)===String(ic.reverse())},{reverse:function(){return tc(this)&&(this.length=this.length),rc(this)}});var oc=pe,nc=TypeError,ac=T([].slice),sc=ac,cc=Math.floor,lc=function(e,t){var r=e.length;if(r<8)for(var i,o,n=1;n<r;){for(o=n,i=e[n];o&&t(e[o-1],i)>0;)e[o]=e[--o];o!==n++&&(e[o]=i)}else for(var a=cc(r/2),s=lc(sc(e,0,a),t),c=lc(sc(e,a),t),l=s.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(s[u],c[h])<=0?s[u++]:c[h++]:u<l?s[u++]:c[h++];return e},dc=lc,uc=Y.match(/firefox\/(\d+)/i),hc=!!uc&&+uc[1],pc=/MSIE|Trident/.test(Y),mc=Y.match(/AppleWebKit\/(\d+)\./),fc=!!mc&&+mc[1],_c=to,gc=T,Ec=ge,vc=Ve,yc=hi,Tc=function(e,t){if(!delete e[t])throw new nc("Cannot delete property "+oc(t)+" of "+oc(e))},Ic=po,Ac=o,Sc=dc,Rc=zs,bc=hc,wc=pc,Cc=te,Dc=fc,Nc=[],kc=gc(Nc.sort),Oc=gc(Nc.push),Mc=Ac((function(){Nc.sort(void 0)})),Lc=Ac((function(){Nc.sort(null)})),Pc=Rc("sort"),xc=!Ac((function(){if(Cc)return Cc<70;if(!(bc&&bc>3)){if(wc)return!0;if(Dc)return Dc<603;var e,t,r,i,o="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:r=3;break;case 68:case 71:r=4;break;default:r=2}for(i=0;i<47;i++)Nc.push({k:t+i,v:r})}for(Nc.sort((function(e,t){return t.v-e.v})),i=0;i<Nc.length;i++)t=Nc[i].k.charAt(0),o.charAt(o.length-1)!==t&&(o+=t);return"DGBEFHACIJK"!==o}}));_c({target:"Array",proto:!0,forced:Mc||!Lc||!Pc||!xc},{sort:function(e){void 0!==e&&Ec(e);var t=vc(this);if(xc)return void 0===e?kc(t):kc(t,e);var r,i,o=[],n=yc(t);for(i=0;i<n;i++)i in t&&Oc(o,t[i]);for(Sc(o,function(e){return function(t,r){return void 0===r?-1:void 0===t?1:void 0!==e?+e(t,r)||0:Ic(t)>Ic(r)?1:-1}}(e)),r=yc(o),i=0;i<r;)t[i]=o[i++];for(;i<n;)Tc(t,i++);return t}}),la("flat");var Uc="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Vc=$r,Fc=function(e,t,r){for(var i in t)Vc(e,i,t[i],r);return e},Bc=z,Hc=TypeError,Wc=function(e,t){if(Bc(t,e))return e;throw new Hc("Incorrect invocation")},jc=ii,Gc=di,zc=RangeError,Kc=function(e){if(void 0===e)return 0;var t=jc(e),r=Gc(t);if(t!==r)throw new zc("Wrong length or index");return r},qc=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},Yc=4503599627370496,Jc=qc,Xc=function(e){return e+Yc-Yc},$c=Math.abs,Qc=function(e,t,r,i){var o=+e,n=$c(o),a=Jc(o);if(n<i)return a*Xc(n/i/t)*i*t;var s=(1+t/2220446049250313e-31)*n,c=s-(s-n);return c>r||c!=c?Infinity*a:a*c},Zc=Math.fround||function(e){return Qc(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},el=Array,tl=Math.abs,rl=Math.pow,il=Math.floor,ol=Math.log,nl=Math.LN2,al={pack:function(e,t,r){var i,o,n,a=el(r),s=8*r-t-1,c=(1<<s)-1,l=c>>1,d=23===t?rl(2,-24)-rl(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tl(e))!=e||Infinity===e?(o=e!=e?1:0,i=c):(i=il(ol(e)/nl),e*(n=rl(2,-i))<1&&(i--,n*=2),(e+=i+l>=1?d/n:d*rl(2,1-l))*n>=2&&(i++,n/=2),i+l>=c?(o=0,i=c):i+l>=1?(o=(e*n-1)*rl(2,t),i+=l):(o=e*rl(2,l-1)*rl(2,t),i=0));t>=8;)a[h++]=255&o,o/=256,t-=8;for(i=i<<t|o,s+=t;s>0;)a[h++]=255&i,i/=256,s-=8;return a[h-1]|=128*u,a},unpack:function(e,t){var r,i=e.length,o=8*i-t-1,n=(1<<o)-1,a=n>>1,s=o-7,c=i-1,l=e[c--],d=127&l;for(l>>=7;s>0;)d=256*d+e[c--],s-=8;for(r=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)r=256*r+e[c--],s-=8;if(0===d)d=1-a;else{if(d===n)return r?NaN:l?-Infinity:Infinity;r+=rl(2,t),d-=a}return(l?-1:1)*r*rl(2,d-t)}},sl=Ve,cl=si,ll=hi,dl=function(e){for(var t=sl(this),r=ll(t),i=arguments.length,o=cl(i>1?arguments[1]:void 0,r),n=i>2?arguments[2]:void 0,a=void 0===n?r:cl(n,r);a>o;)t[o++]=e;return t},ul=F,hl=H,pl=ts,ml=function(e,t,r){var i,o;return pl&&ul(i=t.constructor)&&i!==r&&hl(o=i.prototype)&&o!==r.prototype&&pl(e,o),e},fl=r,_l=T,gl=n,El=Uc,vl=qt,yl=_o,Tl=Fc,Il=o,Al=Wc,Sl=ii,Rl=di,bl=Kc,wl=Zc,Cl=al,Dl=Sa,Nl=ts,kl=dl,Ol=ac,Ml=ml,Ll=Vi,Pl=Ua,xl=Cr,Ul=er.PROPER,Vl=er.CONFIGURABLE,Fl="ArrayBuffer",Bl="DataView",Hl="prototype",Wl="Wrong index",jl=xl.getterFor(Fl),Gl=xl.getterFor(Bl),zl=xl.set,Kl=fl[Fl],ql=Kl,Yl=ql&&ql[Hl],Jl=fl[Bl],Xl=Jl&&Jl[Hl],$l=Object.prototype,Ql=fl.Array,Zl=fl.RangeError,ed=_l(kl),td=_l([].reverse),rd=Cl.pack,id=Cl.unpack,od=function(e){return[255&e]},nd=function(e){return[255&e,e>>8&255]},ad=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},sd=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},cd=function(e){return rd(wl(e),23,4)},ld=function(e){return rd(e,52,8)},dd=function(e,t,r){yl(e[Hl],t,{configurable:!0,get:function(){return r(this)[t]}})},ud=function(e,t,r,i){var o=Gl(e),n=bl(r),a=!!i;if(n+t>o.byteLength)throw new Zl(Wl);var s=o.bytes,c=n+o.byteOffset,l=Ol(s,c,c+t);return a?l:td(l)},hd=function(e,t,r,i,o,n){var a=Gl(e),s=bl(r),c=i(+o),l=!!n;if(s+t>a.byteLength)throw new Zl(Wl);for(var d=a.bytes,u=s+a.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(El){var pd=Ul&&Kl.name!==Fl;Il((function(){Kl(1)}))&&Il((function(){new Kl(-1)}))&&!Il((function(){return new Kl,new Kl(1.5),new Kl(NaN),1!==Kl.length||pd&&!Vl}))?pd&&Vl&&vl(Kl,"name",Fl):((ql=function(e){return Al(this,Yl),Ml(new Kl(bl(e)),this,ql)})[Hl]=Yl,Yl.constructor=ql,Ll(ql,Kl)),Nl&&Dl(Xl)!==$l&&Nl(Xl,$l);var md=new Jl(new ql(2)),fd=_l(Xl.setInt8);md.setInt8(0,2147483648),md.setInt8(1,2147483649),!md.getInt8(0)&&md.getInt8(1)||Tl(Xl,{setInt8:function(e,t){fd(this,e,t<<24>>24)},setUint8:function(e,t){fd(this,e,t<<24>>24)}},{unsafe:!0})}else Yl=(ql=function(e){Al(this,Yl);var t=bl(e);zl(this,{type:Fl,bytes:ed(Ql(t),0),byteLength:t}),gl||(this.byteLength=t,this.detached=!1)})[Hl],Xl=(Jl=function(e,t,r){Al(this,Xl),Al(e,Yl);var i=jl(e),o=i.byteLength,n=Sl(t);if(n<0||n>o)throw new Zl("Wrong offset");if(n+(r=void 0===r?o-n:Rl(r))>o)throw new Zl("Wrong length");zl(this,{type:Bl,buffer:e,byteLength:r,byteOffset:n,bytes:i.bytes}),gl||(this.buffer=e,this.byteLength=r,this.byteOffset=n)})[Hl],gl&&(dd(ql,"byteLength",jl),dd(Jl,"buffer",Gl),dd(Jl,"byteLength",Gl),dd(Jl,"byteOffset",Gl)),Tl(Xl,{getInt8:function(e){return ud(this,1,e)[0]<<24>>24},getUint8:function(e){return ud(this,1,e)[0]},getInt16:function(e){var t=ud(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ud(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return sd(ud(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return sd(ud(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return id(ud(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return id(ud(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){hd(this,1,e,od,t)},setUint8:function(e,t){hd(this,1,e,od,t)},setInt16:function(e,t){hd(this,2,e,nd,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){hd(this,2,e,nd,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){hd(this,4,e,ad,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){hd(this,4,e,ad,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){hd(this,4,e,cd,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){hd(this,8,e,ld,t,arguments.length>2&&arguments[2])}});Pl(ql,Fl),Pl(Jl,Bl);var _d={ArrayBuffer:ql,DataView:Jl},gd=G,Ed=_o,vd=n,yd=tt("species"),Td=function(e){var t=gd(e);vd&&t&&!t[yd]&&Ed(t,yd,{configurable:!0,get:function(){return this}})},Id=Td,Ad="ArrayBuffer",Sd=_d[Ad];to({global:!0,constructor:!0,forced:r[Ad]!==Sd},{ArrayBuffer:Sd}),Id(Ad);var Rd=to,bd=Jo,wd=o,Cd=Mt,Dd=si,Nd=di,kd=_d.ArrayBuffer,Od=_d.DataView,Md=Od.prototype,Ld=bd(kd.prototype.slice),Pd=bd(Md.getUint8),xd=bd(Md.setUint8);Rd({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:wd((function(){return!new kd(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Ld&&void 0===t)return Ld(Cd(this),e);for(var r=Cd(this).byteLength,i=Dd(e,r),o=Dd(void 0===t?r:t,r),n=new kd(Nd(o-i)),a=new Od(this),s=new Od(n),c=0;i<o;)xd(s,c++,Pd(a,i++));return n}});var Ud,Vd,Fd,Bd,Hd=vn,Wd=pe,jd=TypeError,Gd=function(e){if(Hd(e))return e;throw new jd(Wd(e)+" is not a constructor")},zd=Mt,Kd=Gd,qd=k,Yd=tt("species"),Jd=function(e,t){var r,i=zd(e).constructor;return void 0===i||qd(r=zd(i)[Yd])?t:Kd(r)},Xd=a,$d=Function.prototype,Qd=$d.apply,Zd=$d.call,eu="object"==typeof Reflect&&Reflect.apply||(Xd?Zd.bind(Qd):function(){return Zd.apply(Qd,arguments)}),tu=TypeError,ru=function(e,t){if(e<t)throw new tu("Not enough arguments");return e},iu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ou=r,nu=eu,au=Zo,su=F,cu=He,lu=o,du=jn,uu=ac,hu=_t,pu=ru,mu=iu,fu=$s,_u=ou.setImmediate,gu=ou.clearImmediate,Eu=ou.process,vu=ou.Dispatch,yu=ou.Function,Tu=ou.MessageChannel,Iu=ou.String,Au=0,Su={},Ru="onreadystatechange";lu((function(){Ud=ou.location}));var bu=function(e){if(cu(Su,e)){var t=Su[e];delete Su[e],t()}},wu=function(e){return function(){bu(e)}},Cu=function(e){bu(e.data)},Du=function(e){ou.postMessage(Iu(e),Ud.protocol+"//"+Ud.host)};_u&&gu||(_u=function(e){pu(arguments.length,1);var t=su(e)?e:yu(e),r=uu(arguments,1);return Su[++Au]=function(){nu(t,void 0,r)},Vd(Au),Au},gu=function(e){delete Su[e]},fu?Vd=function(e){Eu.nextTick(wu(e))}:vu&&vu.now?Vd=function(e){vu.now(wu(e))}:Tu&&!mu?(Bd=(Fd=new Tu).port2,Fd.port1.onmessage=Cu,Vd=au(Bd.postMessage,Bd)):ou.addEventListener&&su(ou.postMessage)&&!ou.importScripts&&Ud&&"file:"!==Ud.protocol&&!lu(Du)?(Vd=Du,ou.addEventListener("message",Cu,!1)):Vd=Ru in hu("script")?function(e){du.appendChild(hu("script"))[Ru]=function(){du.removeChild(this),bu(e)}}:function(e){setTimeout(wu(e),0)});var Nu={set:_u,clear:gu},ku=r,Ou=n,Mu=Object.getOwnPropertyDescriptor,Lu=function(e){if(!Ou)return ku[e];var t=Mu(ku,e);return t&&t.value},Pu=function(){this.head=null,this.tail=null};Pu.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.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 xu,Uu,Vu,Fu,Bu,Hu=Pu,Wu=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,ju=/web0s(?!.*chrome)/i.test(Y),Gu=r,zu=Lu,Ku=Zo,qu=Nu.set,Yu=Hu,Ju=iu,Xu=Wu,$u=ju,Qu=$s,Zu=Gu.MutationObserver||Gu.WebKitMutationObserver,eh=Gu.document,th=Gu.process,rh=Gu.Promise,ih=zu("queueMicrotask");if(!ih){var oh=new Yu,nh=function(){var e,t;for(Qu&&(e=th.domain)&&e.exit();t=oh.get();)try{t()}catch(xG){throw oh.head&&xu(),xG}e&&e.enter()};Ju||Qu||$u||!Zu||!eh?!Xu&&rh&&rh.resolve?((Fu=rh.resolve(void 0)).constructor=rh,Bu=Ku(Fu.then,Fu),xu=function(){Bu(nh)}):Qu?xu=function(){th.nextTick(nh)}:(qu=Ku(qu,Gu),xu=function(){qu(nh)}):(Uu=!0,Vu=eh.createTextNode(""),new Zu(nh).observe(Vu,{characterData:!0}),xu=function(){Vu.data=Uu=!Uu}),ih=function(e){oh.head||xu(),oh.add(e)}}var ah=ih,sh=function(e){try{return{error:!1,value:e()}}catch(xG){return{error:!0,value:xG}}},ch=r.Promise,lh=r,dh=ch,uh=F,hh=qi,ph=sr,mh=tt,fh=Xs,_h=te;dh&&dh.prototype;var gh=mh("species"),Eh=!1,vh=uh(lh.PromiseRejectionEvent),yh=hh("Promise",(function(){var e=ph(dh),t=e!==String(dh);if(!t&&66===_h)return!0;if(!_h||_h<51||!/native code/.test(e)){var r=new dh((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((r.constructor={})[gh]=i,!(Eh=r.then((function(){}))instanceof i))return!0}return!(t||"BROWSER"!==fh&&"DENO"!==fh||vh)})),Th={CONSTRUCTOR:yh,REJECTION_EVENT:vh,SUBCLASSING:Eh},Ih={},Ah=ge,Sh=TypeError,Rh=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw new Sh("Bad Promise constructor");t=e,r=i})),this.resolve=Ah(t),this.reject=Ah(r)};Ih.f=function(e){return new Rh(e)};var bh,wh,Ch,Dh=to,Nh=$s,kh=r,Oh=l,Mh=$r,Lh=ts,Ph=Ua,xh=Td,Uh=ge,Vh=F,Fh=H,Bh=Wc,Hh=Jd,Wh=Nu.set,jh=ah,Gh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(xG){}},zh=sh,Kh=Hu,qh=Cr,Yh=ch,Jh=Ih,Xh="Promise",$h=Th.CONSTRUCTOR,Qh=Th.REJECTION_EVENT,Zh=Th.SUBCLASSING,ep=qh.getterFor(Xh),tp=qh.set,rp=Yh&&Yh.prototype,ip=Yh,op=rp,np=kh.TypeError,ap=kh.document,sp=kh.process,cp=Jh.f,lp=cp,dp=!!(ap&&ap.createEvent&&kh.dispatchEvent),up="unhandledrejection",hp=function(e){var t;return!(!Fh(e)||!Vh(t=e.then))&&t},pp=function(e,t){var r,i,o,n=t.value,a=1===t.state,s=a?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&Ep(t),t.rejection=1),!0===s?r=n:(d&&d.enter(),r=s(n),d&&(d.exit(),o=!0)),r===e.promise?l(new np("Promise-chain cycle")):(i=hp(r))?Oh(i,r,c,l):c(r)):l(n)}catch(xG){d&&!o&&d.exit(),l(xG)}},mp=function(e,t){e.notified||(e.notified=!0,jh((function(){for(var r,i=e.reactions;r=i.get();)pp(r,e);e.notified=!1,t&&!e.rejection&&_p(e)})))},fp=function(e,t,r){var i,o;dp?((i=ap.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),kh.dispatchEvent(i)):i={promise:t,reason:r},!Qh&&(o=kh["on"+e])?o(i):e===up&&Gh("Unhandled promise rejection",r)},_p=function(e){Oh(Wh,kh,(function(){var t,r=e.facade,i=e.value;if(gp(e)&&(t=zh((function(){Nh?sp.emit("unhandledRejection",i,r):fp(up,r,i)})),e.rejection=Nh||gp(e)?2:1,t.error))throw t.value}))},gp=function(e){return 1!==e.rejection&&!e.parent},Ep=function(e){Oh(Wh,kh,(function(){var t=e.facade;Nh?sp.emit("rejectionHandled",t):fp("rejectionhandled",t,e.value)}))},vp=function(e,t,r){return function(i){e(t,i,r)}},yp=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,mp(e,!0))},Tp=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw new np("Promise can't be resolved itself");var i=hp(t);i?jh((function(){var r={done:!1};try{Oh(i,t,vp(Tp,r,e),vp(yp,r,e))}catch(xG){yp(r,xG,e)}})):(e.value=t,e.state=1,mp(e,!1))}catch(xG){yp({done:!1},xG,e)}}};if($h&&(op=(ip=function(e){Bh(this,op),Uh(e),Oh(bh,this);var t=ep(this);try{e(vp(Tp,t),vp(yp,t))}catch(xG){yp(t,xG)}}).prototype,(bh=function(e){tp(this,{type:Xh,done:!1,notified:!1,parent:!1,reactions:new Kh,rejection:!1,state:0,value:null})}).prototype=Mh(op,"then",(function(e,t){var r=ep(this),i=cp(Hh(this,ip));return r.parent=!0,i.ok=!Vh(e)||e,i.fail=Vh(t)&&t,i.domain=Nh?sp.domain:void 0,0===r.state?r.reactions.add(i):jh((function(){pp(i,r)})),i.promise})),wh=function(){var e=new bh,t=ep(e);this.promise=e,this.resolve=vp(Tp,t),this.reject=vp(yp,t)},Jh.f=cp=function(e){return e===ip||undefined===e?new wh(e):lp(e)},Vh(Yh)&&rp!==Object.prototype)){Ch=rp.then,Zh||Mh(rp,"then",(function(e,t){var r=this;return new ip((function(e,t){Oh(Ch,r,e,t)})).then(e,t)}),{unsafe:!0});try{delete rp.constructor}catch(xG){}Lh&&Lh(rp,op)}Dh({global:!0,constructor:!0,wrap:!0,forced:$h},{Promise:ip}),Ph(ip,Xh,!1),xh(Xh);var Ip=fa,Ap=tt("iterator"),Sp=Array.prototype,Rp=function(e){return void 0!==e&&(Ip.Array===e||Sp[Ap]===e)},bp=lo,wp=ye,Cp=k,Dp=fa,Np=tt("iterator"),kp=function(e){if(!Cp(e))return wp(e,Np)||wp(e,"@@iterator")||Dp[bp(e)]},Op=l,Mp=ge,Lp=Mt,Pp=pe,xp=kp,Up=TypeError,Vp=function(e,t){var r=arguments.length<2?xp(e):t;if(Mp(r))return Lp(Op(r,e));throw new Up(Pp(e)+" is not iterable")},Fp=l,Bp=Mt,Hp=ye,Wp=function(e,t,r){var i,o;Bp(e);try{if(!(i=Hp(e,"return"))){if("throw"===t)throw r;return r}i=Fp(i,e)}catch(xG){o=!0,i=xG}if("throw"===t)throw r;if(o)throw i;return Bp(i),r},jp=Zo,Gp=l,zp=Mt,Kp=pe,qp=Rp,Yp=hi,Jp=z,Xp=Vp,$p=kp,Qp=Wp,Zp=TypeError,em=function(e,t){this.stopped=e,this.result=t},tm=em.prototype,rm=function(e,t,r){var i,o,n,a,s,c,l,d=r&&r.that,u=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_RECORD),p=!(!r||!r.IS_ITERATOR),m=!(!r||!r.INTERRUPTED),f=jp(t,d),_=function(e){return i&&Qp(i,"normal",e),new em(!0,e)},g=function(e){return u?(zp(e),m?f(e[0],e[1],_):f(e[0],e[1])):m?f(e,_):f(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(o=$p(e)))throw new Zp(Kp(e)+" is not iterable");if(qp(o)){for(n=0,a=Yp(e);a>n;n++)if((s=g(e[n]))&&Jp(tm,s))return s;return new em(!1)}i=Xp(e,o)}for(c=h?e.next:i.next;!(l=Gp(c,i)).done;){try{s=g(l.value)}catch(xG){Qp(i,"throw",xG)}if("object"==typeof s&&s&&Jp(tm,s))return s}return new em(!1)},im=tt("iterator"),om=!1;try{var nm=0,am={next:function(){return{done:!!nm++}},return:function(){om=!0}};am[im]=function(){return this},Array.from(am,(function(){throw 2}))}catch(xG){}var sm=function(e,t){try{if(!t&&!om)return!1}catch(xG){return!1}var r=!1;try{var i={};i[im]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(xG){}return r},cm=ch,lm=Th.CONSTRUCTOR||!sm((function(e){cm.all(e).then(void 0,(function(){}))})),dm=l,um=ge,hm=Ih,pm=sh,mm=rm;to({target:"Promise",stat:!0,forced:lm},{all:function(e){var t=this,r=hm.f(t),i=r.resolve,o=r.reject,n=pm((function(){var r=um(t.resolve),n=[],a=0,s=1;mm(e,(function(e){var c=a++,l=!1;s++,dm(r,t,e).then((function(e){l||(l=!0,n[c]=e,--s||i(n))}),o)})),--s||i(n)}));return n.error&&o(n.value),r.promise}});var fm=to,_m=Th.CONSTRUCTOR,gm=ch,Em=G,vm=F,ym=$r,Tm=gm&&gm.prototype;if(fm({target:"Promise",proto:!0,forced:_m,real:!0},{catch:function(e){return this.then(void 0,e)}}),vm(gm)){var Im=Em("Promise").prototype.catch;Tm.catch!==Im&&ym(Tm,"catch",Im,{unsafe:!0})}var Am=l,Sm=ge,Rm=Ih,bm=sh,wm=rm;to({target:"Promise",stat:!0,forced:lm},{race:function(e){var t=this,r=Rm.f(t),i=r.reject,o=bm((function(){var o=Sm(t.resolve);wm(e,(function(e){Am(o,t,e).then(r.resolve,i)}))}));return o.error&&i(o.value),r.promise}});var Cm=Ih;to({target:"Promise",stat:!0,forced:Th.CONSTRUCTOR},{reject:function(e){var t=Cm.f(this);return(0,t.reject)(e),t.promise}});var Dm=Mt,Nm=H,km=Ih,Om=function(e,t){if(Dm(e),Nm(t)&&t.constructor===e)return t;var r=km.f(e);return(0,r.resolve)(t),r.promise},Mm=to,Lm=Th.CONSTRUCTOR,Pm=Om;G("Promise"),Mm({target:"Promise",stat:!0,forced:Lm},{resolve:function(e){return Pm(this,e)}});var xm=to,Um=ch,Vm=o,Fm=G,Bm=F,Hm=Jd,Wm=Om,jm=$r,Gm=Um&&Um.prototype;if(xm({target:"Promise",proto:!0,real:!0,forced:!!Um&&Vm((function(){Gm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Hm(this,Fm("Promise")),r=Bm(e);return this.then(r?function(r){return Wm(t,e()).then((function(){return r}))}:e,r?function(r){return Wm(t,e()).then((function(){throw r}))}:e)}}),Bm(Um)){var zm=Fm("Promise").prototype.finally;Gm.finally!==zm&&jm(Gm,"finally",zm,{unsafe:!0})}var Km=H,qm=R,Ym=tt("match"),Jm=function(e){var t;return Km(e)&&(void 0!==(t=e[Ym])?!!t:"RegExp"===qm(e))},Xm=Mt,$m=function(){var e=Xm(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},Qm=l,Zm=He,ef=z,tf=$m,rf=RegExp.prototype,of=function(e){var t=e.flags;return void 0!==t||"flags"in rf||Zm(e,"flags")||!ef(rf,e)?t:Qm(tf,e)},nf=o,af=r.RegExp,sf=nf((function(){var e=af("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),cf=sf||nf((function(){return!af("a","y").sticky})),lf={BROKEN_CARET:sf||nf((function(){var e=af("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),MISSED_STICKY:cf,UNSUPPORTED_Y:sf},df=Ct.f,uf=o,hf=r.RegExp,pf=uf((function(){var e=hf(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),mf=o,ff=r.RegExp,_f=mf((function(){var e=ff("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),gf=n,Ef=r,vf=T,yf=qi,Tf=ml,If=qt,Af=ia,Sf=Qr.f,Rf=z,bf=Jm,wf=po,Cf=of,Df=lf,Nf=function(e,t,r){r in e||df(e,r,{configurable:!0,get:function(){return t[r]},set:function(e){t[r]=e}})},kf=$r,Of=o,Mf=He,Lf=Cr.enforce,Pf=Td,xf=pf,Uf=_f,Vf=tt("match"),Ff=Ef.RegExp,Bf=Ff.prototype,Hf=Ef.SyntaxError,Wf=vf(Bf.exec),jf=vf("".charAt),Gf=vf("".replace),zf=vf("".indexOf),Kf=vf("".slice),qf=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Yf=/a/g,Jf=/a/g,Xf=new Ff(Yf)!==Yf,$f=Df.MISSED_STICKY,Qf=Df.UNSUPPORTED_Y,Zf=gf&&(!Xf||$f||xf||Uf||Of((function(){return Jf[Vf]=!1,Ff(Yf)!==Yf||Ff(Jf)===Jf||"/a/i"!==String(Ff(Yf,"i"))})));if(yf("RegExp",Zf)){for(var e_=function(e,t){var r,i,o,n,a,s,c=Rf(Bf,this),l=bf(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===e_)return e;if((l||Rf(Bf,e))&&(e=e.source,d&&(t=Cf(h))),e=void 0===e?"":wf(e),t=void 0===t?"":wf(t),h=e,xf&&"dotAll"in Yf&&(i=!!t&&zf(t,"s")>-1)&&(t=Gf(t,/s/g,"")),r=t,$f&&"sticky"in Yf&&(o=!!t&&zf(t,"y")>-1)&&Qf&&(t=Gf(t,/y/g,"")),Uf&&(n=function(e){for(var t,r=e.length,i=0,o="",n=[],a=Af(null),s=!1,c=!1,l=0,d="";i<=r;i++){if("\\"===(t=jf(e,i)))t+=jf(e,++i);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:if(o+=t,"?:"===Kf(e,i+1,i+3))continue;Wf(qf,Kf(e,i+1))&&(i+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||Mf(a,d))throw new Hf("Invalid capture group name");a[d]=!0,n[n.length]=[d,l],c=!1,d="";continue}c?d+=t:o+=t}return[o,n]}(e),e=n[0],u=n[1]),a=Tf(Ff(e,t),c?this:Bf,e_),(i||o||u.length)&&(s=Lf(a),i&&(s.dotAll=!0,s.raw=e_(function(e){for(var t,r=e.length,i=0,o="",n=!1;i<=r;i++)"\\"!==(t=jf(e,i))?n||"."!==t?("["===t?n=!0:"]"===t&&(n=!1),o+=t):o+="[\\s\\S]":o+=t+jf(e,++i);return o}(e),r)),o&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{If(a,"source",""===h?"(?:)":h)}catch(xG){}return a},t_=Sf(Ff),r_=0;t_.length>r_;)Nf(e_,Ff,t_[r_++]);Bf.constructor=e_,e_.prototype=Bf,kf(Ef,"RegExp",e_,{constructor:!0})}Pf("RegExp");var i_=l,o_=T,n_=po,a_=$m,s_=lf,c_=ia,l_=Cr.get,d_=pf,u_=_f,h_=Pe("native-string-replace",String.prototype.replace),p_=RegExp.prototype.exec,m_=p_,f_=o_("".charAt),__=o_("".indexOf),g_=o_("".replace),E_=o_("".slice),v_=function(){var e=/a/,t=/b*/g;return i_(p_,e,"a"),i_(p_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),y_=s_.BROKEN_CARET,T_=void 0!==/()??/.exec("")[1];(v_||T_||y_||d_||u_)&&(m_=function(e){var t,r,i,o,n,a,s,c=this,l=l_(c),d=n_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=i_(m_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=y_&&c.sticky,m=i_(a_,c),f=c.source,_=0,g=d;if(p&&(m=g_(m,"y",""),-1===__(m,"g")&&(m+="g"),g=E_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==f_(d,c.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),r=new RegExp("^(?:"+f+")",m)),T_&&(r=new RegExp("^"+f+"$(?!\\s)",m)),v_&&(i=c.lastIndex),o=i_(p_,p?r:c,g),p?o?(o.input=E_(o.input,_),o[0]=E_(o[0],_),o.index=c.lastIndex,c.lastIndex+=o[0].length):c.lastIndex=0:v_&&o&&(c.lastIndex=c.global?o.index+o[0].length:i),T_&&o&&o.length>1&&i_(h_,o[0],r,(function(){for(n=1;n<arguments.length-2;n++)void 0===arguments[n]&&(o[n]=void 0)})),o&&h)for(o.groups=a=c_(null),n=0;n<h.length;n++)a[(s=h[n])[0]]=o[s[1]];return o});var I_=m_;to({target:"RegExp",proto:!0,forced:/./.exec!==I_},{exec:I_});var A_=n,S_=_o,R_=$m,b_=o,w_=r.RegExp,C_=w_.prototype,D_=A_&&b_((function(){var e=!0;try{w_(".","d")}catch(xG){e=!1}var t={},r="",i=e?"dgimsy":"gimsy",o=function(e,i){Object.defineProperty(t,e,{get:function(){return r+=i,!0}})},n={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var a in e&&(n.hasIndices="d"),n)o(a,n[a]);return Object.getOwnPropertyDescriptor(C_,"flags").get.call(t)!==i||r!==i}));D_&&S_(C_,"flags",{configurable:!0,get:R_});var N_=ii,k_=po,O_=L,M_=RangeError,L_=T,P_=di,x_=po,U_=function(e){var t=k_(O_(this)),r="",i=N_(e);if(i<0||Infinity===i)throw new M_("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(r+=t);return r},V_=L,F_=L_(U_),B_=L_("".slice),H_=Math.ceil,W_=function(e){return function(t,r,i){var o,n,a=x_(V_(t)),s=P_(r),c=a.length,l=void 0===i?" ":x_(i);return s<=c||""===l?a:((n=F_(l,H_((o=s-c)/l.length))).length>o&&(n=B_(n,0,o)),e?a+n:n+a)}},j_={start:W_(!1),end:W_(!0)},G_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),z_=j_.start;to({target:"String",proto:!0,forced:G_},{padStart:function(e){return z_(this,e,arguments.length>1?arguments[1]:void 0)}});var K_=l,q_=$r,Y_=I_,J_=o,X_=tt,$_=qt,Q_=X_("species"),Z_=RegExp.prototype,eg=T,tg=ii,rg=po,ig=L,og=eg("".charAt),ng=eg("".charCodeAt),ag=eg("".slice),sg=function(e){return function(t,r){var i,o,n=rg(ig(t)),a=tg(r),s=n.length;return a<0||a>=s?e?"":void 0:(i=ng(n,a))<55296||i>56319||a+1===s||(o=ng(n,a+1))<56320||o>57343?e?og(n,a):i:e?ag(n,a,a+2):o-56320+(i-55296<<10)+65536}},cg={codeAt:sg(!1),charAt:sg(!0)},lg=cg.charAt,dg=T,ug=Ve,hg=Math.floor,pg=dg("".charAt),mg=dg("".replace),fg=dg("".slice),_g=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,gg=/\$([$&'`]|\d{1,2})/g,Eg=function(e,t,r,i,o,n){var a=r+e.length,s=i.length,c=gg;return void 0!==o&&(o=ug(o),c=_g),mg(n,c,(function(n,c){var l;switch(pg(c,0)){case"$":return"$";case"&":return e;case"`":return fg(t,0,r);case"'":return fg(t,a);case"<":l=o[fg(c,1,-1)];break;default:var d=+c;if(0===d)return n;if(d>s){var u=hg(d/10);return 0===u?n:u<=s?void 0===i[u-1]?pg(c,1):i[u-1]+pg(c,1):n}l=i[d-1]}return void 0===l?"":l}))},vg=l,yg=Mt,Tg=F,Ig=R,Ag=I_,Sg=TypeError,Rg=eu,bg=l,wg=T,Cg=function(e,t,r,i){var o=X_(e),n=!J_((function(){var t={};return t[o]=function(){return 7},7!==""[e](t)})),a=n&&!J_((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[Q_]=function(){return r},r.flags="",r[o]=/./[o]),r.exec=function(){return t=!0,null},r[o](""),!t}));if(!n||!a||r){var s=/./[o],c=t(o,""[e],(function(e,t,r,i,o){var a=t.exec;return a===Y_||a===Z_.exec?n&&!o?{done:!0,value:K_(s,t,r,i)}:{done:!0,value:K_(e,r,t,i)}:{done:!1}}));q_(String.prototype,e,c[0]),q_(Z_,o,c[1])}i&&$_(Z_[o],"sham",!0)},Dg=o,Ng=Mt,kg=F,Og=k,Mg=ii,Lg=di,Pg=po,xg=L,Ug=function(e,t,r){return t+(r?lg(e,t).length:1)},Vg=ye,Fg=Eg,Bg=function(e,t){var r=e.exec;if(Tg(r)){var i=vg(r,e,t);return null!==i&&yg(i),i}if("RegExp"===Ig(e))return vg(Ag,e,t);throw new Sg("RegExp#exec called on incompatible receiver")},Hg=tt("replace"),Wg=Math.max,jg=Math.min,Gg=wg([].concat),zg=wg([].push),Kg=wg("".indexOf),qg=wg("".slice),Yg=function(e){return void 0===e?e:String(e)},Jg="$0"==="a".replace(/./,"$0"),Xg=!!/./[Hg]&&""===/./[Hg]("a","$0");Cg("replace",(function(e,t,r){var i=Xg?"$":"$0";return[function(e,r){var i=xg(this),o=Og(e)?void 0:Vg(e,Hg);return o?bg(o,e,i,r):bg(t,Pg(i),e,r)},function(e,o){var n=Ng(this),a=Pg(e);if("string"==typeof o&&-1===Kg(o,i)&&-1===Kg(o,"$<")){var s=r(t,n,a,o);if(s.done)return s.value}var c=kg(o);c||(o=Pg(o));var l,d=n.global;d&&(l=n.unicode,n.lastIndex=0);for(var u,h=[];null!==(u=Bg(n,a))&&(zg(h,u),d);){""===Pg(u[0])&&(n.lastIndex=Ug(a,Lg(n.lastIndex),l))}for(var p="",m=0,f=0;f<h.length;f++){for(var _,g=Pg((u=h[f])[0]),E=Wg(jg(Mg(u.index),a.length),0),v=[],y=1;y<u.length;y++)zg(v,Yg(u[y]));var T=u.groups;if(c){var I=Gg([g],v,E,a);void 0!==T&&zg(I,T),_=Pg(Rg(o,void 0,I))}else _=Fg(g,a,E,v,T,o);E>=m&&(p+=qg(a,m,E)+_,m=E+g.length)}return p+qg(a,m)}]}),!!Dg((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}))||!Jg||Xg);var $g="\t\n\v\f\r                 \u2028\u2029\ufeff",Qg=L,Zg=po,eE=$g,tE=T("".replace),rE=RegExp("^["+eE+"]+"),iE=RegExp("(^|[^"+eE+"])["+eE+"]+$"),oE=function(e){return function(t){var r=Zg(Qg(t));return 1&e&&(r=tE(r,rE,"")),2&e&&(r=tE(r,iE,"$1")),r}},nE={start:oE(1),end:oE(2),trim:oE(3)},aE=er.PROPER,sE=o,cE=$g,lE=nE.trim;to({target:"String",proto:!0,forced:function(e){return sE((function(){return!!cE[e]()||"​…᠎"!=="​…᠎"[e]()||aE&&cE[e].name!==e}))}("trim")},{trim:function(){return lE(this)}});var dE,uE,hE,pE={exports:{}},mE=Uc,fE=n,_E=r,gE=F,EE=H,vE=He,yE=lo,TE=pe,IE=qt,AE=$r,SE=_o,RE=z,bE=Sa,wE=ts,CE=tt,DE=Ke,NE=Cr.enforce,kE=Cr.get,OE=_E.Int8Array,ME=OE&&OE.prototype,LE=_E.Uint8ClampedArray,PE=LE&&LE.prototype,xE=OE&&bE(OE),UE=ME&&bE(ME),VE=Object.prototype,FE=_E.TypeError,BE=CE("toStringTag"),HE=DE("TYPED_ARRAY_TAG"),WE="TypedArrayConstructor",jE=mE&&!!wE&&"Opera"!==yE(_E.opera),GE=!1,zE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},KE={BigInt64Array:8,BigUint64Array:8},qE=function(e){var t=bE(e);if(EE(t)){var r=kE(t);return r&&vE(r,WE)?r[WE]:qE(t)}},YE=function(e){if(!EE(e))return!1;var t=yE(e);return vE(zE,t)||vE(KE,t)};for(dE in zE)(hE=(uE=_E[dE])&&uE.prototype)?NE(hE)[WE]=uE:jE=!1;for(dE in KE)(hE=(uE=_E[dE])&&uE.prototype)&&(NE(hE)[WE]=uE);if((!jE||!gE(xE)||xE===Function.prototype)&&(xE=function(){throw new FE("Incorrect invocation")},jE))for(dE in zE)_E[dE]&&wE(_E[dE],xE);if((!jE||!UE||UE===VE)&&(UE=xE.prototype,jE))for(dE in zE)_E[dE]&&wE(_E[dE].prototype,UE);if(jE&&bE(PE)!==UE&&wE(PE,UE),fE&&!vE(UE,BE))for(dE in GE=!0,SE(UE,BE,{configurable:!0,get:function(){return EE(this)?this[HE]:void 0}}),zE)_E[dE]&&IE(_E[dE],HE,dE);var JE={NATIVE_ARRAY_BUFFER_VIEWS:jE,TYPED_ARRAY_TAG:GE&&HE,aTypedArray:function(e){if(YE(e))return e;throw new FE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(gE(e)&&(!wE||RE(xE,e)))return e;throw new FE(TE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,r,i){if(fE){if(r)for(var o in zE){var n=_E[o];if(n&&vE(n.prototype,e))try{delete n.prototype[e]}catch(xG){try{n.prototype[e]=t}catch(a){}}}UE[e]&&!r||AE(UE,e,r?t:jE&&ME[e]||t,i)}},exportTypedArrayStaticMethod:function(e,t,r){var i,o;if(fE){if(wE){if(r)for(i in zE)if((o=_E[i])&&vE(o,e))try{delete o[e]}catch(xG){}if(xE[e]&&!r)return;try{return AE(xE,e,r?t:jE&&xE[e]||t)}catch(xG){}}for(i in zE)!(o=_E[i])||o[e]&&!r||AE(o,e,t)}},getTypedArrayConstructor:qE,isView:function(e){if(!EE(e))return!1;var t=yE(e);return"DataView"===t||vE(zE,t)||vE(KE,t)},isTypedArray:YE,TypedArray:xE,TypedArrayPrototype:UE},XE=r,$E=o,QE=sm,ZE=JE.NATIVE_ARRAY_BUFFER_VIEWS,ev=XE.ArrayBuffer,tv=XE.Int8Array,rv=!ZE||!$E((function(){tv(1)}))||!$E((function(){new tv(-1)}))||!QE((function(e){new tv,new tv(null),new tv(1.5),new tv(e)}),!0)||$E((function(){return 1!==new tv(new ev(2),1,void 0).length})),iv=H,ov=Math.floor,nv=Number.isInteger||function(e){return!iv(e)&&isFinite(e)&&ov(e)===e},av=ii,sv=RangeError,cv=function(e){var t=av(e);if(t<0)throw new sv("The argument can't be less than 0");return t},lv=RangeError,dv=function(e,t){var r=cv(e);if(r%t)throw new lv("Wrong offset");return r},uv=Math.round,hv=lo,pv=lt,mv=TypeError,fv=function(e){var t=pv(e,"number");if("number"==typeof t)throw new mv("Can't convert number to bigint");return BigInt(t)},_v=Zo,gv=l,Ev=Gd,vv=Ve,yv=hi,Tv=Vp,Iv=kp,Av=Rp,Sv=function(e){var t=hv(e);return"BigInt64Array"===t||"BigUint64Array"===t},Rv=JE.aTypedArrayConstructor,bv=fv,wv=Zo,Cv=N,Dv=Ve,Nv=hi,kv=bn,Ov=T([].push),Mv=function(e){var t=1===e,r=2===e,i=3===e,o=4===e,n=6===e,a=7===e,s=5===e||n;return function(c,l,d,u){for(var h,p,m=Dv(c),f=Cv(m),_=Nv(f),g=wv(l,d),E=0,v=u||kv,y=t?v(c,_):r||a?v(c,0):void 0;_>E;E++)if((s||E in f)&&(p=g(h=f[E],E,m),e))if(t)y[E]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return E;case 2:Ov(y,h)}else switch(e){case 4:return!1;case 7:Ov(y,h)}return n?-1:i||o?o:y}},Lv={forEach:Mv(0),map:Mv(1),filter:Mv(2),some:Mv(3),every:Mv(4),find:Mv(5),findIndex:Mv(6),filterReject:Mv(7)},Pv=hi,xv=to,Uv=r,Vv=l,Fv=n,Bv=rv,Hv=JE,Wv=_d,jv=Wc,Gv=_,zv=qt,Kv=nv,qv=di,Yv=Kc,Jv=dv,Xv=function(e){var t=uv(e);return t<0?0:t>255?255:255&t},$v=ht,Qv=He,Zv=lo,ey=H,ty=ue,ry=ia,iy=z,oy=ts,ny=Qr.f,ay=function(e){var t,r,i,o,n,a,s,c,l=Ev(this),d=vv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Iv(d);if(m&&!Av(m))for(c=(s=Tv(d,m)).next,d=[];!(a=gv(c,s)).done;)d.push(a.value);for(p&&u>2&&(h=_v(h,arguments[2])),r=yv(d),i=new(Rv(l))(r),o=Sv(i),t=0;r>t;t++)n=p?h(d[t],t):d[t],i[t]=o?bv(n):+n;return i},sy=Lv.forEach,cy=Td,ly=_o,dy=Ct,uy=i,hy=function(e,t,r){for(var i=0,o=arguments.length>2?r:Pv(t),n=new e(o);o>i;)n[i]=t[i++];return n},py=ml,my=Cr.get,fy=Cr.set,_y=Cr.enforce,gy=dy.f,Ey=uy.f,vy=Uv.RangeError,yy=Wv.ArrayBuffer,Ty=yy.prototype,Iy=Wv.DataView,Ay=Hv.NATIVE_ARRAY_BUFFER_VIEWS,Sy=Hv.TYPED_ARRAY_TAG,Ry=Hv.TypedArray,by=Hv.TypedArrayPrototype,wy=Hv.isTypedArray,Cy="BYTES_PER_ELEMENT",Dy="Wrong length",Ny=function(e,t){ly(e,t,{configurable:!0,get:function(){return my(this)[t]}})},ky=function(e){var t;return iy(Ty,e)||"ArrayBuffer"===(t=Zv(e))||"SharedArrayBuffer"===t},Oy=function(e,t){return wy(e)&&!ty(t)&&t in e&&Kv(+t)&&t>=0},My=function(e,t){return t=$v(t),Oy(e,t)?Gv(2,e[t]):Ey(e,t)},Ly=function(e,t,r){return t=$v(t),!(Oy(e,t)&&ey(r)&&Qv(r,"value"))||Qv(r,"get")||Qv(r,"set")||r.configurable||Qv(r,"writable")&&!r.writable||Qv(r,"enumerable")&&!r.enumerable?gy(e,t,r):(e[t]=r.value,e)};Fv?(Ay||(uy.f=My,dy.f=Ly,Ny(by,"buffer"),Ny(by,"byteOffset"),Ny(by,"byteLength"),Ny(by,"length")),xv({target:"Object",stat:!0,forced:!Ay},{getOwnPropertyDescriptor:My,defineProperty:Ly}),pE.exports=function(e,t,r){var i=e.match(/\d+/)[0]/8,o=e+(r?"Clamped":"")+"Array",n="get"+e,a="set"+e,s=Uv[o],c=s,l=c&&c.prototype,d={},u=function(e,t){gy(e,t,{get:function(){return function(e,t){var r=my(e);return r.view[n](t*i+r.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,o){var n=my(e);n.view[a](t*i+n.byteOffset,r?Xv(o):o,!0)}(this,t,e)},enumerable:!0})};Ay?Bv&&(c=t((function(e,t,r,o){return jv(e,l),py(ey(t)?ky(t)?void 0!==o?new s(t,Jv(r,i),o):void 0!==r?new s(t,Jv(r,i)):new s(t):wy(t)?hy(c,t):Vv(ay,c,t):new s(Yv(t)),e,c)})),oy&&oy(c,Ry),sy(ny(s),(function(e){e in c||zv(c,e,s[e])})),c.prototype=l):(c=t((function(e,t,r,o){jv(e,l);var n,a,s,d=0,h=0;if(ey(t)){if(!ky(t))return wy(t)?hy(c,t):Vv(ay,c,t);n=t,h=Jv(r,i);var p=t.byteLength;if(void 0===o){if(p%i)throw new vy(Dy);if((a=p-h)<0)throw new vy(Dy)}else if((a=qv(o)*i)+h>p)throw new vy(Dy);s=a/i}else s=Yv(t),n=new yy(a=s*i);for(fy(e,{buffer:n,byteOffset:h,byteLength:a,length:s,view:new Iy(n)});d<s;)u(e,d++)})),oy&&oy(c,Ry),l=c.prototype=ry(by)),l.constructor!==c&&zv(l,"constructor",c),_y(l).TypedArrayConstructor=c,Sy&&zv(l,Sy,o);var h=c!==s;d[o]=c,xv({global:!0,constructor:!0,forced:h,sham:!Ay},d),Cy in c||zv(c,Cy,i),Cy in l||zv(l,Cy,i),cy(o)}):pE.exports=function(){};var Py=pE.exports;Py("Float32",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Float64",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Int8",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Int16",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Int32",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Uint8",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Uint8",(function(e){return function(t,r,i){return e(this,t,r,i)}}),!0),Py("Uint16",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Py("Uint32",(function(e){return function(t,r,i){return e(this,t,r,i)}}));var xy=dl,Uy=fv,Vy=lo,Fy=l,By=o,Hy=JE.aTypedArray,Wy=JE.exportTypedArrayMethod,jy=T("".slice);Wy("fill",(function(e){var t=arguments.length;Hy(this);var r="Big"===jy(Vy(this),0,3)?Uy(e):+e;return Fy(xy,this,r,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),By((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var Gy=r,zy=l,Ky=JE,qy=hi,Yy=dv,Jy=Ve,Xy=o,$y=Gy.RangeError,Qy=Gy.Int8Array,Zy=Qy&&Qy.prototype,eT=Zy&&Zy.set,tT=Ky.aTypedArray,rT=Ky.exportTypedArrayMethod,iT=!Xy((function(){var e=new Uint8ClampedArray(2);return zy(eT,e,{length:1,0:3},1),3!==e[1]})),oT=iT&&Ky.NATIVE_ARRAY_BUFFER_VIEWS&&Xy((function(){var e=new Qy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));rT("set",(function(e){tT(this);var t=Yy(arguments.length>1?arguments[1]:void 0,1),r=Jy(e);if(iT)return zy(eT,this,r,t);var i=this.length,o=qy(r),n=0;if(o+t>i)throw new $y("Wrong length");for(;n<o;)this[t+n]=r[n++]}),!iT||oT);var nT=Jo,aT=o,sT=ge,cT=dc,lT=hc,dT=pc,uT=te,hT=fc,pT=JE.aTypedArray,mT=JE.exportTypedArrayMethod,fT=r.Uint16Array,_T=fT&&nT(fT.prototype.sort),gT=!(!_T||aT((function(){_T(new fT(2),null)}))&&aT((function(){_T(new fT(2),{})}))),ET=!!_T&&!aT((function(){if(uT)return uT<74;if(lT)return lT<67;if(dT)return!0;if(hT)return hT<602;var e,t,r=new fT(516),i=Array(516);for(e=0;e<516;e++)t=e%4,r[e]=515-e,i[e]=e-2*t+3;for(_T(r,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(r[e]!==i[e])return!0}));mT("sort",(function(e){return void 0!==e&&sT(e),ET?_T(this,e):cT(pT(this),function(e){return function(t,r){return void 0!==e?+e(t,r)||0:r!=r?-1:t!=t?1:0===t&&0===r?1/t>0&&1/r<0?1:-1:t>r}}(e))}),!ET||gT);var vT=to,yT=l,TT=T,IT=L,AT=F,ST=k,RT=Jm,bT=po,wT=ye,CT=of,DT=Eg,NT=tt("replace"),kT=TypeError,OT=TT("".indexOf);TT("".replace);var MT=TT("".slice),LT=Math.max;vT({target:"String",proto:!0},{replaceAll:function(e,t){var r,i,o,n,a,s,c,l,d,u=IT(this),h=0,p="";if(!ST(e)){if(RT(e)&&(r=bT(IT(CT(e))),!~OT(r,"g")))throw new kT("`.replaceAll` does not allow non-global regexes");if(i=wT(e,NT))return yT(i,e,u,t)}for(o=bT(u),n=bT(e),(a=AT(t))||(t=bT(t)),s=n.length,c=LT(1,s),l=OT(o,n);-1!==l;)d=a?bT(t(n,l,o)):DT(n,o,l,[],void 0,t),p+=MT(o,h,l)+d,h=l+s,l=l+c>o.length?-1:OT(o,n,l+c);return h<o.length&&(p+=MT(o,h)),p}});var PT={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},xT=_t("span").classList,UT=xT&&xT.constructor&&xT.constructor.prototype,VT=UT===Object.prototype?void 0:UT,FT=Lv.forEach,BT=zs("forEach")?[].forEach:function(e){return FT(this,e,arguments.length>1?arguments[1]:void 0)},HT=r,WT=PT,jT=VT,GT=BT,zT=qt,KT=function(e){if(e&&e.forEach!==GT)try{zT(e,"forEach",GT)}catch(xG){e.forEach=GT}};for(var qT in WT)WT[qT]&&KT(HT[qT]&&HT[qT].prototype);KT(jT);var YT=r,JT=PT,XT=VT,$T=Ls,QT=qt,ZT=Ua,eI=tt("iterator"),tI=$T.values,rI=function(e,t){if(e){if(e[eI]!==tI)try{QT(e,eI,tI)}catch(xG){e[eI]=tI}if(ZT(e,t,!0),JT[t])for(var r in $T)if(e[r]!==$T[r])try{QT(e,r,$T[r])}catch(xG){e[r]=$T[r]}}};for(var iI in JT)rI(YT[iI]&&YT[iI].prototype,iI);rI(XT,"DOMTokenList");var oI=Nu.clear;to({global:!0,bind:!0,enumerable:!0,forced:r.clearImmediate!==oI},{clearImmediate:oI});var nI=r,aI=eu,sI=F,cI=Xs,lI=Y,dI=ac,uI=ru,hI=nI.Function,pI=/MSIE .\./.test(lI)||"BUN"===cI&&function(){var e=nI.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),mI=to,fI=r,_I=Nu.set,gI=function(e,t){var r=t?2:1;return pI?function(i,o){var n=uI(arguments.length,1)>r,a=sI(i)?i:hI(i),s=n?dI(arguments,r):[],c=n?function(){aI(a,this,s)}:a;return t?e(c,o):e(c)}:e},EI=fI.setImmediate?gI(_I,!1):_I;mI({global:!0,bind:!0,enumerable:!0,forced:fI.setImmediate!==EI},{setImmediate:EI});var vI=cg.charAt,yI=po,TI=Cr,II=Ts,AI=Is,SI="String Iterator",RI=TI.set,bI=TI.getterFor(SI);II(String,"String",(function(e){RI(this,{type:SI,string:yI(e),index:0})}),(function(){var e,t=bI(this),r=t.string,i=t.index;return i>=r.length?AI(void 0,!0):(e=vI(r,i),t.index+=e.length,AI(e,!1))}));var wI=o,CI=n,DI=tt("iterator"),NI=!wI((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,r=new URLSearchParams("a=1&a=2&b=3"),i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),r.delete("a",2),r.delete("b",void 0),!t.size&&!CI||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[DI]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==i||"x"!==new URL("https://x",void 0).host})),kI=n,OI=T,MI=l,LI=o,PI=Pn,xI=wi,UI=d,VI=Ve,FI=N,BI=Object.assign,HI=Object.defineProperty,WI=OI([].concat),jI=!BI||LI((function(){if(kI&&1!==BI({b:1},BI(HI({},"a",{enumerable:!0,get:function(){HI(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol("assign detection"),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach((function(e){t[e]=e})),7!==BI({},e)[r]||PI(BI({},t)).join("")!==i}))?function(e,t){for(var r=VI(e),i=arguments.length,o=1,n=xI.f,a=UI.f;i>o;)for(var s,c=FI(arguments[o++]),l=n?WI(PI(c),n(c)):PI(c),d=l.length,u=0;d>u;)s=l[u++],kI&&!MI(a,c,s)||(r[s]=c[s]);return r}:BI,GI=Mt,zI=Wp,KI=n,qI=Ct,YI=_,JI=Zo,XI=l,$I=Ve,QI=function(e,t,r,i){try{return i?t(GI(r)[0],r[1]):t(r)}catch(xG){zI(e,"throw",xG)}},ZI=Rp,eA=vn,tA=hi,rA=function(e,t,r){KI?qI.f(e,t,YI(0,r)):e[t]=r},iA=Vp,oA=kp,nA=Array,aA=T,sA=2147483647,cA=/[^\0-\u007E]/,lA=/[.\u3002\uFF0E\uFF61]/g,dA="Overflow: input needs wider integers to process",uA=RangeError,hA=aA(lA.exec),pA=Math.floor,mA=String.fromCharCode,fA=aA("".charCodeAt),_A=aA([].join),gA=aA([].push),EA=aA("".replace),vA=aA("".split),yA=aA("".toLowerCase),TA=function(e){return e+22+75*(e<26)},IA=function(e,t,r){var i=0;for(e=r?pA(e/700):e>>1,e+=pA(e/t);e>455;)e=pA(e/35),i+=36;return pA(i+36*e/(e+38))},AA=function(e){var t=[];e=function(e){for(var t=[],r=0,i=e.length;r<i;){var o=fA(e,r++);if(o>=55296&&o<=56319&&r<i){var n=fA(e,r++);56320==(64512&n)?gA(t,((1023&o)<<10)+(1023&n)+65536):(gA(t,o),r--)}else gA(t,o)}return t}(e);var r,i,o=e.length,n=128,a=0,s=72;for(r=0;r<e.length;r++)(i=e[r])<128&&gA(t,mA(i));var c=t.length,l=c;for(c&&gA(t,"-");l<o;){var d=sA;for(r=0;r<e.length;r++)(i=e[r])>=n&&i<d&&(d=i);var u=l+1;if(d-n>pA((sA-a)/u))throw new uA(dA);for(a+=(d-n)*u,n=d,r=0;r<e.length;r++){if((i=e[r])<n&&++a>sA)throw new uA(dA);if(i===n){for(var h=a,p=36;;){var m=p<=s?1:p>=s+26?26:p-s;if(h<m)break;var f=h-m,_=36-m;gA(t,mA(TA(m+f%_))),h=pA(f/_),p+=36}gA(t,mA(TA(h))),s=IA(a,u,l===c),a=0,l++}}a++,n++}return _A(t,"")},SA=to,RA=T,bA=si,wA=RangeError,CA=String.fromCharCode,DA=String.fromCodePoint,NA=RA([].join);SA({target:"String",stat:!0,arity:1,forced:!!DA&&1!==DA.length},{fromCodePoint:function(e){for(var t,r=[],i=arguments.length,o=0;i>o;){if(t=+arguments[o++],bA(t,1114111)!==t)throw new wA(t+" is not a valid code point");r[o]=t<65536?CA(t):CA(55296+((t-=65536)>>10),t%1024+56320)}return NA(r,"")}});var kA=to,OA=r,MA=Lu,LA=G,PA=l,xA=T,UA=n,VA=NI,FA=$r,BA=_o,HA=Fc,WA=Ua,jA=Ga,GA=Cr,zA=Wc,KA=F,qA=He,YA=Zo,JA=lo,XA=Mt,$A=H,QA=po,ZA=ia,eS=_,tS=Vp,rS=kp,iS=Is,oS=ru,nS=dc,aS=tt("iterator"),sS="URLSearchParams",cS=sS+"Iterator",lS=GA.set,dS=GA.getterFor(sS),uS=GA.getterFor(cS),hS=MA("fetch"),pS=MA("Request"),mS=MA("Headers"),fS=pS&&pS.prototype,_S=mS&&mS.prototype,gS=OA.TypeError,ES=OA.encodeURIComponent,vS=String.fromCharCode,yS=LA("String","fromCodePoint"),TS=parseInt,IS=xA("".charAt),AS=xA([].join),SS=xA([].push),RS=xA("".replace),bS=xA([].shift),wS=xA([].splice),CS=xA("".split),DS=xA("".slice),NS=xA(/./.exec),kS=/\+/g,OS=/^[0-9a-f]+$/i,MS=function(e,t){var r=DS(e,t,t+2);return NS(OS,r)?TS(r,16):NaN},LS=function(e){for(var t=0,r=128;r>0&&e&r;r>>=1)t++;return t},PS=function(e){var t=null;switch(e.length){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return t>1114111?null:t},xS=function(e){for(var t=(e=RS(e,kS," ")).length,r="",i=0;i<t;){var o=IS(e,i);if("%"===o){if("%"===IS(e,i+1)||i+3>t){r+="%",i++;continue}var n=MS(e,i+1);if(n!=n){r+=o,i++;continue}i+=2;var a=LS(n);if(0===a)o=vS(n);else{if(1===a||a>4){r+="�",i++;continue}for(var s=[n],c=1;c<a&&!(++i+3>t||"%"!==IS(e,i));){var l=MS(e,i+1);if(l!=l){i+=3;break}if(l>191||l<128)break;SS(s,l),i+=2,c++}if(s.length!==a){r+="�";continue}var d=PS(s);null===d?r+="�":o=yS(d)}}r+=o,i++}return r},US=/[!'()~]|%20/g,VS={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},FS=function(e){return VS[e]},BS=function(e){return RS(ES(e),US,FS)},HS=jA((function(e,t){lS(this,{type:cS,target:dS(e).entries,index:0,kind:t})}),sS,(function(){var e=uS(this),t=e.target,r=e.index++;if(!t||r>=t.length)return e.target=null,iS(void 0,!0);var i=t[r];switch(e.kind){case"keys":return iS(i.key,!1);case"values":return iS(i.value,!1)}return iS([i.key,i.value],!1)}),!0),WS=function(e){this.entries=[],this.url=null,void 0!==e&&($A(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===IS(e,0)?DS(e,1):e:QA(e)))};WS.prototype={type:sS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,r,i,o,n,a,s,c=this.entries,l=rS(e);if(l)for(r=(t=tS(e,l)).next;!(i=PA(r,t)).done;){if(n=(o=tS(XA(i.value))).next,(a=PA(n,o)).done||(s=PA(n,o)).done||!PA(n,o).done)throw new gS("Expected sequence with length 2");SS(c,{key:QA(a.value),value:QA(s.value)})}else for(var d in e)qA(e,d)&&SS(c,{key:d,value:QA(e[d])})},parseQuery:function(e){if(e)for(var t,r,i=this.entries,o=CS(e,"&"),n=0;n<o.length;)(t=o[n++]).length&&(r=CS(t,"="),SS(i,{key:xS(bS(r)),value:xS(AS(r,"="))}))},serialize:function(){for(var e,t=this.entries,r=[],i=0;i<t.length;)e=t[i++],SS(r,BS(e.key)+"="+BS(e.value));return AS(r,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var jS=function(){zA(this,GS);var e=lS(this,new WS(arguments.length>0?arguments[0]:void 0));UA||(this.size=e.entries.length)},GS=jS.prototype;if(HA(GS,{append:function(e,t){var r=dS(this);oS(arguments.length,2),SS(r.entries,{key:QA(e),value:QA(t)}),UA||this.length++,r.updateURL()},delete:function(e){for(var t=dS(this),r=oS(arguments.length,1),i=t.entries,o=QA(e),n=r<2?void 0:arguments[1],a=void 0===n?n:QA(n),s=0;s<i.length;){var c=i[s];if(c.key!==o||void 0!==a&&c.value!==a)s++;else if(wS(i,s,1),void 0!==a)break}UA||(this.size=i.length),t.updateURL()},get:function(e){var t=dS(this).entries;oS(arguments.length,1);for(var r=QA(e),i=0;i<t.length;i++)if(t[i].key===r)return t[i].value;return null},getAll:function(e){var t=dS(this).entries;oS(arguments.length,1);for(var r=QA(e),i=[],o=0;o<t.length;o++)t[o].key===r&&SS(i,t[o].value);return i},has:function(e){for(var t=dS(this).entries,r=oS(arguments.length,1),i=QA(e),o=r<2?void 0:arguments[1],n=void 0===o?o:QA(o),a=0;a<t.length;){var s=t[a++];if(s.key===i&&(void 0===n||s.value===n))return!0}return!1},set:function(e,t){var r=dS(this);oS(arguments.length,1);for(var i,o=r.entries,n=!1,a=QA(e),s=QA(t),c=0;c<o.length;c++)(i=o[c]).key===a&&(n?wS(o,c--,1):(n=!0,i.value=s));n||SS(o,{key:a,value:s}),UA||(this.size=o.length),r.updateURL()},sort:function(){var e=dS(this);nS(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,r=dS(this).entries,i=YA(e,arguments.length>1?arguments[1]:void 0),o=0;o<r.length;)i((t=r[o++]).value,t.key,this)},keys:function(){return new HS(this,"keys")},values:function(){return new HS(this,"values")},entries:function(){return new HS(this,"entries")}},{enumerable:!0}),FA(GS,aS,GS.entries,{name:"entries"}),FA(GS,"toString",(function(){return dS(this).serialize()}),{enumerable:!0}),UA&&BA(GS,"size",{get:function(){return dS(this).entries.length},configurable:!0,enumerable:!0}),WA(jS,sS),kA({global:!0,constructor:!0,forced:!VA},{URLSearchParams:jS}),!VA&&KA(mS)){var zS=xA(_S.has),KS=xA(_S.set),qS=function(e){if($A(e)){var t,r=e.body;if(JA(r)===sS)return t=e.headers?new mS(e.headers):new mS,zS(t,"content-type")||KS(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),ZA(e,{body:eS(0,QA(r)),headers:eS(0,t)})}return e};if(KA(hS)&&kA({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return hS(e,arguments.length>1?qS(arguments[1]):{})}}),KA(pS)){var YS=function(e){return zA(this,fS),new pS(e,arguments.length>1?qS(arguments[1]):{})};fS.constructor=YS,YS.prototype=fS,kA({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:YS})}}var JS,XS=to,$S=n,QS=NI,ZS=r,eR=Zo,tR=T,rR=$r,iR=_o,oR=Wc,nR=He,aR=jI,sR=function(e){var t=$I(e),r=eA(this),i=arguments.length,o=i>1?arguments[1]:void 0,n=void 0!==o;n&&(o=JI(o,i>2?arguments[2]:void 0));var a,s,c,l,d,u,h=oA(t),p=0;if(!h||this===nA&&ZI(h))for(a=tA(t),s=r?new this(a):nA(a);a>p;p++)u=n?o(t[p],p):t[p],rA(s,p,u);else for(s=r?new this:[],d=(l=iA(t,h)).next;!(c=XI(d,l)).done;p++)u=n?QI(l,o,[c.value,p],!0):c.value,rA(s,p,u);return s.length=p,s},cR=ac,lR=cg.codeAt,dR=function(e){var t,r,i=[],o=vA(EA(yA(e),lA,"."),".");for(t=0;t<o.length;t++)r=o[t],gA(i,hA(cA,r)?"xn--"+AA(r):r);return _A(i,".")},uR=po,hR=Ua,pR=ru,mR={URLSearchParams:jS,getState:dS},fR=Cr,_R=fR.set,gR=fR.getterFor("URL"),ER=mR.URLSearchParams,vR=mR.getState,yR=ZS.URL,TR=ZS.TypeError,IR=ZS.parseInt,AR=Math.floor,SR=Math.pow,RR=tR("".charAt),bR=tR(/./.exec),wR=tR([].join),CR=tR(1..toString),DR=tR([].pop),NR=tR([].push),kR=tR("".replace),OR=tR([].shift),MR=tR("".split),LR=tR("".slice),PR=tR("".toLowerCase),xR=tR([].unshift),UR="Invalid scheme",VR="Invalid host",FR="Invalid port",BR=/[a-z]/i,HR=/[\d+-.a-z]/i,WR=/\d/,jR=/^0x/i,GR=/^[0-7]+$/,zR=/^\d+$/,KR=/^[\da-f]+$/i,qR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,YR=/[\0\t\n\r #/:<>?@[\\\]^|]/,JR=/^[\u0000-\u0020]+/,XR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,$R=/[\t\n\r]/g,QR=function(e){var t,r,i,o;if("number"==typeof e){for(t=[],r=0;r<4;r++)xR(t,e%256),e=AR(e/256);return wR(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,r=1,i=null,o=0,n=0;n<8;n++)0!==e[n]?(o>r&&(t=i,r=o),i=null,o=0):(null===i&&(i=n),++o);return o>r?i:t}(e),r=0;r<8;r++)o&&0===e[r]||(o&&(o=!1),i===r?(t+=r?":":"::",o=!0):(t+=CR(e[r],16),r<7&&(t+=":")));return"["+t+"]"}return e},ZR={},eb=aR({},ZR,{" ":1,'"':1,"<":1,">":1,"`":1}),tb=aR({},eb,{"#":1,"?":1,"{":1,"}":1}),rb=aR({},tb,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ib=function(e,t){var r=lR(e,0);return r>32&&r<127&&!nR(t,e)?e:encodeURIComponent(e)},ob={ftp:21,file:null,http:80,https:443,ws:80,wss:443},nb=function(e,t){var r;return 2===e.length&&bR(BR,RR(e,0))&&(":"===(r=RR(e,1))||!t&&"|"===r)},ab=function(e){var t;return e.length>1&&nb(LR(e,0,2))&&(2===e.length||"/"===(t=RR(e,2))||"\\"===t||"?"===t||"#"===t)},sb=function(e){return"."===e||"%2e"===PR(e)},cb={},lb={},db={},ub={},hb={},pb={},mb={},fb={},_b={},gb={},Eb={},vb={},yb={},Tb={},Ib={},Ab={},Sb={},Rb={},bb={},wb={},Cb={},Db=function(e,t,r){var i,o,n,a=uR(e);if(t){if(o=this.parse(a))throw new TR(o);this.searchParams=null}else{if(void 0!==r&&(i=new Db(r,!0)),o=this.parse(a,null,i))throw new TR(o);(n=vR(new ER)).bindURL(this),this.searchParams=n}};Db.prototype={type:"URL",parse:function(e,t,r){var i,o,n,a,s,c=this,l=t||cb,d=0,u="",h=!1,p=!1,m=!1;for(e=uR(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=kR(e,JR,""),e=kR(e,XR,"$1")),e=kR(e,$R,""),i=sR(e);d<=i.length;){switch(o=i[d],l){case cb:if(!o||!bR(BR,o)){if(t)return UR;l=db;continue}u+=PR(o),l=lb;break;case lb:if(o&&(bR(HR,o)||"+"===o||"-"===o||"."===o))u+=PR(o);else{if(":"!==o){if(t)return UR;u="",l=db,d=0;continue}if(t&&(c.isSpecial()!==nR(ob,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&ob[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=Tb:c.isSpecial()&&r&&r.scheme===c.scheme?l=ub:c.isSpecial()?l=fb:"/"===i[d+1]?(l=hb,d++):(c.cannotBeABaseURL=!0,NR(c.path,""),l=bb)}break;case db:if(!r||r.cannotBeABaseURL&&"#"!==o)return UR;if(r.cannotBeABaseURL&&"#"===o){c.scheme=r.scheme,c.path=cR(r.path),c.query=r.query,c.fragment="",c.cannotBeABaseURL=!0,l=Cb;break}l="file"===r.scheme?Tb:pb;continue;case ub:if("/"!==o||"/"!==i[d+1]){l=pb;continue}l=_b,d++;break;case hb:if("/"===o){l=gb;break}l=Rb;continue;case pb:if(c.scheme=r.scheme,o===JS)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=cR(r.path),c.query=r.query;else if("/"===o||"\\"===o&&c.isSpecial())l=mb;else if("?"===o)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=cR(r.path),c.query="",l=wb;else{if("#"!==o){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=cR(r.path),c.path.length--,l=Rb;continue}c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=cR(r.path),c.query=r.query,c.fragment="",l=Cb}break;case mb:if(!c.isSpecial()||"/"!==o&&"\\"!==o){if("/"!==o){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,l=Rb;continue}l=gb}else l=_b;break;case fb:if(l=_b,"/"!==o||"/"!==RR(u,d+1))continue;d++;break;case _b:if("/"!==o&&"\\"!==o){l=gb;continue}break;case gb:if("@"===o){h&&(u="%40"+u),h=!0,n=sR(u);for(var f=0;f<n.length;f++){var _=n[f];if(":"!==_||m){var g=ib(_,rb);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(o===JS||"/"===o||"?"===o||"#"===o||"\\"===o&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=sR(u).length+1,u="",l=Eb}else u+=o;break;case Eb:case vb:if(t&&"file"===c.scheme){l=Ab;continue}if(":"!==o||p){if(o===JS||"/"===o||"?"===o||"#"===o||"\\"===o&&c.isSpecial()){if(c.isSpecial()&&""===u)return VR;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(a=c.parseHost(u))return a;if(u="",l=Sb,t)return;continue}"["===o?p=!0:"]"===o&&(p=!1),u+=o}else{if(""===u)return VR;if(a=c.parseHost(u))return a;if(u="",l=yb,t===vb)return}break;case yb:if(!bR(WR,o)){if(o===JS||"/"===o||"?"===o||"#"===o||"\\"===o&&c.isSpecial()||t){if(""!==u){var E=IR(u,10);if(E>65535)return FR;c.port=c.isSpecial()&&E===ob[c.scheme]?null:E,u=""}if(t)return;l=Sb;continue}return FR}u+=o;break;case Tb:if(c.scheme="file","/"===o||"\\"===o)l=Ib;else{if(!r||"file"!==r.scheme){l=Rb;continue}switch(o){case JS:c.host=r.host,c.path=cR(r.path),c.query=r.query;break;case"?":c.host=r.host,c.path=cR(r.path),c.query="",l=wb;break;case"#":c.host=r.host,c.path=cR(r.path),c.query=r.query,c.fragment="",l=Cb;break;default:ab(wR(cR(i,d),""))||(c.host=r.host,c.path=cR(r.path),c.shortenPath()),l=Rb;continue}}break;case Ib:if("/"===o||"\\"===o){l=Ab;break}r&&"file"===r.scheme&&!ab(wR(cR(i,d),""))&&(nb(r.path[0],!0)?NR(c.path,r.path[0]):c.host=r.host),l=Rb;continue;case Ab:if(o===JS||"/"===o||"\\"===o||"?"===o||"#"===o){if(!t&&nb(u))l=Rb;else if(""===u){if(c.host="",t)return;l=Sb}else{if(a=c.parseHost(u))return a;if("localhost"===c.host&&(c.host=""),t)return;u="",l=Sb}continue}u+=o;break;case Sb:if(c.isSpecial()){if(l=Rb,"/"!==o&&"\\"!==o)continue}else if(t||"?"!==o)if(t||"#"!==o){if(o!==JS&&(l=Rb,"/"!==o))continue}else c.fragment="",l=Cb;else c.query="",l=wb;break;case Rb:if(o===JS||"/"===o||"\\"===o&&c.isSpecial()||!t&&("?"===o||"#"===o)){if(".."===(s=PR(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(c.shortenPath(),"/"===o||"\\"===o&&c.isSpecial()||NR(c.path,"")):sb(u)?"/"===o||"\\"===o&&c.isSpecial()||NR(c.path,""):("file"===c.scheme&&!c.path.length&&nb(u)&&(c.host&&(c.host=""),u=RR(u,0)+":"),NR(c.path,u)),u="","file"===c.scheme&&(o===JS||"?"===o||"#"===o))for(;c.path.length>1&&""===c.path[0];)OR(c.path);"?"===o?(c.query="",l=wb):"#"===o&&(c.fragment="",l=Cb)}else u+=ib(o,tb);break;case bb:"?"===o?(c.query="",l=wb):"#"===o?(c.fragment="",l=Cb):o!==JS&&(c.path[0]+=ib(o,ZR));break;case wb:t||"#"!==o?o!==JS&&("'"===o&&c.isSpecial()?c.query+="%27":c.query+="#"===o?"%23":ib(o,ZR)):(c.fragment="",l=Cb);break;case Cb:o!==JS&&(c.fragment+=ib(o,eb))}d++}},parseHost:function(e){var t,r,i;if("["===RR(e,0)){if("]"!==RR(e,e.length-1))return VR;if(t=function(e){var t,r,i,o,n,a,s,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return RR(e,u)};if(":"===h()){if(":"!==RR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=r=0;r<4&&bR(KR,h());)t=16*t+IR(h(),16),u++,r++;if("."===h()){if(0===r)return;if(u-=r,l>6)return;for(i=0;h();){if(o=null,i>0){if(!("."===h()&&i<4))return;u++}if(!bR(WR,h()))return;for(;bR(WR,h());){if(n=IR(h(),10),null===o)o=n;else{if(0===o)return;o=10*o+n}if(o>255)return;u++}c[l]=256*c[l]+o,2!=++i&&4!==i||l++}if(4!==i)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(a=l-d,l=7;0!==l&&a>0;)s=c[l],c[l--]=c[d+a-1],c[d+--a]=s;else if(8!==l)return;return c}(LR(e,1,-1)),!t)return VR;this.host=t}else if(this.isSpecial()){if(e=dR(e),bR(qR,e))return VR;if(t=function(e){var t,r,i,o,n,a,s,c=MR(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(r=[],i=0;i<t;i++){if(""===(o=c[i]))return e;if(n=10,o.length>1&&"0"===RR(o,0)&&(n=bR(jR,o)?16:8,o=LR(o,8===n?1:2)),""===o)a=0;else{if(!bR(10===n?zR:8===n?GR:KR,o))return e;a=IR(o,n)}NR(r,a)}for(i=0;i<t;i++)if(a=r[i],i===t-1){if(a>=SR(256,5-t))return null}else if(a>255)return null;for(s=DR(r),i=0;i<r.length;i++)s+=r[i]*SR(256,3-i);return s}(e),null===t)return VR;this.host=t}else{if(bR(YR,e))return VR;for(t="",r=sR(e),i=0;i<r.length;i++)t+=ib(r[i],ZR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return nR(ob,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&nb(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,r=e.username,i=e.password,o=e.host,n=e.port,a=e.path,s=e.query,c=e.fragment,l=t+":";return null!==o?(l+="//",e.includesCredentials()&&(l+=r+(i?":"+i:"")+"@"),l+=QR(o),null!==n&&(l+=":"+n)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?a[0]:a.length?"/"+wR(a,"/"):"",null!==s&&(l+="?"+s),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new TR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new Nb(e.path[0]).origin}catch(xG){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+QR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(uR(e)+":",cb)},getUsername:function(){return this.username},setUsername:function(e){var t=sR(uR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var r=0;r<t.length;r++)this.username+=ib(t[r],rb)}},getPassword:function(){return this.password},setPassword:function(e){var t=sR(uR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var r=0;r<t.length;r++)this.password+=ib(t[r],rb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?QR(e):QR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Eb)},getHostname:function(){var e=this.host;return null===e?"":QR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,vb)},getPort:function(){var e=this.port;return null===e?"":uR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=uR(e))?this.port=null:this.parse(e,yb))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+wR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Sb))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=uR(e))?this.query=null:("?"===RR(e,0)&&(e=LR(e,1)),this.query="",this.parse(e,wb)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=uR(e))?("#"===RR(e,0)&&(e=LR(e,1)),this.fragment="",this.parse(e,Cb)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Nb=function(e){var t=oR(this,kb),r=pR(arguments.length,1)>1?arguments[1]:void 0,i=_R(t,new Db(e,!1,r));$S||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},kb=Nb.prototype,Ob=function(e,t){return{get:function(){return gR(this)[e]()},set:t&&function(e){return gR(this)[t](e)},configurable:!0,enumerable:!0}};if($S&&(iR(kb,"href",Ob("serialize","setHref")),iR(kb,"origin",Ob("getOrigin")),iR(kb,"protocol",Ob("getProtocol","setProtocol")),iR(kb,"username",Ob("getUsername","setUsername")),iR(kb,"password",Ob("getPassword","setPassword")),iR(kb,"host",Ob("getHost","setHost")),iR(kb,"hostname",Ob("getHostname","setHostname")),iR(kb,"port",Ob("getPort","setPort")),iR(kb,"pathname",Ob("getPathname","setPathname")),iR(kb,"search",Ob("getSearch","setSearch")),iR(kb,"searchParams",Ob("getSearchParams")),iR(kb,"hash",Ob("getHash","setHash"))),rR(kb,"toJSON",(function(){return gR(this).serialize()}),{enumerable:!0}),rR(kb,"toString",(function(){return gR(this).serialize()}),{enumerable:!0}),yR){var Mb=yR.createObjectURL,Lb=yR.revokeObjectURL;Mb&&rR(Nb,"createObjectURL",eR(Mb,yR)),Lb&&rR(Nb,"revokeObjectURL",eR(Lb,yR))}hR(Nb,"URL"),XS({global:!0,constructor:!0,forced:!QS,sham:!$S},{URL:Nb});var Pb=l;to({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return Pb(URL.prototype.toString,this)}});var xb,Ub=Object.create,Vb=Object.defineProperty,Fb=Object.defineProperties,Bb=Object.getOwnPropertyDescriptor,Hb=Object.getOwnPropertyDescriptors,Wb=Object.getOwnPropertyNames,jb=Object.getOwnPropertySymbols,Gb=Object.getPrototypeOf,zb=Object.prototype.hasOwnProperty,Kb=Object.prototype.propertyIsEnumerable,qb=Reflect.get,Yb=Math.pow,Jb=(e,t,r)=>t in e?Vb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Xb=(e,t)=>{for(var r in t||(t={}))zb.call(t,r)&&Jb(e,r,t[r]);if(jb)for(var r of jb(t))Kb.call(t,r)&&Jb(e,r,t[r]);return e},$b=(e,t)=>Fb(e,Hb(t)),Qb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Zb=(e,t)=>{for(var r in t)Vb(e,r,{get:t[r],enumerable:!0})},ew=(e,t,r)=>(r=null!=e?Ub(Gb(e)):{},((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Wb(t))!zb.call(e,o)&&o!==r&&Vb(e,o,{get:()=>t[o],enumerable:!(i=Bb(t,o))||i.enumerable});return e})(!t&&e&&e.__esModule?r:Vb(r,"default",{value:e,enumerable:!0}),e)),tw=(e,t,r,i)=>{for(var o,n=i>1?void 0:i?Bb(t,r):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(i?o(t,r,n):o(n))||n);return i&&n&&Vb(t,r,n),n},rw=(e,t,r)=>Jb(e,"symbol"!=typeof t?t+"":t,r),iw=(e,t,r)=>qb(Gb(e),r,t),ow=(e,t,r)=>new Promise(((i,o)=>{var n=e=>{try{s(r.next(e))}catch(ZO){o(ZO)}},a=e=>{try{s(r.throw(e))}catch(ZO){o(ZO)}},s=e=>e.done?i(e.value):Promise.resolve(e.value).then(n,a);s((r=r.apply(e,t)).next())})),nw=Qb(((e,t)=>{var r=Object.prototype.hasOwnProperty,i="~";function o(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,r,o,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new n(r,o||e,a),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function c(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(i=!1)),c.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)r.call(e,t)&&o.push(i?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},c.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,n=r.length,a=new Array(n);o<n;o++)a[o]=r[o].fn;return a},c.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},c.prototype.emit=function(e,t,r,o,n,a){var s=i?i+e:e;if(!this._events[s])return!1;var c,l,d=this._events[s],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,r),!0;case 4:return d.fn.call(d.context,t,r,o),!0;case 5:return d.fn.call(d.context,t,r,o,n),!0;case 6:return d.fn.call(d.context,t,r,o,n,a),!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,r);break;case 4:d[l].fn.call(d[l].context,t,r,o);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,r){return a(this,e,t,r,!1)},c.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},c.prototype.removeListener=function(e,t,r,o){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn===t&&(!o||a.once)&&(!r||a.context===r)&&s(this,n);else{for(var c=0,l=[],d=a.length;c<d;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[n]=1===l.length?l[0]:l:s(this,n)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=i,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),aw=Qb(((e,t)=>{var r=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(r).forEach((function(e){r[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),sw=Qb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var o=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:o&&!r[e.name]&&(r[e.name]={});var n=e.push?{}:o?r[e.name]:r;(function(e,r,i,o){if(o&&!i)r[o]=t(e[1]);else for(var n=0;n<i.length;n+=1)null!=e[n+1]&&(r[i[n]]=t(e[n+1]))})(i.match(e.reg),n,e.names,e.name),e.push&&r[e.push].push(n)},i=aw(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(o).forEach((function(e){var t=e[0],o=e.slice(2);"m"===t&&(n.push({rtp:[],fmtp:[]}),a=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(o))return r(c,a,o)}})),t.media=n,t};var n=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(n,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),o=0;o<i.length;o+=3)r.push({component:i[o],ip:i[o+1],port:i[o+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(n,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}})),cw=Qb(((e,t)=>{var r=aw(),i=/%[sdv%]/g,o=function(e){var t=1,r=arguments,o=r.length;return e.replace(i,(function(e){if(t>=o)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},n=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?i.push(r[t.name][a]):i.push(r[t.names[n]])}else i.push(r[t.name]);return o.apply(null,i)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["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 i=t.outerOrder||a,o=t.innerOrder||s,c=[];return i.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(n(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(n(t,r,e))}))}))})),e.media.forEach((function(e){c.push(n("m",r.m[0],e)),o.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(n(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(n(t,r,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),lw=Qb((e=>{var t=sw(),r=cw(),i=aw();e.grammar=i,e.write=r,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})),dw=((xb=dw||{})[xb.INVALID_PARAMETER=4096]="INVALID_PARAMETER",xb[xb.INVALID_OPERATION=4097]="INVALID_OPERATION",xb[xb.NOT_SUPPORTED=4098]="NOT_SUPPORTED",xb[xb.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",xb[xb.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",xb[xb.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",xb[xb.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",xb[xb.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",xb[xb.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",xb[xb.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",xb[xb.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",xb[xb.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",xb[xb.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",xb[xb.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",xb[xb.CLIENT_BANNED=16448]="CLIENT_BANNED",xb[xb.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",xb[xb.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",xb[xb.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",xb[xb.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",xb[xb.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",xb[xb.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",xb[xb.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",xb[xb.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",xb[xb.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",xb[xb.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",xb[xb.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",xb[xb.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",xb[xb.API_CALL_ABORTED=16461]="API_CALL_ABORTED",xb[xb.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",xb[xb.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",xb[xb.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",xb[xb.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",xb[xb.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",xb[xb.UNKNOWN=65535]="UNKNOWN",xb),uw=dw,hw=class extends Error{constructor(e){let{name:t="RtcError",message:r,code:i=uw.UNKNOWN,extraCode:o=0,constraint:n}=e,a="<".concat(function(e){for(let t in uw)if(uw[t]===e)return t;return"UNKNOWN"}(i)," 0x").concat(i.toString(16),">"),s="".concat(r).concat(n?" constraint: ".concat(n):"").concat(null!=r&&r.includes(a)?"":" ".concat(a));super(s),rw(this,"code"),rw(this,"extraCode"),rw(this,"message"),rw(this,"originMessage"),rw(this,"name"),rw(this,"constraint"),this.code=i,this.extraCode=o,this.name=t,this.message=s,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},pw=hw,mw=function(){return 0},fw=function(){return Date.now()+0},_w=function(){let e=new Date;return e.setTime(fw()),e.toLocaleString()},gw=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Ew={};Zb(Ew,{REPORT_TYPE:()=>wN,buildSSOPackage:()=>CN,bytes2ms:()=>CD,calculateScaleResolutionDownNumber:()=>AN,concatArrayBuffers:()=>DN,convertObjectNumberToInt:()=>EN,copyProperties:()=>wD,deepClone:()=>cN,deepCloneBasic:()=>bN,deepMerge:()=>sN,delay:()=>vN,fibonacci:()=>PD,formatedTime:()=>uN,getConstructorName:()=>JD,getContainerFromElement:()=>dN,getEnv:()=>vD,getFirst16Bits:()=>kN,getInternalVersion:()=>tN,getLast16Bits:()=>NN,getLoggerUrl:()=>TD,getMediaStreamTrackInfo:()=>IN,getMuteStateFromFlag:()=>oN,getNetworkType:()=>AD,getNumNetworkType:()=>bD,getReconnectionTimeout:()=>xD,getStringByteLength:()=>mN,getTurnServer:()=>nN,getUint32Version:()=>gN,getValueType:()=>UD,getViewListFromView:()=>lN,glog:()=>OD,ipv4ToUint32:()=>aN,isArray:()=>GD,isAudioWorkletSupported:()=>XD,isBoolean:()=>WD,isConstructor:()=>YD,isEmpty:()=>iN,isFunction:()=>VD,isLangChinese:()=>MD,isMediaStreamTrack:()=>zD,isNumber:()=>HD,isObject:()=>jD,isOverseaSdkAppId:()=>yD,isPlainObject:()=>LD,isPortrait:()=>fN,isPromise:()=>qD,isRemoteTrack:()=>KD,isRotate90Or270:()=>SN,isSetSinkIdSupported:()=>$D,isString:()=>BD,isUndefined:()=>FD,loadImage:()=>_N,loadVideo:()=>RN,ms2bytes:()=>ND,ms2samples:()=>kD,normalizeUrl:()=>TN,performanceNow:()=>ZD,promiseAny:()=>QD,samples2ms:()=>DD,setNetworkType:()=>RD,stringify:()=>hN,stringifyIncludeValue:()=>pN,throttlePromise:()=>yN});var vw={};Zb(vw,{AUDIO_MUTE_BIT:()=>nC,AUDIO_STAT_BIT:()=>oC,AUX_STAT_BIT:()=>iC,AUX_STREAM_MSID:()=>dC,BACKEND_ENV:()=>Zw,BASE_DOC_URL:()=>Lw,BASE_HOST:()=>Nw,CAPABILITIES_KEYS:()=>$C,CLASS_NAME:()=>WC,CLOUD_CONSOLE_URL:()=>Mw,CROSS_ROOM_BIT:()=>cC,DATA_FREEZE_TIMING:()=>PC,DOC_URL:()=>Pw,DTLS_STATE_UNKNOWN:()=>yC,ENV_NAME:()=>Bw,EXCHANGE_SDP_TIMEOUT:()=>NC,IS_WORKER:()=>Rw,IS_WORKLET:()=>bw,KIBANA_EVENT:()=>wC,LOCAL_STREAM_PUBLISH_STATE:()=>LC,LOGGER_CMD_TYPE:()=>Fw,LOGGER_DOMAIN:()=>xw,LOGGER_DOMAIN_OVERSEA:()=>Uw,LOG_LEVEL:()=>Hw,LOG_LEVEL_NAME:()=>qC,MAIN_STREAM_MSID:()=>lC,MAX_RTT:()=>QC,MICROPHONE_COMMUNICATIONS:()=>KC,MICROPHONE_DEFAULT:()=>GC,MUTE_ALL_BIT:()=>sC,NAME:()=>$w,NETWORK_TYPE:()=>Gw,NOT_SUPPORTED_H264:()=>MC,PAUSED_RETRY_COUNT:()=>jC,PEERCONNECTION_CONNECTING_TIMEOUT:()=>FC,PEER_CONNECTION_STATE:()=>TC,PEER_LEAVE_REASON:()=>YC,RECOVER_CAPTURE_INTERVAL:()=>XC,REMOTE_STREAM_TYPE_AUX:()=>hC,REMOTE_STREAM_TYPE_MAIN:()=>uC,RENDER_FREEZE_TIMING:()=>xC,SCHEDULE_DOMAIN:()=>BC,SCHEDULE_TIMEOUT:()=>HC,SDP_SEMANTICS_PLAN_B:()=>OC,SDP_SEMANTICS_UNIFIED_PLAN:()=>kC,SECOND_HOST:()=>kw,SIGNAL_PING_PONG_INTERVAL:()=>jw,SIGNAL_PING_TIMEOUT:()=>Ww,SIGNAL_RECONNECTION_COUNT:()=>bC,SMALL_STAT_BIT:()=>rC,SPEAKER_DEFAULT:()=>zC,STORAGE_EXPIRES_TIME:()=>zw,STREAM_TYPE_BIG:()=>UC,STREAM_TYPE_SMALL:()=>VC,SUBSCRIBE_SMALL_RETRY_COUNT:()=>JC,SYNC_USER_LIST_INTERVAL:()=>CC,Scene:()=>eC,THIRD_HOST:()=>Ow,TRANSPORT_DIRECTION:()=>Qw,TRTC_ERROR_ASSISTANCE:()=>Vw,TRTC_QUALITY_BAD:()=>gC,TRTC_QUALITY_DISCONNECTED:()=>vC,TRTC_QUALITY_EXCELLENT:()=>mC,TRTC_QUALITY_GOOD:()=>fC,TRTC_QUALITY_POOR:()=>_C,TRTC_QUALITY_UNKNOWN:()=>pC,TRTC_QUALITY_VERY_BAD:()=>EC,UPDATE_OFFER_TIMEOUT:()=>DC,VIDEO_MUTE_BIT:()=>aC,VIDEO_STAT_BIT:()=>tC,audioProfileMap:()=>Kw,defaultBigVideoProfile:()=>Yw,defaultSmallVideoProfile:()=>Jw,getRetryCount:()=>SC,getScriptDir:()=>ww,innerVersion:()=>yw,loggerProxy:()=>Cw,screenProfileMap:()=>Xw,setLoggerProxy:()=>Dw,setRetryCount:()=>AC,setVersion:()=>Iw,version:()=>Tw,videoProfileMap:()=>qw});var yw="4.15.00.1600",Tw="5.0.0";function Iw(e){Tw=e;let[t,r,i]=e.split(".").map((e=>parseInt(e,10)));yw="".concat(t,".").concat(Math.min(15,r),".").concat(Math.min(15,i),".").concat(r.toString().padStart(2,"0")).concat(i.toString().padStart(2,"0"))}var Aw,Sw,Rw="undefined"!=typeof importScripts,bw="undefined"!=typeof registerProcessor,ww=()=>{let e=Rw?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Cw="",Dw=e=>Cw=e,Nw="web.sdk.qcloud.com",kw="web.sdk.tencent.cn",Ow="web.sdk.cloud.tencent.cn",Mw="https://console.cloud.tencent.com/trtc",Lw="https://".concat(Nw,"/trtc/webrtc/v5/doc"),Pw="".concat(Lw,"/zh-cn/"),xw="https://yun.tim.qq.com",Uw="https://apisgp.my-imcloud.com",Vw="trtc_error_assistance",Fw={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Bw={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Hw=((Sw=Hw||{})[Sw.TRACE=0]="TRACE",Sw[Sw.DEBUG=1]="DEBUG",Sw[Sw.INFO=2]="INFO",Sw[Sw.WARN=3]="WARN",Sw[Sw.ERROR=4]="ERROR",Sw[Sw.NONE=5]="NONE",Sw),Ww=18e3,jw=2e3,Gw={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},zw=6048e5,Kw={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},qw={"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}},Yw=qw["480p_2"],Jw=qw["120p_2"],Xw={"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}},$w={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",LOADEDMETADATA:"loadedmetadata",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",RESIZE:"resize",TIME_UPDATE:"timeupdate"},Qw={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Zw={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},eC=((Aw=eC||{}).LIVE="live",Aw.RTC="rtc",Aw),tC=1,rC=2,iC=4,oC=8,nC=64,aC=16,sC=112,cC=128,lC="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",dC="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",uC=$w.MAIN,hC=$w.AUXILIARY,pC=0,mC=1,fC=2,_C=3,gC=4,EC=5,vC=6,yC="unknown",TC={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},IC=1/0;function AC(e){IC=e}function SC(){return IC}var RC,bC=30,wC={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},CC=1e4,DC=1e4,NC=1e4,kC="unified-plan",OC="plan-b",MC=1028,LC=((RC=LC||{})[RC.UNPUBLISH=-1]="UNPUBLISH",RC[RC.PUBLISHING=0]="PUBLISHING",RC[RC.PUBLISHED=1]="PUBLISHED",RC),PC=500,xC=1e3,UC=$w.BIG,VC=$w.SMALL,FC=1e4,BC={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},HC=2e3,WC={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},jC=5,GC="default",zC=GC,KC="communications",qC=Object.keys(Hw),YC=["normal leave","timeout leave","kick","role change"],JC=10,XC=2e3,$C=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],QC=1e4,ZC=function(e,t,r,i){return new(r||(r=Promise))((function(o,n){function a(e){try{c(i.next(e))}catch(t){n(t)}}function s(e){try{c(i.throw(e))}catch(t){n(t)}}function c(e){e.done?o(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(a,s)}c((i=i.apply(e,t||[])).next())}))},eD=Symbol(32),tD=Symbol(16),rD=Symbol(8),iD=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,t){return t&&this.consume(),this.need=e,this.flush()}read(e){return ZC(this,void 0,void 0,(function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise(((t,r)=>{var i;this.reject=r,this.resolve=e=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(e)},this.demand(e,!0)||null===(i=this.pull)||void 0===i||i.call(this,e)}))}))}readU32(){return this.read(eD)}readU16(){return this.read(tD)}readU8(){return this.read(rD)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),null===(e=this.reject)||void 0===e||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null,t=this.buffer.subarray(this.consumed),r=0,i=e=>t.length<(r=e);if("number"==typeof this.need){if(i(this.need))return;e=t.subarray(0,r)}else if(this.need===eD){if(i(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===tD){if(i(2))return;e=t[0]<<8|t[1]}else if(this.need===rD){if(i(1))return;e=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(i(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,r)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(i(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,r)),e=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise((e=>this.pull=e));this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){let t=this.buffer.length,r=t+e;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{let e=new Uint8Array(r);e.set(this.buffer),this.buffer=e}return this.buffer.subarray(t,r)}return this.buffer=new Uint8Array(e),this.buffer}};iD.U32=eD,iD.U16=tD,iD.U8=rD;var oD=128;function nD(e){let t=new iD;for(;e>=128;)t.malloc(1)[0]=255&e|oD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function aD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=new iD,i=t<<3;switch(typeof e){case"boolean":let o=r.malloc(2);o[0]=i,o[1]=e?1:0;break;case"number":r.malloc(1)[0]=i,r.write(nD(e));break;case"string":r.malloc(1)[0]=2|i;let n=(new TextEncoder).encode(e);r.write(nD(n.length));let a=r.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new iD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let r=aD(e[t],t+1);r&&s.write(r)}else{let t=1;for(let r in e){let i=aD(e[r],t++);i&&s.write(i)}}0===t?s.buffer&&r.write(s.buffer):(r.malloc(1)[0]=2|i,s.buffer&&(r.write(nD(s.buffer.length)),r.write(s.buffer)))}return r.buffer||new Uint8Array(0)}var sD=class{constructor(){rw(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(e){this.buffer.push(e>>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let t=0;t<e.length;t++)this.buffer.push(e[t])}};function cD(e,t,r){e[r]=t>>>24&255,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=255&t}function lD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function dD(e,t){return e[t]}function uD(e,t,r){return(new TextDecoder).decode(function(e,t,r){return e.slice(t,t+r)}(e,t,r))}var hD=0,pD=2654435769,mD=16,fD=2,_D=7;function gD(e,t){let r=new sD,i=function(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&void 0!==arguments[4]?arguments[4]:2e3,encryption:arguments.length>5&&void 0!==arguments[5]?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&void 0!==arguments[6]?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:r,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:i,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}(t,e,hD);hD=hD+1&2147483647,r.writeInt32(0),r.writeInt32(i.version),r.writeByte(i.encryption);let o=(new TextEncoder).encode(i.d2);r.writeInt32(o.length+4),o&&r.writeBytes(o),r.writeByte(i.uinType);let n=(new TextEncoder).encode(i.uin);r.writeInt32(n.length+4),n.length&&r.writeBytes(n);let a=new sD;a.writeInt32(0),a.writeInt32(i.reqHead.seqNumber),a.writeInt32(i.reqHead.appId),a.writeByte(i.reqHead.appId>>>24&255),a.writeByte(i.reqHead.appId>>>16&255),a.writeByte(i.reqHead.appId>>>8&255),a.writeByte(255&i.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(i.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let c=(new TextEncoder).encode(i.reqHead.serviceCmd);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let l=(new TextEncoder).encode(i.reqHead.cookie);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let d=(new TextEncoder).encode(i.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(i.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(i.reqHead.clientVersionInfo);a.writeInt16(h.length+2),h.length&&a.writeBytes(h);let p=a.length;a.data[0]=p>>>24&255,a.data[1]=p>>>16&255,a.data[2]=p>>>8&255,a.data[3]=255&p,BD(e)&&(e=(new TextEncoder).encode(e)),a.writeInt32(e.length+4),e.length&&a.writeBytes(e);let m=new Uint8Array(a.data),f=null;1===i.encryption?f=(new TextEncoder).encode(i.uin):2===i.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let r=e.length,i=(r+1+fD+_D)%8;i&&(i=8-i);let o=r+1+fD+_D+i,n=new Uint8Array(o),a=0,s=new Uint8Array(8),c=new Uint8Array(8),l=new Uint8Array(8),d=0;s[0]=248&Math.floor(256*Math.random())|i,d=1;for(let h=0;h<i;h++)s[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<fD;)if(d<8&&(s[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){ED(s,t,c,l,n,a),a+=8,d=0;for(let e=0;e<8;e++)l[e]=n[a-8+e]}let u=0;for(;u<r;)if(d<8&&(s[d]=e[u],d+=1,u+=1),8===d){ED(s,t,c,l,n,a),a+=8,d=0;for(let e=0;e<8;e++)l[e]=n[a-8+e]}for(let h=0;h<_D;)if(d<8&&(s[d]=0,d+=1,h+=1),8===d){ED(s,t,c,l,n,a),a+=8,d=0;for(let e=0;e<8;e++)l[e]=n[a-8+e]}return n}(m,f)),r.writeBytes(m);let _=new Uint8Array(r.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function ED(e,t,r,i,o,n){for(let a=0;a<8;a++)e[a]^=i[a];!function(e,t,r,i){let o=lD(e,0),n=lD(e,4),a=[];for(let c=0;c<4;c++)a[c]=lD(t,4*c);let s=0;for(let c=0;c<mD;c++)s+=pD,s>>>=0,o+=(n<<4)+a[0]^n+s^(n>>>5)+a[1],o>>>=0,n+=(o<<4)+a[2]^o+s^(o>>>5)+a[3],n>>>=0;cD(r,o,i),cD(r,n,i+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=r[a];for(let a=0;a<8;a++)r[a]=e[a]}var vD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},yD=e=>Number(e)<14e8,TD=function(e,t){let r;r=Cw||(yD(e)?Uw:xw);let i=Math.floor(Math.random()*Yb(2,31));return"".concat(r,"/v5/AVQualityReportSvc/C2S?random=").concat(i,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},ID="unknown";function AD(){if("unknown"!==ID)return ID;let{userAgent:e,connection:t}=navigator,r=(e.match(/NetType\/\S+/)||[])[0]||"";r=r.toLowerCase().replace("nettype/",""),"3gnet"===r&&(r="3g");let i=t&&t.type&&t.type.toLowerCase(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===o&&(o="2g"),i&&(ID=SD(i,o)),ID}function SD(e,t){if(Gw[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function RD(e){ID=SD(e)}function bD(){return Gw[AD()]}function wD(e,t){for(let r of Reflect.ownKeys(t))if("constructor"!==r&&"prototype"!==r&&"name"!==r){let i=Object.getOwnPropertyDescriptor(t,r)||"";Object.defineProperty(e,r,i)}return e}function CD(e){return DD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function DD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function ND(e){return 4*kD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function kD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var OD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},MD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},LD=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 r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function PD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:PD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function xD(e){return e>8?3e4:1e3*PD(e)}function UD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var VD=e=>"function"==typeof e,FD=e=>void 0===e,BD=e=>"string"==typeof e,HD=e=>"number"==typeof e,WD=e=>"boolean"==typeof e,jD=e=>"object"===UD(e),GD=e=>"array"===UD(e),zD=e=>UD(e)==="MediaStreamTrack".toLowerCase(),KD=e=>e.isRemote,qD=e=>"promise"===UD(e),YD=e=>VD(e)&&e.prototype.constructor===e,JD=e=>YD(e)?e.prototype.constructor.name:"",XD="undefined"!=typeof AudioWorkletNode,$D="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function QD(e){return new Promise(((t,r)=>{let i=[];e.forEach((o=>{o.then(t).catch((t=>{i.push(t),i.length===e.length&&r(i)}))}))}))}function ZD(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var eN=e=>+e<10?"0".concat(e):e,tN=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let r=t.split("."),i=eN(r[1])+eN(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),"".concat(r.join("."),".").concat(i)},rN=Object.prototype.hasOwnProperty;function iN(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(LD(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(rN.call(e,t))return!1;return!0}return!1}function oN(e,t){return{userId:t,hasAudio:!!(e&oC),hasVideo:!!(e&tC),hasAuxiliary:!!(e&iC),hasSmall:!!(e&rC),audioMuted:!!(e&nC),videoMuted:!!(e&aC),audioAvailable:!(!(e&oC)||e&nC),videoAvailable:!(!(e&tC)||e&aC)}}function nN(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!FD(e.username)&&!FD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",FD(e.credentialType)||(t.credentialType=e.credentialType)),t}function aN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!BD(e))return 0;let r=e.split(".");return t?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var sN=function(e,t,r,i){if(!jD(e)||!jD(t))return 0;let o,n=0,a=Object.keys(t);for(let s=0,c=a.length;s<c;s++)if(o=a[s],!(FD(t[o])||r&&r.includes(o)))if(jD(e[o])&&jD(t[o]))n+=sN(e[o],t[o],r,i);else{if(i&&i.includes(t[o]))continue;e[o]!==t[o]&&(e[o]=cN(t[o]),n+=1)}return n};function cN(e){if(GD(e)){let t=[];return e.forEach(((e,r)=>{t[r]=cN(e)})),t}if(jD(e)){let t={};return Object.keys(e).forEach((r=>{t[r]=cN(e[r])})),t}return e}var lN=e=>{let t=[];if(GD(e))t=[...e];else if(BD(e)){let r=document.getElementById(e);r&&t.push(r)}else e&&t.push(e);return t},dN=e=>BD(e)?document.getElementById(e):e,uN=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),r=e.getFullYear(),i=e.getMonth()+1,o=e.getDate(),n=t(e.getHours()),a=t(e.getMinutes()),s=t(e.getSeconds());return"".concat(r,"/").concat(i,"/").concat(o," ").concat(n,":").concat(a,":").concat(s)})(new Date);function hN(e,t){let{keysToInclude:r,keysToExclude:i}=t;try{if(GD(e))return"[".concat(e.map((e=>hN(e,{keysToInclude:r,keysToExclude:i}))).join(","),"]");if(!LD(e)||!GD(r)&&!GD(i))return JSON.stringify(e);let t={},o=new Set(r),n=new Set(i);return Object.keys(e).forEach((a=>{(0===n.size&&o.has(a)||0===o.size&&!n.has(a))&&(t[a]=LD(e[a])||GD(e[a])?JSON.parse(hN(e[a],{keysToExclude:i,keysToInclude:r})):e[a])})),JSON.stringify(t)}catch(RC){return"{}"}}function pN(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=[];return Object.keys(e).forEach((i=>{t===e[i]&&r.push(i)})),hN(e,{keysToInclude:r})}function mN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var fN=()=>{var e,t,r,i;return null!=(e=window.screen)&&e.orientation?!(null==(i=null==(r=null==(t=window.screen)?void 0:t.orientation)?void 0:r.type)||!i.includes("portrait")):0===window.orientation||180===window.orientation},_N=e=>ow(void 0,null,(function*(){return new Promise(((t,r)=>{let i;if(BD(e))i=new Image,i.crossOrigin="anonymous",i.src=e;else if(i=e,i.complete)return void t(i);i.onload=()=>t(i),i.onerror=()=>{r(new pw({code:uw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),gN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},EN=e=>(Object.keys(e).forEach((t=>{HD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(LD(e[t])||GD(e[t]))&&EN(e[t])})),e);function vN(e,t){return new Promise((r=>{let i=setTimeout(r,e);t&&t(i)}))}function yN(e,t){let r=null;return function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];return r||(r=e.apply(t||this,o),r.finally((()=>r=null)),r)}}function TN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function IN(e){var t;try{let{width:r,height:i,frameRate:o,sampleRate:n,sampleSize:a,channelCount:s}=null==(t=e.getSettings)?void 0:t.call(e),c=e.kind===$w.AUDIO?"".concat(n,"x").concat(a,"@").concat(s):"".concat(r,"x").concat(i,"@").concat(o),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(l)}catch(Aw){return""}}function AN(e,t){return e.width*e.height==t.width*t.height?1:fN()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function SN(e){return 90===e||270===e}function RN(e){return ow(this,null,(function*(){return new Promise(((t,r)=>{let i=document.createElement("video");i.crossOrigin="anonymous",i.src=e,i.muted=!0,i.loop=!0,i.playsInline=!0,i.play().then((()=>t(i))),i.onerror=()=>{r(i.error)}}))}))}function bN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if("object"!=typeof e||null===e)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let r=[];return t.set(e,r),e.forEach(((e,i)=>{r[i]=bN(e,t)})),r}if("[object Object]"===Object.prototype.toString.call(e)){let r={};return t.set(e,r),Reflect.ownKeys(e).forEach((i=>{r[i]=bN(e[i],t)})),r}return e}var wN=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(wN||{});function CN(e,t,r,i){try{let o=function(e,t,r,i){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:r};return FD(i)||(o=$b(Xb({},o),{gzip:+i})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(o)}}}(e,t,r,i);return gD(aD(o),r)}catch(iM){return JSON.stringify(e)}}function DN(e,t){let r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}function NN(e){return(65535&e)>>>0}function kN(e){return(4294901760&e)>>>0}function ON(e){let t=function(e){try{let t={},r=0;t.totalLength=lD(e,r),r+=4,t.version=lD(e,r),r+=4,t.encryption=dD(e,r),r+=1,t.uinType=dD(e,r),r+=1,t.uinLength=lD(e,r),r+=4,t.uin=t.uinLength>4?uD(e,r,t.uinLength-4):"",r+=t.uinLength-4;let i=e.slice(r);if(2===t.encryption){e=function(e,t){let r=0,i=new Uint8Array(8).fill(0),o=new Uint8Array(e.slice(0,8)),n=MN(o,t),a=7&n[0],s=e.length-1-a-fD-_D,c=new Uint8Array(s),l=0,d=i,u=e.slice(0,8);r=8;let h=1;h+=a;for(let m=1;m<=fD;)if(h<8)h++,m++;else if(8===h){let i=LN(e,r,d,u,n,t);d=i.ivPreCrypt,u=i.ivCurCrypt,n=i.debiBuf,r=i.bufPos,h=0}let p=s;for(;p>0;)if(h<8)c[l++]=n[h]^d[h],h++,p--;else if(8===h){let i=LN(e,r,d,u,n,t);d=i.ivPreCrypt,u=i.ivCurCrypt,n=i.debiBuf,r=i.bufPos,h=0}for(let m=1;m<=_D;)if(h<8)n[h],d[h],h++,m++;else if(8===h){if(r>=e.length)break;let i=LN(e,r,d,u,n,t);if(!i.success)break;d=i.ivPreCrypt,u=i.ivCurCrypt,n=i.debiBuf,r=i.bufPos,h=0}return c}(i,new Uint8Array(16).fill(0)),t.decrypted=!0,r=0}else e=i,r=0;return t.rspHeadLength=lD(e,r),r+=4,t.seqNo=lD(e,r),r+=4,t.retCode=lD(e,r),r+=4,t.retStrLength=lD(e,r),r+=4,t.retStr=t.retStrLength?uD(e,r,t.retStrLength-4):"",r+=t.retStrLength-4,t.serviceCmdLength=lD(e,r),r+=4,t.serviceCmd=t.serviceCmdLength?uD(e,r,t.serviceCmdLength-4):"",r+=t.serviceCmdLength-4,t.cookieLength=lD(e,r),r+=4,t.cookie=t.cookieLength?uD(e,r,t.cookieLength-4):"",r+=t.cookieLength-4,t.flag=lD(e,r),r+=4,t.busiBuffLength=lD(e,r),r+=4,t.busiBuff=t.busiBuffLength?uD(e,r,t.busiBuffLength-4):"",r+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function MN(e,t){let r=e[0]<<24|e[1]<<16|e[2]<<8|e[3],i=e[4]<<24|e[5]<<16|e[6]<<8|e[7];r>>>=0,i>>>=0;let o=pD*mD>>>0;for(let n=0;n<mD;n++)i-=(r<<4)+t[2]^r+o^(r>>>5)+t[3],i>>>=0,r-=(i<<4)+t[0]^i+o^(i>>>5)+t[1],r>>>=0,o-=pD,o>>>=0;return new Uint8Array([r>>>24&255,r>>>16&255,r>>>8&255,255&r,i>>>24&255,i>>>16&255,i>>>8&255,255&i])}function LN(e,t,r,i,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(i),s=e.slice(t,t+8),c=new Uint8Array(8);for(let l=0;l<8;l++)c[l]=o[l]^s[l];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:MN(c,n),bufPos:t+8}}var PN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function xN(e){let{url:t,body:r,method:i="POST",timeout:o,priority:n}=e;return new Promise(((e,a)=>{if("fetch"in window)return fetch(t,{method:i,body:r,priority:n}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:ON(new Uint8Array(e))||(PN?PN.decode(e):e)}))))))).then(e,a);let s=new XMLHttpRequest;s.onreadystatechange=()=>{if(4===s.readyState)if(s.status>=200&&s.status<300)try{let t=JSON.parse(s.response);e({data:t})}catch(nM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(i,t,!0),s.send(r)}))}function UN(e){return ow(this,null,(function*(){let t=ZD(),r=JSON.stringify(e);try{if(!CompressionStream||r.length<=2800)return r;let e=new Blob([r],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),i=yield(yield(yield new Response(e)).blob()).arrayBuffer();return qO.debug("compressJSON ".concat(r.length," -> ").concat(i.byteLength," ").concat(ZD()-t,"ms")),i}catch(RC){return r}}))}var VN=Object.prototype.hasOwnProperty,FN=e=>"function"==typeof e,BN=e=>e.isRemote,HN=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 r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};var WN=function(e){let{retryFunction:t,settings:r,onError:i,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=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}=r,h=0,p=-1,m=0,f=(e,r)=>ow(this,null,(function*(){let l=s||this;try{let r=yield t.apply(l,c);h>0&&a&&a.call(this,h),h=0,e(r)}catch(cL){let a=()=>{clearTimeout(p),h=0,m=2,r(cL)},s=()=>{2!==m&&h<(FN(d)?d():d)?(h++,m=1,FN(o)&&o.call(this,h,a),p=window.setTimeout((()=>{p=-1,f(e,r)}),FN(u)?u(h):u)):(a(),FN(n)&&n.call(this,cL))};FN(i)?i.call(this,{error:cL,retry:s,reject:r,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(f)}},jN=class{constructor(e){rw(this,"userId"),rw(this,"remoteUserId"),rw(this,"id"),rw(this,"sdkAppId"),rw(this,"type"),rw(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof 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 r=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(r?"|".concat(r):"","]")),qO.log(e,t,void 0===this.userId||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(HN(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(VN.call(e,t))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(4,t)}},GN={};Zb(GN,{ANDROID_VERSION:()=>ik,CHROME_MAJOR_VERSION:()=>cO,CHROME_VERSION:()=>lO,EDGE_VERSION:()=>dk,EDG_MAJOR_VERSION:()=>pk,EDG_VERSION:()=>hk,ELECTRON_MAJOR_VERSION:()=>dO,FIREFOX_MAJOR_VERSION:()=>ck,FIREFOX_VERSION:()=>sk,HUAWEI_VERSION:()=>Yk,IE_VERSION:()=>Sk,IOS_MAIN_VERSION:()=>EO,IOS_VERSION:()=>fO,IPADQQB_VERSION:()=>Pk,IS_ANDROID:()=>rk,IS_ANDROID_WEBVIEW:()=>mO,IS_ANY_SAFARI:()=>hO,IS_CHROME:()=>aO,IS_CHROME_OS:()=>Fk,IS_CHROMIUM_BASE:()=>nO,IS_DESKTOP_IOS_CHROME:()=>IO,IS_EDG:()=>uk,IS_EDGE:()=>lk,IS_ELECTRON:()=>Wk,IS_FIREFOX:()=>ak,IS_HEADLESS_CHROME:()=>sO,IS_HONOR:()=>qk,IS_HUAWEI:()=>Kk,IS_HUAWEIBROWSER:()=>zk,IS_IE:()=>Ak,IS_IE8:()=>Ik,IS_IOS:()=>tk,IS_IOS_13_OR_14:()=>TO,IS_IOS_15_1:()=>yO,IS_IOS_CHROME:()=>oO,IS_IPAD:()=>$N,IS_IPADQQB:()=>Lk,IS_IPAD_PRO:()=>QN,IS_IPHONE:()=>ZN,IS_IPOD:()=>ek,IS_LINUX:()=>Vk,IS_LOCAL:()=>AO,IS_MAC:()=>Uk,IS_MACQQB:()=>Ok,IS_MIBROWSER:()=>jk,IS_MQQB:()=>Ck,IS_NATIVE_ANDROID:()=>nk,IS_OLD_ANDROID:()=>ok,IS_OPENHARMONY:()=>tO,IS_OPPOBROWSER:()=>$k,IS_SAFARI:()=>uO,IS_SAFARI_15_1:()=>vO,IS_SAMSUNGBROWSER:()=>Jk,IS_SOGOU:()=>_k,IS_SOGOUM:()=>mk,IS_TBS:()=>Ek,IS_UCBROWSER:()=>Hk,IS_VIVOBROWSER:()=>Zk,IS_WECHAT:()=>Rk,IS_WIN:()=>xk,IS_WQQB:()=>Nk,IS_WX:()=>Bk,IS_X5MQQB:()=>wk,IS_XWEB:()=>yk,MACQQB_VERSION:()=>Mk,MI_VERSION:()=>Gk,MQQB_VERSION:()=>Dk,OPENHARMONY_VERSION:()=>rO,OPPO_VERSION:()=>Qk,SAFARI_VERSION:()=>pO,SAMSUNG_VERSION:()=>Xk,SOGOUM_VERSION:()=>fk,SOGOU_VERSION:()=>gk,TBS_VERSION:()=>vk,UA_DATA_STRING:()=>DO,USER_AGENT:()=>zN,VIVO_VERSION:()=>eO,WECHAT_VERSION:()=>bk,WQQB_VERSION:()=>kk,XWEB_VERSION:()=>Tk,browserInfo:()=>RO,getBrowserCoreNumber:()=>UO,getBrowserInfo:()=>bO,getChromeMajorVersion:()=>iO,getDeviceModel:()=>OO,getDeviceModelFromUA:()=>MO,getGPUInfo:()=>kO,getOSName:()=>PO,getOSNumber:()=>xO,getOSString:()=>VO,getOSType:()=>BO,getTerminalType:()=>FO,getUserAgentData:()=>NO,isLocalStorageEnabled:()=>SO,isMobile:()=>CO,isVersionLargerThan:()=>gO,isVersionSmallerThan:()=>_O});var zN="undefined"==typeof navigator?"":navigator.userAgent,KN=e=>new RegExp(e,"i").test(zN),qN=e=>{if(KN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),r=zN.match(t);if(r&&r[1])return r[1]}return""},YN=e=>{if(KN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),r=zN.match(t);if(r&&r[1])return parseFloat(r[1])}return NaN},JN=/AppleWebKit\/([\d.]+)/i.exec(zN),XN=JN?parseFloat(JN[1]):NaN,$N=KN("iPad"),QN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&KN("Macintosh"),ZN=KN("iPhone")&&!$N,ek=KN("iPod"),tk=ZN||$N||ek||QN,rk=KN("Android"),ik=function(){if(rk){let e=zN.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),r=e[2]&&parseFloat(e[2]);if(t&&r)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),ok=rk&&KN("webkit")&&ik<2.3,nk=rk&&ik<5&&XN<537,ak=KN("Firefox"),sk=qN("Firefox"),ck=YN("Firefox"),lk=KN("Edge"),dk=qN("Edge"),uk=KN("Edg"),hk=qN("Edg"),pk=YN("Edg"),mk=KN("SogouMobileBrowser"),fk=qN("SogouMobileBrowser"),_k=KN("MetaSr\\s"),gk=qN("MetaSr\\s"),Ek=KN("TBS"),vk=qN("TBS"),yk=KN("XWEB"),Tk=qN("XWEB"),Ik=KN("MSIE\\s8\\.0"),Ak=KN("MSIE\\/\\d+"),Sk=function(){if(Ak){let e=/MSIE\s(\d+)\.\d/.exec(zN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(zN)&&/rv:11.0/.test(zN)&&(t=11),t}return NaN}(),Rk=KN("(micromessenger|webbrowser)"),bk=qN("MicroMessenger"),wk=!Ek&&KN("MQQBrowser")&&KN("COVC"),Ck=!Ek&&KN("MQQBrowser")&&!KN("COVC"),Dk=Ck||wk?qN("MQQBrowser"):"",Nk=!Ek&&KN(" QQBrowser"),kk=qN(" QQBrowser"),Ok=!Ek&&KN("QQBrowserLite"),Mk=qN("QQBrowserLite"),Lk=!Ek&&KN("MQBHD"),Pk=qN("MQBHD"),xk=KN("Windows"),Uk=!tk&&KN("MAC OS X"),Vk=!rk&&KN("Linux"),Fk=KN("CrOS"),Bk=KN("MicroMessenger"),Hk=KN("UCBrowser"),Wk=KN("Electron"),jk=KN("MiuiBrowser"),Gk=qN("MiuiBrowser"),zk=KN("HuaweiBrowser"),Kk=KN("Huawei")||KN("HUAWEI"),qk=KN("Honor")||KN("HONOR"),Yk=qN("HuaweiBrowser"),Jk=KN("SamsungBrowser"),Xk=qN("SamsungBrowser"),$k=KN("HeyTapBrowser"),Qk=qN("HeyTapBrowser"),Zk=KN("VivoBrowser"),eO=qN("VivoBrowser"),tO=KN("OpenHarmony"),rO=qN("OpenHarmony"),iO=()=>YN("Chrome"),oO=KN("CriOS"),nO=KN("Chrome"),aO=!lk&&!_k&&!mk&&!Ek&&!yk&&!uk&&!Nk&&!jk&&!zk&&!Jk&&!$k&&!Zk&&nO,sO=KN("HeadlessChrome"),cO=iO(),lO=qN("Chrome"),dO=YN("Electron"),uO=!nO&&!Ck&&!wk&&!Ok&&!Lk&&KN("Safari"),hO=uO||tk,pO=qN("Version"),mO=/Android.*(wv|.0.0.0)/.test(zN),fO=(()=>{if(QN)return pO;if(tk){let e=zN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function _O(e,t){let r=e.split(".").map((e=>Number(e))),i=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(r.length,i.length);o++){let e=r[o]||0,t=i[o]||0;if(e<t)return!0;if(e>t)return!1}return!1}function gO(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=e.split(".").map((e=>Number(e))),o=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(i.length,o.length);n++){let e=i[n]||0,t=o[n]||0;if(e>t)return!0;if(e<t)return!1}return r}var EO=Number(fO.split(".")[0]),vO="15.1"===pO,yO="15.1"===fO,TO=(()=>{let e=Number(fO.split(".")[0]);return 14===e||13===e})(),IO=oO&&"11.1.1"===pO,AO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),SO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(tM){e=!1}return e}})(),RO=bO();function bO(){let e=new Map([[ak,["Firefox",sk]],[uk,["Edg",hk]],[aO,["Chrome",lO]],[oO,["ChiOS",qN("CriOS")]],[uO&&!oO,["Safari",pO]],[Ek,["TBS",vk]],[yk,["XWEB",Tk]],[Rk&&ZN,["WeChat",bk]],[Nk,["QQ(Win)",kk]],[Ck,["QQ(Mobile)",Dk]],[wk,["QQ(Mobile X5)",Dk]],[Ok,["QQ(Mac)",Mk]],[Lk,["QQ(iPad)",Pk]],[jk,["MI",Gk]],[zk,["HW",Yk]],[Jk,["Samsung",Xk]],[$k,["OPPO",Qk]],[Zk,["VIVO",eO]],[lk,["EDGE",dk]],[mk,["SogouMobile",fk]],[_k,["Sogou",gk]]]),t="unknown",r="unknown";return e.has(!0)&&([t,r]=e.get(!0)),{name:t,version:r}}var wO=null;function CO(){return wO&&"boolean"==typeof wO.mobile?wO.mobile:rk||tk||ZN||$N||tO}var DO="";function NO(){return ow(this,null,(function*(){if(wO)return wO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(wO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!DO&&(DO="UAData: ".concat(wO.platform,"/").concat(wO.platformVersion),wO.architecture&&wO.bitness&&(DO+=" ".concat(wO.architecture,"/").concat(wO.bitness)),wO.mobile&&(DO+=" mobile"),wO.model&&(DO+=" model: ".concat(wO.model.replace(/\s+/g,"/"))),wO.fullVersionList&&(DO+=" ".concat(wO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),wO}catch(yH){return null}}))}function kO(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let r=t.getExtension("WEBGL_debug_renderer_info");if(r){let e=t.getParameter(r.UNMASKED_VENDOR_WEBGL),i=t.getParameter(r.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(i)}return""}catch(yH){return""}}function OO(){return(null==wO?void 0:wO.model)||MO()||""}function MO(){let e=zN.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var LO=new Map([[rk,"Android"],[tk,"iOS"],[xk,"Windows"],[Uk,"MacOS"],[Vk,"Linux"],[Fk,"ChromeOS"]]),PO=function(){return LO.get(!0)?LO.get(!0):wO?wO.platform:"unknown"};function xO(){return xk?1:rk?2:Uk?3:tk?4:Vk?5:Fk?6:tO?7:0}function UO(){return nO?1:uO?2:ak?3:0}var VO=()=>{let e=PO();return null!=wO&&wO.platformVersion?e+="/".concat(wO.platformVersion):tk?e+="/".concat(fO):rk&&(e+="/".concat(ik)),e+="/".concat(RO.name,"/").concat(uO&&!oO?RO.version:RO.version.split(".")[0]),null!=wO&&wO.architecture&&(e+="/".concat(wO.architecture)),e};function FO(){return rk?4:ZN?2:$N?3:Uk?12:xk?5:Vk?13:tO?22:1}function BO(){return rk?"Android":ZN?"iPhone":$N?"iPad":Uk?"Mac":xk?"Windows":Vk?"Linux":"unknown"}var HO,WO=new(ew(nw(),1).default),jO=((HO=jO||{}).ROOM_DESTROY="1",HO.JOIN_START="21",HO.JOIN_SCHEDULE_SUCCESS="22",HO.JOIN_SIGNAL_CONNECTION_START="23",HO.JOIN_SIGNAL_CONNECTION_END="24",HO.JOIN_SEND_CMD="25",HO.JOIN_RECEIVED_CMD_RES="26",HO.JOIN_SUCCESS="27",HO.JOIN_FAILED="28",HO.LEAVE_START="51",HO.LEAVE_SEND_CMD="52",HO.LEAVE_SUCCESS="53",HO.PUBLISH_START="61",HO.SEND_FIRST_VIDEO_FRAME="62",HO.PUBLISH_FAILED="63",HO.SUBSCRIBE_START="81",HO.SUBSCRIBE_SUCCESS="82",HO.SUBSCRIBE_FAILED="84",HO.UNSUBSCRIBE_SUCCESS="83",HO.LOCAL_TRACK_CAPTURE_START="101",HO.LOCAL_TRACK_CAPTURE_SUCCESS="102",HO.LOCAL_TRACK_CAPTURE_FAILED="103",HO.LOCAL_TRACK_PUBLISHED="104",HO.LOCAL_TRACK_UNPUBLISHED="105",HO.LOCAL_TRACK_REPLACED="106",HO.SWITCH_DEVICE_SUCCESS="107",HO.TRACK_MUTED="108",HO.TRACK_UNMUTED="109",HO.REMOTE_TRACK_SUBSCRIBED="110",HO.REMOTE_TRACK_UNSUBSCRIBED="111",HO.LOCAL_TRACK_RECAPTURE="112",HO.LOCAL_AUDIO_STARTED="113",HO.LOCAL_AUDIO_STOPPED="114",HO.REMOTE_AUDIO_STARTED="115",HO.REMOTE_AUDIO_STOPPED="116",HO.PLAY_TRACK_START="151",HO.PLAYER_STATE_CHANGED="152",HO.VIDEO_LOADED_DATA="153",HO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",HO.AUDIO_CONTEXT_LONG_SUSPENDED="155",HO.SIGNAL_CONNECTION_STATE_CHANGED="201",HO.PEER_CONNECTION_STATE_CHANGED="202",HO.SINGLE_CONNECTION_STAT="203",HO.SPC_RECONNECTED="204",HO.HEARTBEAT_REPORT="251",HO.RECEIVED_PUBLISHED_USER_LIST="252",HO.REMOTE_PUBLISH_STATE_CHANGED="253",HO.AUDIO_LEVEL_INTERVAL="260",HO.NETWORK_QUALITY="261",HO.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",HO.QUALITY_LIMITATION_CHANGED="263",HO.LOG="264",HO.AUDIO_PROCESSOR_DEBUG="265",HO.SSO_SWITCH="266",HO.SWITCH_ROOM_START="401",HO.SWITCH_ROOM_SUCCESS="407",HO.SWITCH_ROOM_FAILED="408",HO),GO=jO,zO=new class{constructor(){rw(this,"enable",!1),rw(this,"ssoFailCount",0),WO.on("22",(e=>{let{schedule:t}=e;var r;null!=(r=null==t?void 0:t.config)&&r.sso&&WO.emit("266",{enable:!0})})),WO.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&WO.emit("266",{enable:!1})}},KO=class e{constructor(){rw(this,"_isEnableUploadLog",!0),rw(this,"_localJoinedUser",new Map),rw(this,"_queue",[]),rw(this,"_timeoutId",-1),rw(this,"_logLevel",1),rw(this,"_logLevelToUpload",2),!Rw&&!bw&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){WO.on(GO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var r;null!=(r=null==t?void 0:t.config)&&r.logLevelToUpload&&Hw[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),WO.on(GO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),WO.once(GO.JOIN_FAILED,(()=>{this.startUpload()})),WO.on(GO.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()),5e3)}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 r=this._queue[t];if(r.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:i,sdkAppId:o}=t;e.map.has(i)?e.map.get(i).logs.push(r):e.map.set(i,{userId:i,sdkAppId:o,logs:[r]})}));else if(BD(r.userId)&&HD(r.sdkAppId)){let{userId:t,sdkAppId:i}=r;e.map.has(t)?e.map.get(t).logs.push(r):e.map.set(t,{userId:t,sdkAppId:i,logs:[r]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return ow(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:r,sdkAppId:i,logs:o}=t[e],n={timestamp:_w(),sdkAppId:String(i),userId:r,version:Tw,log:o.map((e=>e.log)).join("\n")},a=JSON.stringify(n),s=zO.enable?CN(n,2002,i):a;yield this.uploadLogWithRetry(s,i,s instanceof Uint8Array,a),o.forEach((e=>e.uploaded=!0))}}catch(iM){}let r=t.filter((e=>!e.uploaded));r.length>0&&(this._queue=r.concat(this._queue))}))}uploadLogWithRetry(e,t,r,i){return WN({retryFunction:()=>xN({url:TD(t,Fw.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{r&&"ok"!==e.data&&(zO.handleUploadFailed(),this.uploadLogWithRetry(i,t,!1,i))})),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(fw()),"[".concat(gw(t),"] <").concat(Hw[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){FD(Hw[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(BD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Aw){return""}}addLogToQueue(e,t){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,n={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:i,sdkAppId:o,forAllJoinedClients:r};WO.emit(GO.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,r){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],o=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var a;if(r.unshift(this.getPrefix(t)),this.addLogToQueue(t,r,i,o,n),t<this._logLevel)return;let s=(null==(a=Hw[t])?void 0:a.toLowerCase())||"info";e.PRINT_LOG_TAG?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...r):console[s](...r)}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(4,t)}createLogger(e){return new jN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Hw[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};rw(KO,"PRINT_LOG_TAG",!(tk||rk||sO));var qO=new KO,YO=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)}))},JO=new class{constructor(){rw(this,"_prefix","TRTC"),rw(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){SO()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix))try{let t=localStorage.getItem(e);if(!t)return!1;let r=JSON.parse(t);if(r&&r.expiresIn<Date.now())return!0}catch(iM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(SO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(tM){qO.warn(tM)}}getItem(e){if(!SO())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let r=JSON.parse(t);return r&&r.expiresIn>=Date.now()?r.value:null}catch(Aw){qO.warn(Aw)}}setItem(e,t){if(SO())try{let r={expiresIn:Date.now()+zw,value:t};this._queue.set(this.getRealKey(e),r)}catch(RC){qO.warn(RC)}}deleteItem(e){if(!SO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Aw){return qO.warn(Aw),!1}}clear(){if(SO())try{localStorage.clear()}catch(tM){qO.warn(tM)}}},XO={};Zb(XO,{HTTPS_API:()=>UL,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>nP,IS_GET_CAPABILITIES_SUPPORTED:()=>oP,IS_GET_SETTINGS_SUPPORTED:()=>iP,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>rP,IS_INSERTABLE_STREAM_SUPPORTED:()=>aP,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>vP,IS_RTC_RTP_SENDER_SUPPORTED:()=>ZL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>sP,IS_SEI_SUPPORTED:()=>cP,IS_SPC_SUPPORTED:()=>$L,basis:()=>mP,capabilityCheck:()=>gP,checkSystemRequirementsInternal:()=>kL,decodeSupportStatus:()=>NL,detectVideoCodecCapabilities:()=>IP,detectVideoDecoderCapabilities:()=>SP,detectVideoEncoderCapabilities:()=>AP,encodeSupportStatus:()=>DL,getBrowserInfo:()=>TL,getDisplayResolution:()=>FL,getH264ProfileLevelIds:()=>RP,isAddTransceiverSupported:()=>XL,isBrowserSupported:()=>IL,isCanvasCaptureStreamAPISupported:()=>WL,isCanvasSmallStreamSupported:()=>jL,isGetReceiversSupported:()=>qL,isGetSendersSupported:()=>YL,isGetTransceiversSupported:()=>JL,isGetUserMediaSupported:()=>BL,isMediaDevicesSupported:()=>SL,isMediaSessionSupported:()=>uP,isMediaStreamTrackGeneratorSupported:()=>CL,isMediaStreamTrackProcessorSupported:()=>wL,isReplaceTrackSupported:()=>eP,isRequestVideoFrameCallbackSupported:()=>EP,isSIMDSupported:()=>pP,isScaleResolutionDownBySupported:()=>GL,isScreenCaptureApiAvailable:()=>ML,isSelectedCandidatePair:()=>VL,isSetParametersSupported:()=>tP,isSetSinkIdSupported:()=>LL,isSmallStreamSupported:()=>zL,isStopTransceiverSupported:()=>QL,isTRTCSupported:()=>OL,isUnifiedPlanDefault:()=>KL,isUsedInHttpProtocol:()=>bL,isWebAudioSupported:()=>HL,isWebCodecSupported:()=>dP,isWebCodecsSupported:()=>AL,isWebRTCSupported:()=>lP,isWebTransportSupported:()=>hP});var $O={};Zb($O,{AUDIO_LEVEL_SCALE:()=>jM,AudioCodecPipelineType:()=>JM,AudioDecoderDowngradeState:()=>SM,AudioPlayerMode:()=>BM,AudioType:()=>NM,BASIC_TYPE:()=>KM,BannedReason:()=>HM,CONNECTION_CLOSED_REASON:()=>uM,CheckPermissionType:()=>tL,ClientEvent:()=>hM,CodecType:()=>XM,ConnectionEvent:()=>dM,ConnectionState:()=>AM,DECODE_FAILED_ERROR_CODE:()=>$M,DenoiserMode:()=>GM,DeviceType:()=>rL,FacingMode:()=>VM,FrameWorkType:()=>lM,LeaveReason:()=>WM,LocalTrackEvent:()=>mM,MULTI_VIDEO_DATA_TYPE:()=>LM,MediaType:()=>CM,MediaTypeLabel:()=>DM,MonitorEventId:()=>PM,MutedFlag:()=>vM,NetworkQualityValue:()=>xM,PlayerState:()=>fM,ReceiveMode:()=>UM,RemoteStreamType:()=>MM,RemoteTrackEvent:()=>EM,RoomEvent:()=>_M,SMALL_MODE:()=>eL,SceneNumber:()=>yM,StreamEvent:()=>pM,StreamType:()=>OM,SubscribeMediaType:()=>zM,TIMER_TYPE:()=>ZM,TRACK_ACTION:()=>wM,TRACK_KIND:()=>bM,TrackEvent:()=>gM,UserRole:()=>IM,UserRoleNumber:()=>TM,VideoCodec:()=>qM,VideoCodecPipelineType:()=>YM,VideoContentHint:()=>QM,VideoDecoderDowngradeState:()=>RM,VideoPlayerMode:()=>FM,VideoType:()=>kM});var QO,ZO,eM,tM,rM,iM,oM,nM,aM,sM,cM,lM=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(lM||{}),dM=((cM=dM||{}).TRACK_ADDED="track-added",cM.TRACK_UPDATED="track-updated",cM.TRACK_SUBSCRIBED="track-subscribed",cM.STREAM_ADDED="stream-added",cM.STREAM_REMOVED="stream-removed",cM.STREAM_UPDATED="stream-updated",cM.STREAM_PUBLISHED="stream-published",cM.STREAM_SUBSCRIBED="stream-subscribed",cM.STREAM_UNSUBSCRIBED="stream-unsubscribed",cM.STATE_CHANGED="state-changed",cM.ERROR="error",cM.CONNECTION_STATE_CHANGED="connection-state-changed",cM.FIREWALL_RESTRICTION="firewall-restriction",cM.SEI_MESSAGE="sei-message",cM.CLOSED="closed",cM),uM=(e=>(e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e))(uM||{}),hM=((sM=hM||{}).STREAM_ADDED="stream-added",sM.STREAM_REMOVED="stream-removed",sM.STREAM_UPDATED="stream-updated",sM.STREAM_SUBSCRIBED="stream-subscribed",sM.CONNECTION_STATE_CHANGED="connection-state-changed",sM.PEER_JOIN="peer-join",sM.PEER_LEAVE="peer-leave",sM.MUTE_AUDIO="mute-audio",sM.MUTE_VIDEO="mute-video",sM.UNMUTE_AUDIO="unmute-audio",sM.UNMUTE_VIDEO="unmute-video",sM.CLIENT_BANNED="client-banned",sM.NETWORK_QUALITY="network-quality",sM.AUDIO_VOLUME="audio-volume",sM.SEI_MESSAGE="sei-message",sM.ERROR="error",sM),pM=((aM=pM||{}).PLAYER_STATE_CHANGED="player-state-changed",aM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",aM.CONNECTION_STATE_CHANGED="connection-state-changed",aM.DEVICE_AUTO_RECOVERED="device-auto-recovered",aM.ERROR="error",aM),mM=((nM=mM||{}).DEVICE_AUTO_RECOVERED="1",nM.DEVICE_RECOVER_FAILED="5",nM.DEVICE_CHANGED="2",nM.ERROR="3",nM.PUBLISH_STATE_CHANGED="4",nM.ENCODE_FAILED="6",nM.TRACK_ENDED="7",nM.RENDER="render",nM),fM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(fM||{}),_M=((oM=_M||{}).PEER_JOIN="peer-join",oM.PEER_LEAVE="peer-leave",oM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",oM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",oM.BANNED="banned",oM.NETWORK_QUALITY="network-quality",oM.AUDIO_VOLUME="audio-volume",oM.SEI_MESSAGE="sei-message",oM.ERROR="error",oM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",oM.REMOTE_PUBLISHED="remote-published",oM.REMOTE_UNPUBLISHED="remote-unpublished",oM.FIREWALL_RESTRICTION="firewall-restriction",oM.HEARTBEAT_REPORT="heartbeat-report",oM.CUSTOM_MESSAGE="custom-message",oM.LAYER_DATA="layerData",oM.FIRST_VIDEO_FRAME="first-video-frame",oM.DUMP="dump",oM.AUDIO_FRAME="audio-frame",oM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",oM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",oM.NTP_TIME_UPDATED="ntp-time-updated",oM),gM=(e=>(e.PLAYER_STATE_CHANGED="player-state-changed",e.MUTE="mute",e.UNMUTE="unmute",e.ERROR="error",e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",e.FIRST_VIDEO_FRAME="first-video-frame",e.VIDEO_SIZE_CHANGED="video-size-changed",e))(gM||{}),EM=((iM=EM||{}).DECODE_FAILED="decode-failed",iM.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",iM.REMOTE_PUBLISH_CHANGED="remote-publish-changed",iM.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",iM),vM=((rM=vM||{})[rM.VIDEO=1]="VIDEO",rM[rM.SMALL=2]="SMALL",rM[rM.AUX=4]="AUX",rM[rM.AUDIO=8]="AUDIO",rM[rM.VIDEO_MUTE=16]="VIDEO_MUTE",rM[rM.AUX_MUTE=32]="AUX_MUTE",rM[rM.AUDIO_MUTE=64]="AUDIO_MUTE",rM),yM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(yM||{}),TM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(TM||{}),IM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(IM||{}),AM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(AM||{}),SM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(SM||{}),RM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(RM||{}),bM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(bM||{}),wM=(e=>(e.ADD="add",e.REMOVE="remove",e))(wM||{}),CM=(e=>(e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e))(CM||{}),DM={1:"audio",2:"auxVideo",4:"video"},NM=((tM=NM||{})[tM.opus=111]="opus",tM),kM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(kM||{}),OM=(e=>(e.Big="big",e.Small="small",e))(OM||{}),MM=(e=>(e.Main="main",e.Aux="auxiliary",e))(MM||{}),LM=(e=>(e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e))(LM||{}),PM=((eM=PM||{})[eM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",eM[eM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",eM[eM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",eM[eM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",eM[eM.MUTE_AUDIO=32772]="MUTE_AUDIO",eM[eM.MUTE_VIDEO=32773]="MUTE_VIDEO",eM[eM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",eM[eM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",eM[eM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",eM[eM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",eM[eM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",eM[eM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",eM[eM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",eM[eM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",eM[eM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",eM[eM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",eM[eM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",eM[eM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",eM[eM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",eM[eM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",eM[eM.JOIN=32788]="JOIN",eM[eM.LEAVE=32789]="LEAVE",eM[eM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",eM[eM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",eM[eM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",eM[eM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",eM[eM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",eM[eM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",eM[eM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",eM[eM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",eM[eM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",eM[eM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",eM[eM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",eM[eM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",eM[eM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",eM[eM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",eM[eM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",eM[eM.PUBLISH_AUX=32805]="PUBLISH_AUX",eM[eM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",eM[eM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",eM[eM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",eM[eM.VIDEO_DECODER=4005]="VIDEO_DECODER",eM),xM=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e))(xM||{}),UM=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e))(UM||{}),VM=(e=>(e.user="user",e.environment="environment",e))(VM||{}),FM=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e))(FM||{}),BM=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(BM||{}),HM=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(HM||{}),WM=((ZO=WM||{})[ZO.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",ZO[ZO.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",ZO[ZO.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",ZO[ZO.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",ZO[ZO.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",ZO[ZO.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",ZO[ZO.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",ZO[ZO.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",ZO[ZO.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",ZO),jM=1e8,GM=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(GM||{}),zM=class{constructor(){rw(this,"mediaType",0)}set audio(e){e?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(e){e?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(e){e?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(e){e?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},KM=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(KM||{}),qM=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(qM||{}),YM=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(YM||{}),JM=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(JM||{}),XM=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(XM||{}),$M=((QO=$M||{})[QO.SUCCESS=0]="SUCCESS",QO[QO.FAILED=1]="FAILED",QO[QO.WEBCODEC_INIT=2]="WEBCODEC_INIT",QO[QO.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",QO[QO.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",QO[QO.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",QO[QO.WASM_INIT=6]="WASM_INIT",QO[QO.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",QO[QO.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",QO[QO.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",QO[QO.TEST=10]="TEST",QO[QO.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",QO),QM=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(QM||{}),ZM=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(ZM||{}),eL=(e=>(e.CANVAS="canvas",e.API="api",e))(eL||{}),tL=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(tL||{}),rL=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(rL||{}),iL={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_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"},oL={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' is a required param when calling ").concat(i,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:r,fnName:i,value:o}=e,n="".concat(t||r.name),a="";return a=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(i,"(), received type: ").concat(UD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' cannot be '").concat(o,"' when calling ").concat(i,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:r,fnName:i,value:o}=e,n="".concat(t||r.name),a="".concat(r.instanceOf.name||r.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(i,"(), received type: ").concat(UD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' must be one of ").concat(r.values.join("|")," when calling ").concat(i,"(), received: ").concat(o,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:r,fnName:i,value:o}=e;return"the min value of ".concat(t||r.name," is ").concat(r.min,", received: ").concat(o,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:r,fnName:i,value:o}=e;return"the max value of ".concat(t||r.name," is ").concat(r.max,", received: ").concat(o,".")},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:r}=e;return"Failed to join room - ".concat(t," code: ").concat(r)},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/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:r,streamType:i}=e;return"failed to subscribe ".concat(r," ").concat(i," 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 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:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' cannot be less than 0 when calling ").concat(i,"().")},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:r}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(r,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:r,type:i}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(r,"(), received: ").concat(i,".")},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:r}=e;return"an error was caught in ".concat(t,".on('").concat(r,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"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_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:r,timesInSecond:i,maxSizeInSecond:o}=e;return"api ".concat(r," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(o," bytes"):i," 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,"()")},nL=(e,t)=>t?"".concat(Lw,"/").concat(e,"/").concat(t):"".concat(Lw,"/").concat(e,"/index.html"),aL=()=>{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=null==localStorage?void 0:localStorage.getItem(Vw);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let r=window.TRTC_ERROR_INFO,i=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:i}}return{}};function sL(e){let{key:t,data:r,link:i,addDocLink:o=!0}=e,n="",a="",s="";VD(oL[t])?n=oL[t](r):BD(oL[t])&&(n=oL[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=aL();i?s="".concat(i.className,".html#").concat(i.fnName):l&&l[t]&&(VD(l[t])?s=l[t](r):BD(l[t])&&(s=l[t]));let d=n;return MD()&&(c&&c[t]&&(VD(c[t])?a=c[t](r):BD(c[t])&&(a=c[t])),a&&(d=o?"".concat(a,"\n请查看文档: ").concat(nL("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=n)),o&&(d+=" \nRefer to: ".concat(nL("en",s),"\n")),d}var cL,lL=ew(lw(),1),dL=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];rw(this,"countMap",new Map),rw(this,"distributionMap",new Map),rw(this,"version"),rw(this,"log",qO.createLogger({id:"kv"})),e&&(WO.on("102",(e=>{let{track:t,cost:r}=e;this.addSuccessEvent({key:t.kind===$w.AUDIO?501700:511700,cost:r})})),WO.on("103",(e=>{let{track:t,error:r}=e;this.addFailedEvent({key:t.kind===$w.AUDIO?501700:511700,error:r})})),WO.on("266",(e=>{let{enable:t}=e;this.log.info("".concat(t?"enable":"disable"," sso")),t?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})})))}getReportData(e,t){let r={msg_sdk_basic_info:{uint32_sdk_version:gN(this.version||Tw),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,r]=e;return{uint32_key:t,uint32_count:r}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,r]=e;return{uint32_key:t,distribution_items:[...r.entries()].map((e=>{let[t,r]=e;return{uint32_item_key:t,uint32_item_value:r}}))}})),str_user_sig:e,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),r}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:r=!1}=e;this.isCountKey(t)?r&&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:r,useUV:i=!0}=e;var o;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(i&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let n=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map;n.set(r,(n.get(r)||0)+1),this.distributionMap.set(t,n)}addNumber(e){let{key:t,value:r,split:i=100,useUV:o=!1,max:n=5e3}=e;var a;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(o&&this.countMap.has(t))return;r>n&&(r=n),this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(a=this.distributionMap)?void 0:a.get(t))||new Map,c=0;if(HD(i))c=Math.floor(r/i);else for(let l=i.length-1;l>0;l--)if(r>i[l]){c=l;break}s.set(c,(s.get(c)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:r,timeKey:i,split:o}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),r)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:i||t+100,value:r,split:o}):i||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:r}=e;if(!t)return;let i=uw.UNKNOWN;r&&(HD(r)?i=r:(!FD(r.extraCode)||!FD(r.code))&&(i=r.extraCode||r.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(i),useUV:!1})}},uL=(e=>(e[e.enterRoom=500700]="enterRoom",e[e.exitRoom=500701]="exitRoom",e[e.switchRole=500702]="switchRole",e[e.destroy=500703]="destroy",e[e.startLocalAudio=500704]="startLocalAudio",e[e.updateLocalAudio=500705]="updateLocalAudio",e[e.stopLocalAudio=500706]="stopLocalAudio",e[e.startLocalVideo=500707]="startLocalVideo",e[e.updateLocalVideo=500708]="updateLocalVideo",e[e.stopLocalVideo=500709]="stopLocalVideo",e[e.startScreenShare=500710]="startScreenShare",e[e.updateScreenShare=500711]="updateScreenShare",e[e.stopScreenShare=500712]="stopScreenShare",e[e.startRemoteVideo=500713]="startRemoteVideo",e[e.updateRemoteVideo=500714]="updateRemoteVideo",e[e.stopRemoteVideo=500715]="stopRemoteVideo",e[e.muteRemoteAudio=500716]="muteRemoteAudio",e[e.setRemoteAudioVolume=500717]="setRemoteAudioVolume",e[e.use=500718]="use",e[e.switchRoom=500719]="switchRoom",e[e.sendSEIMessage=5e5]="sendSEIMessage",e[e.sendCustomMessage=500001]="sendCustomMessage",e))(uL||{}),hL=(e=>(e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e))(hL||{}),pL=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e))(pL||{}),mL=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e))(mL||{}),fL=((cL=fL||{})[cL.DECODER_TYPE=514700]="DECODER_TYPE",cL[cL.DECODER_HW_SW=514701]="DECODER_HW_SW",cL[cL.DECODE_RESULT=514702]="DECODE_RESULT",cL[cL.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",cL[cL.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",cL[cL.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",cL[cL.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",cL[cL.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",cL[cL.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",cL[cL.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",cL[cL.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",cL[cL.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",cL[cL.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",cL[cL.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",cL[cL.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",cL[cL.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",cL[cL.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",cL),_L=new dL(!0),gL=new dL(!1),EL=_L,vL={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},yL=new Map([[ak,["Firefox",sk]],[uk,["Edg",hk]],[aO,["Chrome",lO]],[uO,["Safari",pO]],[Ek,["TBS",vk]],[yk,["XWEB",Tk]],[Rk&&ZN,["WeChat",bk]],[Nk,["QQ(Win)",kk]],[Ck,["QQ(Mobile)",Dk]],[wk,["QQ(Mobile X5)",Dk]],[Ok,["QQ(Mac)",Mk]],[Lk,["QQ(iPad)",Pk]],[jk,["MI",Gk]],[zk,["HW",Yk]],[Jk,["Samsung",Xk]],[$k,["OPPO",Qk]],[Zk,["VIVO",eO]],[lk,["EDGE",dk]],[mk,["SogouMobile",fk]],[_k,["Sogou",gk]]]);function TL(){let e=yL.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var IL=function(){return!(Hk||lk||uk&&pk<80||ak&&ck<56)},AL=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},SL=function(){if(!navigator.mediaDevices)return bL()||qO.error(oL.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},RL=!1;function bL(){return"http:"===location.protocol&&!AO&&(RL||qO.error(sL({key:iL.NOT_SUPPORTED_HTTP})),RL=!0,!0)}var wL=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},CL=function(){return!(null==window||!window.MediaStreamTrackGenerator)},DL=function(){return ow(this,null,(function*(){var e,t,r;if(vL.detail.isH264EncodeSupported&&vL.detail.isVp8EncodeSupported)return{isH264EncodeSupported:vL.detail.isH264EncodeSupported,isVp8EncodeSupported:vL.detail.isVp8EncodeSupported,isH265EncodeSupported:vL.detail.isH265EncodeSupported};let i,o=!1,n=!1,a=!1;try{let s=new RTCPeerConnection,c=document.createElement($w.CANVAS);c.getContext("2d");let l=c.captureStream(0);return s.addTrack(l.getVideoTracks()[0],l),i=yield s.createOffer(),o=-1!==(null==(e=i.sdp)?void 0:e.toLowerCase().indexOf("h264")),n=-1!==(null==(t=i.sdp)?void 0:t.toLowerCase().indexOf("vp8")),a=-1!==(null==(r=i.sdp)?void 0:r.toLowerCase().indexOf("h265")),s.close(),{isH264EncodeSupported:o,isVp8EncodeSupported:n,isH265EncodeSupported:a}}catch(rM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},NL=function(){return ow(this,null,(function*(){var e;if(vL.detail.isH264DecodeSupported&&vL.detail.isVp8DecodeSupported)return{isH264DecodeSupported:vL.detail.isH264DecodeSupported,isVp8DecodeSupported:vL.detail.isVp8DecodeSupported,isH265DecodeSupported:vL.detail.isH265DecodeSupported};let t,r=!1,i=!1;try{let o=new RTCPeerConnection;XL()?(o.addTransceiver($w.VIDEO,{direction:"recvonly"}),t=yield o.createOffer()):t=yield o.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(r=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(i=!0);let n=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return o.close(),{isH264DecodeSupported:r,isVp8DecodeSupported:i,isH265DecodeSupported:n}}catch(iM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var kL=yN((e=>ow(void 0,null,(function*(){let t=Date.now(),r=lP(),i=SL(),o=AL();if(vL.detail.isWebRTCSupported=r,vL.detail.isMediaDevicesSupported=i,vL.detail.isWebCodecsSupported=o,vL.detail.isScreenShareSupported=ML(),vL.detail.isSmallStreamSupported=zL(),37===e)return Object.assign(vL.detail,yield function(){return ow(this,null,(function*(){return xL||(xL=new Promise((e=>ow(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!AL())return void e(t);let r=null,i=null,o=null,n=()=>{o&&clearTimeout(o),r=null,i=null};try{r=document.createElement("canvas"),i=r.getContext("2d"),r.width=320,r.height=240;let a=0,s=()=>{!i||!r||(i.fillStyle="hsl(".concat(a%360,", 50%, 50%)"),i.fillRect(0,0,r.width,r.height),i.fillStyle="white",i.font="20px Arial",i.fillText("Frame ".concat(a),10,30),a++)};o=setTimeout((()=>{n(),e(t)}),5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map((e=>ow(this,null,(function*(){let t,i={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,o)=>ow(this,null,(function*(){try{let n=new VideoEncoder({output:e=>{t(e),i.encodeSupported=!0},error:o});n.configure(e.encodeConfig),s();let a=new VideoFrame(r,{timestamp:0});n.encode(a,{keyFrame:!0}),a.close(),yield n.flush(),n.close()}catch(cM){o(cM)}}))))}catch(p){return qO.warn("".concat(e.type," encoder error:"),p),i}try{yield new Promise(((r,o)=>ow(this,null,(function*(){try{let n=new VideoDecoder({output:e=>{i.decodeSupported=!0,r(0),e.close()},error:o});n.configure(e.decodeConfig),n.decode(t),yield n.flush(),n.close()}catch(cM){o(cM)}}))))}catch(p){qO.warn("".concat(e.type," decoder error:"),p)}return i})))))).forEach((e=>{"h264"===e.type?(t.isH264EncodeSupported=e.encodeSupported,t.isH264DecodeSupported=e.decodeSupported):"vp8"===e.type&&(t.isVp8EncodeSupported=e.encodeSupported,t.isVp8DecodeSupported=e.decodeSupported)})),n(),e(t)}catch(a){n(),qO.warn("detectWebCodecsSupported failed:",a),e(t)}})))),xL)}))}()),vL.detail.isBrowserSupported=o,vL.result=i&&o,vL.result||qO.error("".concat(navigator.userAgent," ").concat(pN(vL.detail,!1))),_P(e),EL.addNumber({key:523800,value:Date.now()-t}),vL;if(vL.result&&vL.detail.isH264EncodeSupported&&vL.detail.isVp8EncodeSupported&&vL.detail.isH265EncodeSupported&&vL.detail.isH264DecodeSupported&&vL.detail.isVp8DecodeSupported&&vL.detail.isH265DecodeSupported)return vL;let n=IL(),{encode:a,decode:s}=yield function(){return ow(this,null,(function*(){let[e,t]=yield Promise.all([DL(),NL()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:c,vp8:l}=a,{h264:d}=s,{h265:u}=a,{vp8:h,h265:p}=s;if(!c||!l){let e=yield DL();qO.warn("detect encode again h264:".concat(c," vp8:").concat(l," result: ").concat(JSON.stringify(e))),c=e.isH264EncodeSupported,l=e.isVp8EncodeSupported}if(c&&d&&rk&&nO&&!yk&&!Ek&&(!$k||115!==cO)){let{encode:e,decode:t}=yield function(){return ow(this,null,(function*(){return PL||(PL=new Promise((e=>ow(this,null,(function*(){let t={encode:!1,decode:!1},r=()=>{};try{let i=document.createElement("canvas"),o=i.getContext("2d");i.width=640,i.height=480;let n=setInterval((()=>{o.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),66),a=-1,s=-1;r=()=>{clearInterval(a),clearInterval(n),clearTimeout(s),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},s=setTimeout((()=>{r(),e(t)}),2e3);let c=i.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=lL.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=lL.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),a=setInterval((()=>ow(this,null,(function*(){t.encode&&t.decode&&(r(),e(t));let[i,o]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||i.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===$w.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||o.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===$w.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(i){r(),qO.warn("detectH264Supported failed",i),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&qO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(DO)),e))),PL)}))}();c=e,d=t}return vL.result=n&&r&&i&&(c||l)&&(d||h),vL.detail.isBrowserSupported=n,vL.detail.isWebRTCSupported=r,vL.detail.isH264EncodeSupported=c,vL.detail.isVp8EncodeSupported=l,vL.detail.isH265EncodeSupported=u,vL.detail.isH264DecodeSupported=d,vL.detail.isVp8DecodeSupported=h,vL.detail.isH265DecodeSupported=p,vL.result||qO.error("".concat(navigator.userAgent," ").concat(pN(vL.detail,!1))),_P(),EL.addNumber({key:523800,value:Date.now()-t}),vL})))),OL=function(){return vL.result},ML=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},LL="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,PL=null;var xL=null;var UL=(e,t,r)=>{"http:"===location.protocol&&!AO&&(e[t]=()=>{throw new pw({code:uw.INVALID_OPERATION,message:oL.NOT_SUPPORTED_HTTP})})},VL=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(WD(e.selected)&&!e.selected)};function FL(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",r=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(r)}return e}function BL(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function HL(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r<t.length;r++)if(t[r]in window){e.isSupported=!0;break}return e.isSupported}function WL(){return"captureStream"in HTMLCanvasElement.prototype}function jL(){return!(Rk||tk||cO&&cO<63)&&!(!IL()||!WL())}function GL(){return!(cO<74||lk||EO<11||ck<46)}function zL(){return jL()||GL()}var KL=function(){if(FD(window.RTCRtpTransceiver)||!XL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:kC}),e.addTransceiver($w.AUDIO),t=!0}catch(Aw){}return null==e||e.close(),t};function qL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function YL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function JL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function XL(){return!(11===EO&&!IO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var $L=!(!XL()||nO&&cO<86);function QL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ZL="RTCRtpSender"in window;function eP(){return ZL&&"replaceTrack"in window.RTCRtpSender.prototype}function tP(){return ZL&&"setParameters"in window.RTCRtpSender.prototype&&YL()}var rP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,iP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,oP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,nP="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,aP=ZL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&iO()>=86,sP="RTCRtpScriptTransform"in window,cP=ZL&&(aP||sP),lP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function dP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return FD(window.AudioDecoder)||(e.AudioDecoder=!0),FD(window.AudioEncoder)||(e.AudioEncoder=!0),FD(window.VideoDecoder)||(e.VideoDecoder=!0),FD(window.VideoEncoder)||(e.VideoEncoder=!0),FD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function uP(){return"mediaSession"in navigator&&!FD(navigator.mediaSession.setActionHandler)}function hP(){return!FD(window.WebTransport)}function pP(){return"undefined"!=typeof WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function mP(){let e={browser:"".concat(RO.name,"/").concat(RO.version),os:PO(),displayResolution:FL(),isScreenShareSupported:ML(),isWebRTCSupported:lP(),isGetUserMediaSupported:BL(),isWebAudioSupported:HL(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:dP(),isMediaSessionSupported:uP(),isWebTransportSupported:hP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var fP="checkResult";function _P(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;JO.setItem(fP+e,{ua:navigator.userAgent,checkResult:vL})}function gP(e){bL();let t=JO.getItem(fP+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!jD(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,vL.detail)&&(vL=t.checkResult),kL(e)}function EP(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var vP="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function yP(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var TP=!1;function IP(){return ow(this,null,(function*(){var e;try{if(TP||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=xO(),r=UO();if(0===t||0===r)return;TP=!0;let i=["H264","VP8","VP9","AV1","H265"],[o,n]=yield Promise.all([AP(i),SP(i)]);o&&Object.keys(o).forEach((e=>{let i=yP(e.toLowerCase());EL.addEnum({key:513707,value:+"".concat(i).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(r),useUV:!1})})),n&&Object.keys(n).forEach((e=>{let i=yP(e.toLowerCase());EL.addEnum({key:514713,value:+"".concat(i).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(r),useUV:!1})}))}catch(tM){qO.info("detectVideoCodecCapabilities failed",tM)}}))}function AP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return ow(this,null,(function*(){let n={};try{for(let a of e){let e=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:r,bitrate:o,framerate:i}});n[a]=e}}catch(Sw){}return n}))}function SP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return ow(this,null,(function*(){let n={};try{for(let a of e){let e=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:r,bitrate:o,framerate:i}});n[a]=e}}catch(Sw){}return n}))}function RP(){let e={sender:new Set,receiver:new Set,senderHex:new Set,receiverHex:new Set};try{if(RTCRtpSender&&"function"==typeof RTCRtpSender.getCapabilities){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter((e=>"video/h264"===e.mimeType.toLowerCase())).forEach((t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1]){let t=r[1];e.senderHex.add(t);let i=parseInt(t,16);isNaN(i)||e.sender.add(i)}}}))}if(RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.getCapabilities){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter((e=>"video/h264"===e.mimeType.toLowerCase())).forEach((t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1]){let t=r[1];e.receiverHex.add(t);let i=parseInt(t,16);isNaN(i)||e.receiver.add(i)}}}))}}catch(tM){qO.warn("get H264 profile levelId failed",tM)}return e}var bP=ew(nw(),1),wP=Symbol("instance"),CP=Symbol("cacheResult"),DP=class{constructor(e,t,r){this.oldState=e,this.newState=t,this.action=r,this.aborted=!1}abort(e){this.aborted=!0,LP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},NP=class extends Error{constructor(e,t,r){super(t),this.state=e,this.message=t,this.cause=r}};var kP=new Map;function OP(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(i,o,n)=>{let a=r.action||o;if(!r.context){let r=kP.get(i)||[];kP.has(i)||kP.set(i,r),r.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let i=this;for(var o=arguments.length,n=new Array(o),c=0;c<o;c++)n[c]=arguments[c];if(r.context&&(i=PP.get("function"==typeof r.context?r.context.call(this,...n):r.context)),i.state===t)return r.sync?i[CP]:Promise.resolve(i[CP]);i.state instanceof DP&&i.state.action==r.abortAction&&i.state.abort(i);let l=null;Array.isArray(e)?0==e.length?i.state instanceof DP&&i.state.abort(i):("string"!=typeof i.state||!e.includes(i.state))&&(l=new NP(i._state,"".concat(i.name," ").concat(a," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e.join("|")))):e!==i.state&&(l=new NP(i._state,"".concat(i.name," ").concat(a," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e)));let d=e=>{if(r.fail&&r.fail.call(this,e),r.sync){if(r.ignoreError)return e;throw e}return r.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=i.state,h=new DP(u,t,a);LP.call(i,h);let p=e=>{var o;return i[CP]=e,h.aborted||(LP.call(i,t),null===(o=r.success)||void 0===o||o.call(this,i[CP])),e},m=e=>(LP.call(i,u,e),d(e));try{let e=s.apply(this,n);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):r.sync?p(e):Promise.resolve(p(e))}catch(sM){return m(new NP(i._state,"".concat(i.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(sM),sM instanceof Error?sM:new Error(String(sM))))}}}}var MP="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 LP(e,t){let r=this._state;this._state=e;let i=e.toString();e&&this.emit(i,r),this.emit(PP.STATECHANGED,e,r,t),this.updateDevTools({value:e,old:r,err:t instanceof Error?t.message:String(t)})}var PP=class e extends bP.default{constructor(t,r,i){super(),this.name=t,this.groupName=r,this._state=e.INIT,t||(t=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let o=i[wP];o?this.name=o.name+"-"+o.count++:i[wP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=kP.get(e)||[],r=new Set,i=[],o=[],n=new Set,a=Object.getPrototypeOf(e);kP.has(a)&&(a.stateDiagram.forEach((e=>r.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:r,action:n}=e;"string"==typeof t?i.push({from:t,to:r,action:n}):t.length?t.forEach((e=>{i.push({from:e,to:r,action:n})})):o.push({to:r,action:n})})),i.forEach((e=>{let{from:t,to:i,action:o}=e;n.add(t),n.add(i),n.add(o+"ing"),r.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),r.add("".concat(o,"ing --\x3e ").concat(i," : ").concat(o," 🟢")),r.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:i}=e;r.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🟢")),n.forEach((e=>{e!==t&&r.add("".concat(e," --\x3e ").concat(i,"ing : ").concat(i))}))}));let s=[...r];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}static get(t){let r;return"string"==typeof t?(r=e.instances.get(t),r||e.instances.set(t,r=new e(t,void 0,Object.create(e.prototype)))):(r=e.instances2.get(t),r||e.instances2.set(t,r=new e(t.constructor.name,void 0,Object.create(e.prototype)))),r}static getState(t){var r;return null===(r=e.get(t))||void 0===r?void 0:r.state}updateDevTools(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};MP(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){LP.call(this,e)}};PP.STATECHANGED="stateChanged",PP.UPDATEAFSM="updateAFSM",PP.INIT="[*]",PP.ON="on",PP.OFF="off",PP.instances=new Map,PP.instances2=new WeakMap;var xP="undefined"!=typeof window,UP=xP&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},VP=xP&&window.cancelIdleCallback||function(e){clearTimeout(e)},FP=xP&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),BP=class e{static generateTaskID(){return this.currentTaskID++}static run(e,t,r){null!=r&&r.fps&&(r.delay=r.delay||Number((1e3/r.fps).toFixed(2))),r=Xb("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},r);let i=$b(Xb({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},r),{delay:r.delay});return this.taskMap.set(i.taskID,i),this[e](i),i.taskID}static interval(t){return t.intervalID=setInterval((()=>{t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}static intervalInWorker(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=t=>{var r;if("tick"===t.data.type){let i=e.workerTasks.get(t.data.taskId);i&&(e.isBreakLoop(i)?(null==(r=e.sharedWorker)||r.postMessage({type:"stop",taskId:i.taskID}),e.workerTasks.delete(i.taskID)):(i.callback(),i.loopCount+=1))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let r=()=>{if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(r,t.delay)};return t.timeoutID=setTimeout(r,t.delay)}static ric(t){let r,i=ZD(),o=()=>{if(r=ZD()-i,r>=t.delay&&(i=ZD()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=UP(o,{timeout:t.delay})};return t.ricID=UP(o,{timeout:t.delay})}static raf(t){let r,i=ZD(),o=()=>document.hidden&&t.backgroundTask?(r=ZD()-i,i=ZD(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay))):(r=ZD()-i,r>=t.delay&&(i=ZD()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(o));if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let e=()=>{if(document.hidden){let e=ZD()-i;e>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-e)}};document.addEventListener("visibilitychange",e),t.onVisibilitychange=e,document.hidden&&e()}return t.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:r,rafID:i,ricID:o,onVisibilitychange:n}=this.taskMap.get(e);return t&&clearInterval(t),r&&clearTimeout(r),i&&FP&&FP(i),o&&VP(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};rw(BP,"taskMap",new Map),rw(BP,"currentTaskID",1),rw(BP,"sharedWorker",null),rw(BP,"workerTasks",new Map);var HP=BP;$w.SEI_MESSAGE;var WP={LOADED_DATA:$w.LOADEDDATA,LOADED_META_DATA:$w.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:$w.RESIZE,TIME_UPDATE:"time-update"},jP={};Zb(jP,{create:()=>zP,remove:()=>KP});var GP=new WeakMap;function zP(e,t){GP.has(e)||GP.set(e,[]);let r=GP.get(e),i={add:(e,o)=>("addEventListener"in t?(r.push(t.removeEventListener.bind(t,e,o)),t.addEventListener(e,o)):(r.push(t.off.bind(t,e,o)),t.on(e,o)),i)};return i}function KP(e){let t=GP.get(e);t&&(t.forEach((e=>e())),GP.delete(e))}var qP=new class{constructor(){rw(this,"_roomIdMap",new Map),rw(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Tw,env:Bw.QCLOUD,browserVersion:RO.name+RO.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:r,userId:i,roomId:o}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=r,this._configs.userId=i,this._roomIdMap.set(i,String(o))}logSuccessEvent(e){AO||!qO.isAbleToUpload||this._configs.env===Bw.QCLOUD&&this.uploadEventToKibana($b(Xb({},e),{result:"success"}))}logFailedEvent(e){if(AO||!qO.isAbleToUpload)return;let{eventType:t,code:r,error:i,userId:o}=e,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:t,result:"failed",code:r||(null==i?void 0:i.extraCode)||(null==i?void 0:i.code)||uw.UNKNOWN};this._configs.env===Bw.QCLOUD&&this.uploadEventToKibana($b(Xb({},n),{error:i}))}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:r,error:i}=e,o={timestamp:_w(),sdkAppId:this._configs.sdkAppId,userId:r||this._configs.userId,version:Tw,log:t};i&&(o.errorInfo=i.message,i.stack&&(o.errorInfo+="\n".concat(i.stack)));let n=zO.enable?CN(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(TD(this._configs.sdkAppId,Fw.LOG),n)}sendRequest(e,t){setTimeout((()=>xN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},YP=new WeakMap;function JP(e){let{settings:t={retries:5,timeout:2e3},onError:r,onRetrying:i,onRetryFailed:o}=e;return function(e,n,a){let s=WN({retryFunction:a.value,settings:t,onError(t){let{error:i,retry:o,reject:a,retryFuncArgs:s}=t;var c;r?r.call(this,i,(()=>{var t;null!=(t=YP.get(e))&&t.has(n)?o():a(i)}),a,s):null!=(c=YP.get(e))&&c.has(n)?o():a(i)},onRetrying(t,r){var o;FN(i)&&i.call(this,t,r),null!=(o=YP.get(e))&&o.has(n)&&(YP.get(e).get(n).stopRetry=r)},onRetryFailed:o});return a.value=function(){let t=YP.get(e);for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return t?t.set(n,{args:i}):YP.set(e,new Map([[n,{args:i}]])),s.apply(this,i).finally((()=>{var t;return null==(t=YP.get(e))?void 0:t.delete(n)}))},a}}var XP=class extends PP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,rw(this,"id"),rw(this,"element",null),rw(this,"track"),rw(this,"url"),rw(this,"attr"),rw(this,"mode"),rw(this,"muted"),rw(this,"_log"),rw(this,"_isPausedByUserCall",!1),rw(this,"_pausedRetryCount"),rw(this,"_isElementPlayingFired",!1),rw(this,"_interval"),rw(this,"_delayDestroyTimeoutId",0),rw(this,"_playSuccessResolve"),rw(this,"_isReplayByRecreateMediaStreamCalled",!1),rw(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=jC,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isPaused(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}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 ow(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(Aw){let t=sL({key:iL.PLAY_FAILED,data:{media:this.kind,error:Aw}});if(this._log.warn(Aw),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new pw({code:uw.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!hO?this._delayDestroyTimeoutId||(null==(t=this.element)||t.remove(),this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped($w.ENDED),this._interval>0&&HP.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),null==(e=this.element)||e.pause(),this._isPausedByUserCall=!0,this instanceof yx&&nO&&cO>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():yO?this.replay():(this.element&&this.track&&nO&&cO>=128&&(this.element.srcObject=new MediaStream([this.track])),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 zP(this.element,this.element).add($w.PLAYING,e).add($w.ENDED,e).add($w.PAUSE,e).add($w.ERROR,e).add($w.LOADEDDATA,e).add($w.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==jP||jP.create(e,e).add($w.ENDED,t).add($w.MUTE,t).add($w.UNMUTE,t),e.readyState===$w.ENDED&&this.handleTrackEvent({type:$w.ENDED}),e.muted&&this.handleTrackEvent({type:$w.MUTE})}}bindAutoPlayEvent(){WO.on(GO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&KP(e)}unbindEvents(){this.element&&KP(this.element),this.unbindTrackEvents(),WO.off(GO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case $w.PLAYING:fx()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying($w.PLAYING),this._interval&&(HP.clearTask(this._interval),this._interval=-1);break;case $w.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped($w.ENDED);break;case $w.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused($w.PAUSE),tk&&(this._interval=HP.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.doResume()}),{delay:3e3}));break;case $w.ERROR:if(this.element&&this.element.error){this.handlePaused($w.ERROR);let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),qP.uploadEvent({log:"stat-".concat(this.kind,"-").concat(wC.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),qk||Kk?this.emit(WP.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case $w.LOADEDDATA:this.kind===$w.VIDEO&&this.emit(WP.LOADED_DATA);break;case $w.LOADEDMETADATA:this.kind===$w.VIDEO&&this.emit(WP.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),qP.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),EL.addSuccessEvent({key:this.kind===$w.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),qP.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),EL.addFailedEvent({key:this.kind===$w.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(WP.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,r)=>{vN(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,i;this._log.warn("element onerror ".concat(null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code," fired after recreated mediaStream")),r(null==(i=this.element)?void 0:i.error)}),vN(5e3).then((()=>{var e,i;(!this.isPlaying||null!=(e=this.element)&&e.error)&&r(null==(i=this.element)?void 0:i.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){return ow(this,null,(function*(){switch(e.type){case $w.ENDED:this.handleStopped($w.ENDED);break;case $w.MUTE:this.handlePaused($w.MUTE);break;case $w.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying($w.UNMUTE))}}))}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};rw(XP,"PlayerEvent",WP),tw([JP({settings:{retries:2,timeout:0},onError(e,t,r,i){i[0]=(i[0]||1e3)+1e3,t()}})],XP.prototype,"doReplayByRecreateMediaStream",1),tw([OP([],"PLAYING",{sync:!0,success(e){this.emit(WP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],XP.prototype,"handlePlaying",1),tw([OP("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(WP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],XP.prototype,"handlePaused",1),tw([OP([],"STOPPED",{sync:!0,success(e){this.emit(WP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],XP.prototype,"handleStopped",1);var $P,QP="trtc_autoplay",ZP="".concat(QP,"_mask"),ex="".concat(QP,"_wrapper"),tx="".concat(QP,"_header"),rx="".concat(QP,"_content"),ix="".concat(QP,"_action_wrapper"),ox="".concat(QP,"_question"),nx="".concat(QP,"_collapse"),ax="".concat(QP,"_action_confirm"),sx="".concat(QP,"_detail"),cx="#2473E8",lx="dialog",dx="".concat(lx,"-show"),ux="".concat(lx,"-1"),hx="".concat(lx,"-2"),px=!1,mx=!1,fx=()=>mx,_x="".concat(Lw,"/").concat(MD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),gx="<br><a href='".concat(_x,"' target='_blank'>").concat(MD()?"其他方案?":"Any other solution?","</a>"),Ex="".concat(MD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(gx):"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(gx)),vx=class{constructor(){if(rw(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),rw(this,"_dialogNode",null),rw(this,"_bodyPosition",""),rw(this,"_showDetail",!1),rw(this,"_isCollapseClicked",!1),rw(this,"_isQuestionClicked",!1),MD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!px){let e=document.createElement("style");e.innerHTML=".".concat(ZP,"{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(ZP," div:not(.").concat(ix,"){display:block !important;}.").concat(ex,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(ex," a{color:").concat(cx,";}.").concat(tx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(rx,"{margin:8px 0;}.").concat(ix,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(nx,"{margin-right:auto;cursor:pointer}.").concat(ox,"{height:100%;line-height:16px;cursor:pointer;}.").concat(ax,"{margin-left:8px;color:#fff;background:").concat(cx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(ax,":hover{opacity:0.9;}.").concat(nx,",.").concat(ax,",.").concat(rx,",.").concat(ox,"{font-size:14px;}@media screen and (max-width:750px){.").concat(ex,"{width:80vw;}}"),document.head.appendChild(e),px=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(ZP,"\"><div class='").concat(ex,"'><div class='").concat(tx,"'>").concat(location.host,"</div><div class='").concat(rx,"'>").concat(this.content,"</div><div class='").concat(sx,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(Ex,"</div><div class='").concat(ix,"'></div></div></div>").trim();let t=document.createElement("button");t.className=ax,t.innerText=MD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=ox,r.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 ',r.onclick=this.onQuestionClick.bind(this);let i=document.createElement("div");i.className=nx,i.innerText="".concat(MD()?"详情 >":"Detail >"),i.onclick=this.onCollapseClick.bind(this);let o=e.content.firstChild,n=o.querySelector(".".concat(ix));return n.appendChild(i),n.appendChild(r),n.appendChild(t),o}addDiaLog(){fx()||(mx=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(ex)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",qO.info("show autoplay dialog"),qP.uploadEvent({log:dx}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,mx=!1)}onConfirm(){qO.warn("confirm clicked, try resume stream"),WO.emit(GO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(sx));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||qP.uploadEvent({log:ux}),this._isCollapseClicked=!0}onQuestionClick(){window.open(_x,"_blank"),this._isQuestionClicked||qP.uploadEvent({log:hx}),this._isQuestionClicked=!0}},yx=class extends XP{constructor(e){super(e,$w.VIDEO),rw(this,"stat",{}),rw(this,"_calculateTimeout",-1),rw(this,"viewMirror",!1),rw(this,"objectFit"),rw(this,"container"),rw(this,"canvas"),rw(this,"_preSize",{width:0,height:0}),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,FD(e.viewMirror)||(this.viewMirror=e.viewMirror),FD(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted)}initializeElement(){var e;let t=document.createElement($w.VIDEO);this.track&&2!==this.mode&&(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,rk&&(t.poster="noposter"),null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}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($w.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add($w.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add($w.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===$w.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,r,i,o,n,a,s,c;if(2===this.mode)return;super.handleElementEvent(e);let l=e.type;if(l===$w.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=jC,this._log.info("view container ".concat(null==(r=this.container)?void 0:r.id," is recreated"))),this._pausedRetryCount>0&&!fx()&&!this._isPausedByUserCall&&(this._log.info("[".concat(jC-this._pausedRetryCount+1,"/").concat(jC,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;l===$w.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):l===$w.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}l===$w.RESIZE&&(this._preSize.height!==(null==(i=this.element)?void 0:i.videoHeight)||this._preSize.width!==(null==(o=this.element)?void 0:o.videoWidth))&&(this._log.info("video size changed to ".concat(null==(n=this.element)?void 0:n.videoWidth,"x").concat(null==(a=this.element)?void 0:a.videoHeight)),this._preSize.height=(null==(s=this.element)?void 0:s.videoHeight)||0,this._preSize.width=(null==(c=this.element)?void 0:c.videoWidth)||0,this.emit(WP.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var r,i,o,n;this.canvas!==e&&(null==(r=this.canvas)||r.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(i=this.element)||i.remove(),null==(o=this.container)||o.appendChild(e)):this.element&&(null==(n=this.container)||n.appendChild(this.element)))}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}setPoster(e){this.element&&(this.element.poster=e)}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(WP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(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}calculateStat(){try{if(EP()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(i,o)=>{this.stat.width=o.width,this.stat.height=o.height,t&&(this.stat.fps=Math.round((o.presentedFrames-t.presentedFrames)/(i-e)*1e3)),e=i,t=o,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(r)}),2e3))};this.element.requestVideoFrameCallback(r)}}catch(Aw){this._log.warn("init stat failed",Aw)}}};function Tx(e,t){return ow(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),qO.info("worklet addModule success")}catch(Aw){throw qO.info("worklet addModule catch error. ".concat(Aw.message)),Aw}}))}"undefined"!=typeof AudioContext?$P=AudioContext:"undefined"!=typeof webkitAudioContext?$P=webkitAudioContext:"undefined"!=typeof mozAudioContext&&($P=mozAudioContext);var Ix,Ax=1500,Sx=-1,Rx=0,bx=-1,wx=!1,Cx=0,Dx=-1,Nx=-1;!function e(){try{if(Ix)return;(Ix=new $P({sampleRate:48e3})).onstatechange=()=>{qO.info("context state: ".concat(Ix.state).concat("running"!==Ix.state?" visibilityState: ".concat(document.visibilityState):"")),kx()},clearTimeout(Sx)}catch(yH){qO.error("initAudioContext failed: ".concat(yH," typeof AudioContextClass: ").concat(typeof $P)),Sx=setTimeout(e,1e3)}}();var kx=()=>{"suspended"===Ix.state?(Rx=ZD(),-1===bx&&(bx=setTimeout((()=>{"suspended"===Ix.state&&(wx=!0,WO.emit("155",{isSuspended:!0}))}),Ax)),Lx(),document.addEventListener("click",kx)):"interrupted"===Ix.state?Lx():(Rx&&(EL.addNumber({key:507800,value:ZD()-Rx,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rx=0),-1!==bx&&(clearTimeout(bx),bx=-1,wx&&(wx=!1,WO.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",kx),document.removeEventListener("click",kx))},Ox=0,Mx=-1;function Lx(){return new Promise(((e,t)=>{if("running"===Ix.state)return e();Date.now()-Ox<1e3?(clearTimeout(Mx),Mx=setTimeout((()=>{Ox=Date.now(),Ix.resume().then(e,t)}),1e3)):(clearTimeout(Mx),Ox=Date.now(),Ix.resume().then(e,t))})).catch((e=>{qO.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",kx)}))}document.addEventListener("click",kx);var Px=e=>Ix,xx=class{constructor(e){this.name=e,rw(this,"node"),rw(this,"node2"),rw(this,"pre",new Set),rw(this,"next",new Set),rw(this,"context"),rw(this,"connectedNodes",new Set),rw(this,"nextInputChannelMap",new Map),rw(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(RC){qO.error(RC)}}setNode(e,t){var r;if(!this.node)try{null==(r=this.context)||r.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),EL.addSuccessEvent({key:502701})}catch(iM){qO.error(iM),EL.addFailedEvent({key:502701,error:iM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),EL.addSuccessEvent({key:502702})}catch(Aw){qO.error(Aw),EL.addFailedEvent({key:502702,error:Aw})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{let r=this.nextInputChannelMap.get(t);e._connect(t.node,r)||t.connectNext(e)}))}_connect(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},Ux=class extends xx{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,rw(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,r=0,i="M".concat(t,",").concat(r);for(let o=0;o<e.length;o++)r=e[o]/128*100/2,i+="L".concat(t,",").concat(r),t+=1;return i}},Vx=class{constructor(){rw(this,"source",new xx),rw(this,"gain",new xx),rw(this,"destination",new xx)}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(Px().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=Wx(e);t&&this.source.replaceNode(t)}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}},Fx=class extends Vx{constructor(e){super(),this.context=e,rw(this,"aec",new xx("aec")),rw(this,"mixNode",new xx("mixNode")),rw(this,"silentNode",new xx("silentNode")),rw(this,"denoiser",new xx("denoiser")),rw(this,"voiceChanger",new xx("voiceChanger")),this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.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.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},Bx=class{constructor(){rw(this,"audioContext",Px()),rw(this,"destination",this.audioContext.createMediaStreamDestination()),rw(this,"inputs",new Set),rw(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]}},Hx=new WeakMap;function Wx(e){try{let t=Hx.get(e);if(t)return t;let r=Px();if(e instanceof HTMLAudioElement)t=r.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=r.createMediaStreamSource(new MediaStream([e]))}return Hx.set(e,t),t}catch(tM){if(!(ak&&tM instanceof Error&&"NotSupportedError"===tM.name))throw tM;qO.warn(tM)}}var jx=class e{constructor(e){rw(this,"_volume",0),rw(this,"_volumeDb",0),rw(this,"_log"),rw(this,"_scriptProcessorNode",null),rw(this,"_audioWorkletNode",null),rw(this,"_interval",200),rw(this,"ready",this.preload());let{log:t}=e;this._log=t,WO.on(GO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-e.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!e.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';e.workletReady=Tx(e.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return e.workletReady.then((()=>this.initAudioWorklet())).catch((e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor())))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(e.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=r=>{e.lastMessageTime=Date.now(),this._volume=r.data.volume||0,this._volumeDb=r.data.volumeDb||0,!t&&r.data.cacheLen&&r.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(tM){this._log.error("volumeMeter init audio worklet error: ".concat(tM)),qP.logFailedEvent({userId:this._log.userId,eventType:wC.LOAD_WORKLET,error:tM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Px().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{e.lastMessageTime=Date.now();let r=t.inputBuffer.getChannelData(0),i=0;for(let e=0;e<r.length;++e)i+=r[e]*r[e];this._volume=Math.sqrt(i/r.length)||0}}catch(tM){this._log.error("volumeMeter init script processor error: ".concat(tM))}}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,WO.off(GO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(e){var t;let{interval:r}=e;this._interval=r,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:r})}};rw(jx,"lastMessageTime",0),rw(jx,"audioContext",Px()),rw(jx,"workletReady");var Gx=jx,zx=class extends xx{constructor(e){super(),rw(this,"_volumeMeter"),this._volumeMeter=new Gx(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return ow(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},Kx=Gx,qx=ew(nw(),1),Yx=e=>t=>t.deviceId===e,Jx=class{constructor(e,t){rw(this,"kind"),rw(this,"type"),rw(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let r=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&Qx(this.devices[0])||t&&(r.forEach((e=>{if(e.deviceId&&!this.devices.find(Yx(e.deviceId))){let r="".concat(this.kind).concat(this.type,"Added");qO.warn("".concat(r,": ").concat(JSON.stringify(e))),t.emit(r,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!r.find(Yx(e.deviceId))){let r="".concat(this.kind).concat(this.type,"Removed");qO.warn("".concat(r,": ").concat(JSON.stringify(e))),t.emit(r,e)}}))),this.devices=r}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},Xx=class extends qx.EventEmitter{constructor(){super(),rw(this,"audioInputs",new Jx($w.AUDIO,"Input")),rw(this,"videoInputs",new Jx($w.VIDEO,"Input")),rw(this,"audioOutputs",new Jx($w.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||HP.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){Zx().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return ow(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let r=yield Zx(t);return e.audioInputs.update(r,e),e.videoInputs.update(r,e),e.audioOutputs.update(r,e),e}()}))}hasBlueTooth(){var e;if(1e3*(null==(e=Px())?void 0:e.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some((e=>t.some((t=>e.label.toLowerCase().includes(t)))))||this.audioInputs.devices.some((e=>t.some((t=>e.label.toLowerCase().includes(t)))))}},$x=bw||Rw?null:new Xx;function Qx(e){return e.deviceId===e.groupId&&""===e.groupId}function Zx(){return ow(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(bL()||!SL())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let r={audio:!1,video:!1};if(t.forEach((e=>{Qx(e)&&(e.kind===$w.AUDIO_INPUT?r.audio=!0:e.kind===$w.VIDEO_INPUT&&(r.video=!0))})),2===e&&(r.audio=!1),1===e&&(r.video=!1),r.audio||r.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(r),r.audio&&Lx()}catch(iM){qO.debug("capture before getDevices failed: ",iM)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&oU.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r}))}()}))}function eU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return $x.update(e?1:0).then((e=>e.audioInputs.devices))}function tU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return $x.update(e?2:0).then((e=>e.videoInputs.devices))}var rU=!1;function iU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return ow(this,null,(function*(){return(tk||uO)&&(e=!1),$x.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var oU=new Set;function nU(e,t){return ow(this,null,(function*(){let r=(yield eU()).find((e=>e.deviceId===GC));return!t&&(null==r?void 0:r.groupId)===e||(null==r?void 0:r.groupId)===e&&r.label===t}))}var aU,sU=class extends Vx{constructor(e){super(),this.log=e,rw(this,"volumeMeter"),rw(this,"volumeMeterAfter3A"),rw(this,"volumeDestination"),rw(this,"analyser",new Ux),this.volumeMeter=new zx({log:this.log}),this.volumeMeterAfter3A=new zx({log:this.log}),this.volumeDestination=new xx,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},cU=class e extends XP{constructor(e){super(e,$w.AUDIO),rw(this,"_outputDeviceId"),rw(this,"_volume",1),rw(this,"_destination",Px().createMediaStreamDestination()),rw(this,"pipeline"),rw(this,"volumeMeterMode","worklet"),rw(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new sU(this._log)}get duration(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===fO||"15.3"===fO||"15.4"===fO)&&this.muted)return void this._log.info("audioElement is muted.");let t=aU||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),this.element=t,HD(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===aU&&(aU=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(WP.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return ow(this,null,(function*(){if(this.track||this.url)return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(Px().createAnalyser()),function(){ow(this,null,(function*(){try{rU||(rU=!0,qO.info("speakers:".concat((yield iU()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),iw(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return ow(this,null,(function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(r=(t=this.element).setSinkId)?void 0:r.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()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},lU=class extends cU{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(WP.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},dU=class extends cU{constructor(e){super(e),rw(this,"_sourceElement"),rw(this,"_output",new xx),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Px().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,i;(null==(r=null==(t=this.element)?void 0:t.error)?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(WP.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.source.channelCount=(null==(i=e.getSettings())?void 0:i.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(e<=1&&!tk)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(tk){if(!this.enableVolumeControlInIOS)return;!function(){if(!tk||-1!==Nx)return;let e=()=>{ZD()-Cx<500||(Ix&&"running"===Ix.state&&Ix.currentTime===Dx&&(qO.warn("context is fake running, auto resume"),Ix.suspend().catch((e=>{qO.warn("context suspend failed: ".concat(e))}))),Dx=Ix.currentTime,Cx=ZD())};Nx=setInterval((()=>{e()}),2e3),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&e()}))}()}if(ak&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),KP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&hO&&(aU=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},uU=class extends PP{constructor(e){let{userId:t,sdkAppId:r,mediaType:i,room:o,PlayerClass:n=(1===i?dU:yx)}=e;var a;super(),rw(this,"id",YO()),rw(this,"userId",""),rw(this,"isRemote"),rw(this,"mediaType"),rw(this,"room"),rw(this,"user"),rw(this,"_log"),rw(this,"_inputTrack"),rw(this,"_outputTrack"),rw(this,"isPlayCalled"),rw(this,"container",null),rw(this,"player"),rw(this,"subVideoPlayerMap"),rw(this,"muted",!1),rw(this,"abortCtrl"),rw(this,"objectFit","cover"),rw(this,"mirror"),rw(this,"rotation"),rw(this,"isScreen",!1),rw(this,"manager"),rw(this,"trackSettings"),rw(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=i,this._log=qO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(a=o||this.room)?void 0:a.userId,remoteUserId:this instanceof YF?void 0:this.userId,sdkAppId:r,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof YF}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:null==o?void 0:o.enableVolumeControlInIOS}),this.player.on(WP.PLAYER_STATE_CHANGED,(e=>{WO.emit(GO.PLAYER_STATE_CHANGED,Xb({track:this},e)),this.emit("player-state-changed",e)})),this.kind===$w.VIDEO&&(this.player.on(WP.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(WP.LOADED_DATA),WO.emit(GO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(WP.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(WP.LOADED_META_DATA)})),this.player.on(WP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})),this.player.on(WP.RESIZE,(e=>{this.emitFirstVideoFrameEvent(WP.RESIZE),this.emit("video-size-changed",Xb({userId:this.userId,streamType:2===this.mediaType?"auxiliary":"main"},e))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(WP.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||qO}get kind(){return 1===this.mediaType?$w.AUDIO:$w.VIDEO}get isAudio(){return this.kind===$w.AUDIO}get strMediaType(){return 4===this.mediaType?$w.VIDEO:2===this.mediaType?$w.SCREEN:$w.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return ow(this,null,(function*(){let r=GD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!FD(t.muted)&&this.setPlayerMute(t.muted),t&&!FD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof yx&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),GD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!FD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===$w.VIDEO)&&this.setPlayerMute(!0),t&&!FD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof yx&&(this.player.setObjectFit(this.objectFit),t&&!FD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof yx&&this.player.setContainer(r)),WO.emit(GO.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(t),GD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(aM){throw this.handleAutoPlayFailed(aM),aM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==$w.VIDEO||FD(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let i=this.manager;if(WD(this.mirror))return r.setViewMirror(this.mirror),void(!this.isRemote&&i&&(i.mirror=!1));switch(this.mirror){case"view":i&&(i.mirror=!1),r.setViewMirror(!0);break;case"publish":i&&(i.mirror=!0),r.setViewMirror(!0);break;case"both":i&&(i.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return ow(this,null,(function*(){if(!this._outputTrack||this.kind===$w.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,r)=>{var i;e.find((e=>r===e))||(t.stop(),null==(i=this.subVideoPlayerMap)||i.delete(r))}));for(let[i,o]of e.entries()){let e=this.subVideoPlayerMap.get(o);e?t&&(FD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new yx({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(i+1)})}))}let r=[...this.subVideoPlayerMap.values()];for(let e of r)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(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(BN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return ow(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(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),WO.emit(e?GO.TRACK_MUTED:GO.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}installTrackEvent(e){zP(e,e).add($w.MUTE,this.onTrackMuted).add($w.UNMUTE,this.onTrackUnmuted).add($w.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===$w.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){KP(e)}setInputMediaStreamTrack(e){var t;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||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._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),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((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(BN(this)?this.jitterBufferDelay:0),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(e){if(this.room&&this.room.enableAutoPlayDialog)new vx;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof yx?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,r,i;if(this.isFirstVideoFrameEmitted)return;let o=null==(t=this.mediaTrack)?void 0:t.getSettings(),n=(null==o?void 0:o.width)||(null==(r=this.player.element)?void 0:r.videoWidth)||0,a=(null==o?void 0:o.height)||(null==(i=this.player.element)?void 0:i.videoHeight)||0;e===WP.RESIZE&&!n&&!a||e===WP.LOADED_META_DATA&&!n&&!a||(e===WP.LOADED_DATA&&!n&&!a&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,SN(this.rotation)&&([n,a]=[a,n]),this.emit("first-video-frame",{width:n,height:a,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};tw([OP([],PP.INIT,{sync:!0})],uU.prototype,"close",1);var hU=Object.prototype.hasOwnProperty;var pU=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(LD(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(hU.call(e,t))return!1;return!0}return!1},mU=WN({retryFunction:function(e){return ow(this,null,(function*(){let t=function(e){return{audio:_U(e),video:gU(e)}}(e);qO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let r=[],i=[],o=["label","deviceId","groupId"];if(t.audio&&(r=yield eU(),qO.info("microphones: ".concat(hN(r.map((e=>$b(Xb({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:o})))),t.video&&(i=yield tU(),qO.info("cameras: ".concat(hN(i,{keysToInclude:o}))),"user"===t.video.facingMode&&!t.video.deviceId)){let e=i.filter((e=>!e.label.includes("infrared"))).find((e=>e.label.includes("facing front")));e&&(t.video.deviceId=e.deviceId,qO.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let r=yield navigator.mediaDevices.getUserMedia(t);return oP&&r.getTracks().forEach((t=>{var r;let i=t.getCapabilities();qO.info("".concat(t.kind," capabilities: ").concat(hN(i,{keysToInclude:$C}))),!FD(e.echoCancellation)&&-1===(null==(r=i.echoCancellation)?void 0:r.indexOf(e.echoCancellation))&&qO.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(i.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))})),t.audio&&Lx(),r}catch(aM){let{message:o}=aM;throw"NotFoundError"===aM.name&&(e.video&&i&&0===i.length&&(o=sL({key:iL.CAMERA_NOT_FOUND})),e.audio&&r&&0===r.length&&(o=sL({key:iL.MICROPHONE_NOT_FOUND}))),new pw({code:uw.INITIALIZE_FAILED,name:aM.name,message:o,constraint:aM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:r,reject:i,retryFuncArgs:o,retriedCount:n}=e,a=n+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name||"AbortError"===t.name?(1===a?(o[0].video&&(o[0].maxResolution=!1,(!uO||o[0].width*o[0].height<=2073600)&&o[0].frameRate&&(o[0].frameRate=o[0].frameRate>10?10:5)),o[0].retryWhenExactFailed&&o[0].useExactDeviceId&&(o[0].useExactDeviceId=!1)):2===a?o[0].useDeviceIdOnly=!0:3===a&&!o[0].useExactDeviceId&&(o[0].useTrueAsConstraint=!0),r()):i(t),o[0].microphoneId&&fU(o[0].microphoneId,!1),o[0].cameraId&&fU(o[0].cameraId,!0)},onRetrying:e=>{qO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{qP.logFailedEvent({eventType:wC.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{qP.logSuccessEvent({eventType:wC.GET_USER_MEDIA_RETRY}),qP.uploadEvent({log:"stat-".concat(wC.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function fU(e,t){return ow(this,null,(function*(){let r=(t?yield tU():yield eU()).find((t=>t.deviceId===e));r&&VD(r.getCapabilities)&&qO.warn(hN(r.getCapabilities(),{keysToInclude:$C}))}))}function _U(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!pU(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(HD(e.channelCount)&&(t.channelCount=e.channelCount),(WD(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),WD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),WD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!pU(t)||t)}function gU(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,r={};return e.cameraId?r.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(r.facingMode=e.facingMode),e.useDeviceIdOnly&&!pU(r)?r:(e.width&&(r.width={ideal:e.width},t&&!ak&&(r.width.max=e.width)),e.height&&(r.height={ideal:e.height},t&&!ak&&(r.height.max=e.height)),ak&&Uk&&e.width&&e.height&&e.width*e.height<101376&&(r.width=e.width,r.height=e.height),e.frameRate&&(r.frameRate=e.frameRate),!!pU(r)||r)}var EU=mU;function vU(e){return yU(((t,r)=>function(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return ow(this,null,(function*(){let r=yield t.apply(this,i);return yield e.call(this,...i),r}))}))}function yU(e){return function(t,r,i){return i.value=e(i.value,r),i}}var TU=(()=>{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)}})(),IU=0,AU=class{constructor(){rw(this,"log",qO.createLogger({id:"fq".concat(++IU)})),rw(this,"isRunning",!1),rw(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var r,i;let o=Xb({},e),n=new Promise(((e,t)=>{o.resolve=e,o.reject=t}));return o.promise=n,t?this.length<=1?this.queue.push(o):null==(i=null==(r=this.lastQueueItem)?void 0:r.promise)||i.then(o.resolve,o.reject):this.queue.push(o),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),n}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:r,resolve:i,reject:o}=this.queue[0];this.isRunning=!0,e.apply(r,t).then(i,o).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},SU=new WeakMap,RU=new WeakMap;function bU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,r,i){let o=i.value;return i.value=function(){let t=SU.get(this)||new AU;for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return SU.set(this,t),t.push({fn:o,args:i,context:this},e)},i}}function wU(e,t){return yU(((r,i)=>function(){let i=e;try{for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let e=r.apply(this,n),s=ZD();return qD(e)?e.then((e=>(t?EL.addSuccessEvent({key:i,cost:ZD()-s}):EL.addSuccessEvent({key:i}),e))).catch((e=>{throw EL.addFailedEvent({key:i,error:e}),e})):(EL.addSuccessEvent({key:i}),e)}catch(Sw){throw EL.addFailedEvent({key:i,error:Sw}),Sw}}))}var CU={};function DU(){}Zb(CU,{Events:()=>GU,Inspect:()=>PU,LastSink:()=>xU,Sink:()=>UU,Subscribe:()=>VU,TimeoutError:()=>zU,audit:()=>QV,bindCallback:()=>wV,bindNodeCallback:()=>CV,buffer:()=>oV,bufferCount:()=>iV,bufferTime:()=>PF,call:()=>NU,catchError:()=>UF,combineLatest:()=>ZU,concat:()=>XU,concatMap:()=>AF,concatMapTo:()=>SF,count:()=>LV,create:()=>BU,debounce:()=>tF,debounceTime:()=>rF,defer:()=>sV,delay:()=>xF,deliver:()=>HU,dispose:()=>OU,elementAt:()=>iF,empty:()=>kV,every:()=>cF,exhaustMap:()=>kF,exhaustMapTo:()=>OF,expand:()=>FF,filter:()=>VV,find:()=>oF,findIndex:()=>nF,first:()=>aF,fromAnimationFrame:()=>RV,fromArray:()=>mV,fromEvent:()=>vV,fromEventPattern:()=>EV,fromFetch:()=>TV,fromIterable:()=>IV,fromPromise:()=>yV,fromReadableStream:()=>SV,fromReader:()=>AV,groupBy:()=>MF,identity:()=>kU,ignoreElements:()=>FV,iif:()=>QU,inspect:()=>MU,interval:()=>fV,last:()=>sF,map:()=>hF,mapTo:()=>pF,max:()=>PV,merge:()=>YU,mergeMap:()=>wF,mergeMapTo:()=>CF,min:()=>xV,never:()=>DV,nothing:()=>DU,of:()=>pV,pairwise:()=>dF,pipe:()=>FU,race:()=>JU,range:()=>bV,reduce:()=>MV,retry:()=>zF,scan:()=>lF,setAsapScheduler:()=>uV,share:()=>qU,shareReplay:()=>$U,skip:()=>GV,skipUntil:()=>zV,skipWhile:()=>KV,startWith:()=>tV,subject:()=>aV,subscribe:()=>WF,sum:()=>UV,switchMap:()=>EF,switchMapTo:()=>yF,take:()=>BV,takeLast:()=>jV,takeUntil:()=>HV,takeWhile:()=>WV,tap:()=>jF,throttle:()=>XV,throwError:()=>NV,timeInterval:()=>LF,timeout:()=>GF,timer:()=>_V,toPromise:()=>BF,toReadableStream:()=>HF,withLatestFrom:()=>rV,zip:()=>eV});var NU=e=>e(),kU=e=>e;function OU(){this.dispose()}var MU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,LU=1,PU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new jU(e,this,this.streamId++);return GU.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},xU=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=DU,this.error=DU,this.next=DU,this.dispose=DU,this.subscribe=DU,this.doDefer()}subscribe(e){return e instanceof PU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(NU),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}},UU=class extends xU{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)}},VU=class extends xU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:DU,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:DU,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:DU;if(super(),this._next=t,this._error=r,this._complete=i,this.then=DU,e instanceof PU){let o={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{GU.defer(o,0)})),GU.create(o),GU.pipe(o),this.sourceId=o.id,this.subscribe(e),GU.subscribe({id:o.id,end:!0}),t==DU?this._next=e=>GU.next(o,0,e):this.next=e=>{GU.next(o,0,e),t(e)},i==DU?this._complete=()=>GU.complete(o,0):this.complete=()=>{this.dispose(),GU.complete(o,0),i()},r==DU?this._error=e=>GU.complete(o,0,e):this.error=e=>{this.dispose(),GU.complete(o,0,e),r(e)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function FU(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return r.reduce(((e,t)=>t(e)),e)}function BU(e,t,r){if(MU()){let i=Object.defineProperties(Object.setPrototypeOf(e,PU.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:r,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});GU.create(i);for(let e=0;e<r.length;e++){let t=r[e];"function"==typeof t&&t instanceof PU&&GU.addSource(i,t)}return i}return e}function HU(e,t){return function(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return r=>{if(r instanceof PU){let o=BU((t=>{let n=new e(t,...i);n.sourceId=o.id,n.subscribe(r)}),t,arguments);return o.source=r,GU.pipe(o),o}return t=>r(new e(t,...i))}}}function WU(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var jU=class extends UU{constructor(e,t,r){super(e),this.source=t,this.id=r,this.sourceId=e.sourceId,this.defer((()=>{GU.defer(this.source,this.id)}))}next(e){GU.next(this.source,this.id,e),this.sink.next(e)}complete(){GU.complete(this.source,this.id),this.sink.complete()}error(e){GU.complete(this.source,this.id,e),this.sink.error(e)}},GU={addSource(e,t){WU("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,r){WU("next",{id:e.id,streamId:t,data:r&&r.toString()})},subscribe(e,t){let{id:r,end:i}=e;WU("subscribe",{id:r,end:i,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,r){WU("complete",{id:e.id,streamId:t,err:r?r.toString():null})},defer(e,t){WU("defer",{id:e.id,streamId:t})},pipe(e){WU("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){WU("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=LU++),WU("create",{name:e.toString(),id:e.id})}},zU=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},KU=class extends xU{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()}};function qU(){return e=>{let t=new KU(e);if(e instanceof PU){let r=BU((e=>{t.add(e)}),"share",arguments);return t.sourceId=r.id,r.source=e,GU.pipe(r),r}return BU(t.add.bind(t),"share",arguments)}}function YU(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU((e=>{let r=new UU(e),i=t.length;r.complete=()=>{0==--i&&e.complete()},t.forEach(r.bindSubscribe)}),"merge",arguments)}function JU(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU((e=>{let r=new Map;t.forEach((t=>{let i=new UU(e);r.set(t,i),i.complete=()=>{r.delete(t),0===r.size?e.complete():i.dispose()},i.next=e=>{r.delete(t),r.forEach((e=>e.dispose())),i.resetNext(),i.resetComplete(),i.next(e)}})),t.forEach((e=>r.get(e).subscribe(e)))}),"race",arguments)}function XU(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU((e=>{let r=0,i=t.length,o=new UU(e);o.complete=()=>{r<i&&!o.disposed?(o.doDefer(),o.subscribe(t[r++])):e.complete()},o.complete()}),"concat",arguments)}function $U(e){return t=>{let r=new KU(t),i=[];return r.next=function(t){i.push(t),i.length>e&&i.shift(),this.sinks.forEach((e=>e.next(t)))},BU((e=>{e.defer((()=>r.remove(e))),i.forEach((t=>e.next(t))),r.add(e)}),"shareReplay",arguments)}}function QU(e,t,r){return BU((i=>e()?t(i):r(i)),"iif",arguments)}function ZU(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU((e=>{let r=t.length,i=r,o=r,n=new Array(r),a=()=>{0==--o&&e.complete()};t.forEach(((t,r)=>{let o=new UU(e);o.next=t=>{i--,o.next=t=>{n[r]=t,0===i&&e.next(n)},o.next(t)},o.complete=a,o.subscribe(t)}))}),"combineLatest",arguments)}function eV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU((e=>{let r=t.length,i=r,o=new Array(r),n=()=>{0==--i&&e.complete()};t.forEach(((t,r)=>{let i=new UU(e),a=[];o[r]=a,i.next=t=>{a.push(t),o.every((e=>e.length))&&e.next(o.map((e=>e.shift())))},i.complete=n,i.subscribe(t)}))}),"zip",arguments)}function tV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return e=>BU((function(r){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;i<o&&!r.disposed;)r.next(t[i++]);r.disposed||r.subscribe(e)}),"startWith",arguments)}var rV=HU(class extends UU{constructor(e){super(e);let t=new UU(this.sink);for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];t.next=e=>this.buffer=e,t.complete=DU,t.subscribe(ZU(...i))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),iV=HU(class extends UU{constructor(e,t,r){super(e),this.bufferSize=t,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((e=>this.sink.next(e))),super.complete()}},"bufferCount"),oV=HU(class extends UU{constructor(e,t){super(e),this.buffer=[];let r=new UU(e);r.next=t=>{e.next(this.buffer),this.buffer=[]},r.complete=DU,r.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),nV=function(e,t,r,i){return new(r||(r=Promise))((function(o,n){function a(e){try{c(i.next(e))}catch(t){n(t)}}function s(e){try{c(i.throw(e))}catch(t){n(t)}}function c(e){e.done?o(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(a,s)}c((i=i.apply(e,t||[])).next())}))};function aV(e){let t=arguments,r=qU()(BU((t=>{r.next=e=>t.next(e),r.complete=()=>t.complete(),r.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return r.next=DU,r.complete=DU,r.error=DU,r}function sV(e){return BU((t=>t.subscribe(e())),"defer",arguments)}var cV={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},lV="undefined"!=typeof Promise?cV.promise:cV.setImmediate?cV.setImmediate:cV.setTimeout,dV=e=>t=>{lV((()=>e(t)))},uV=e=>{"function"==typeof e?lV=e:cV[e]&&(lV=cV[e])},hV=e=>dV((t=>{for(let r=0;!t.disposed&&r<e.length;r++)t.next(e[r]);t.complete()}));function pV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return BU(hV(t),"of",arguments)}function mV(e){return BU(hV(e),"fromArray",arguments)}function fV(e){return BU((t=>{let r=0,i=setInterval((()=>t.next(r++)),e);return t.defer((()=>{clearInterval(i)})),"interval"}),"interval",arguments)}function _V(e,t){return BU((r=>{let i=0,o=setTimeout((()=>{if(r.removeDefer(n),r.next(i++),t){let e=setInterval((()=>r.next(i++)),t);r.defer((()=>{clearInterval(e)}))}else r.complete()}),e),n=()=>clearTimeout(o);r.defer(n)}),"timer",arguments)}function gV(e,t){return r=>{let i=e=>r.next(e);r.defer((()=>t(i))),e(i)}}function EV(e,t){return BU(gV(e,t),"fromEventPattern",arguments)}function vV(e,t){if("on"in e&&"off"in e)return BU(gV((r=>e.on(t,r)),(r=>e.off(t,r))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return BU(gV((r=>e.addListener(t,r)),(r=>e.removeListener(t,r))),"fromEvent",arguments);if("addEventListener"in e)return BU(gV((r=>e.addEventListener(t,r)),(r=>e.removeEventListener(t,r))),"fromEvent",arguments);throw"target is not a EventDispachter"}function yV(e){return BU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function TV(e,t){return BU(sV((()=>yV(fetch(e,t)))),"fromFetch",arguments)}function IV(e){return BU(dV((t=>{try{for(let r of e){if(t.disposed)return;t.next(r)}t.complete()}catch(Aw){t.error(Aw)}})),"fromIterable",arguments)}function AV(e){let t=r=>nV(this,void 0,void 0,(function*(){if(r.disposed)return;let{done:i,value:o}=yield e.read();i?r.complete():(r.next(o),t(r))}));return BU((e=>{t(e)}),"fromReader",arguments)}function SV(e){return BU((t=>{let r=new AbortController,i=r.signal;t.defer((()=>r.abort("cancelled"))),e.pipeTo(new WritableStream({write(e){t.next(e)},close(){t.complete()},abort(e){t.error(e)}}),{signal:i}).then((()=>t.complete()),(e=>t.error(e)))}),"fromReadableStream",arguments)}function RV(){return BU((e=>{let t=requestAnimationFrame((function r(i){e.disposed||(e.next(i),t=requestAnimationFrame(r))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function bV(e,t){return BU((function(r){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;i<o&&!r.disposed;)r.next(i++);return r.complete(),"range"}),"range",arguments)}function wV(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return BU((r=>{let o=i.concat((e=>(r.next(e),r.complete())));e.apply(t,o)}),"bindCallback",arguments)}function CV(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return BU((r=>{let o=i.concat(((e,t)=>e?r.error(e):(r.next(t),r.complete())));e.apply(t,o)}),"bindNodeCallback",arguments)}function DV(){return BU((()=>{}),"never",arguments)}function NV(e){return BU((t=>t.error(e)),"throwError",arguments)}function kV(){return BU((e=>e.complete()),"empty",arguments)}var OV=class extends UU{constructor(e,t,r){super(e),this.f=t;let i=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===r?this.next=e=>{this.acc=e,this.complete=i,this.resetNext()}:(this.acc=r,this.complete=i)}next(e){this.acc=this.f(this.acc,e)}},MV=HU(OV,"reduce"),LV=e=>HU(OV,"count")(((t,r)=>e(r)?t+1:t),0),PV=()=>HU(OV,"max")(Math.max),xV=()=>HU(OV,"min")(Math.min),UV=()=>HU(OV,"sum")(((e,t)=>e+t),0),VV=HU(class extends UU{constructor(e,t,r){super(e),this.filter=t,this.thisArg=r}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),FV=HU(class extends UU{next(e){}},"ignoreElements"),BV=HU(class extends UU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&(this.doDefer(),this.complete())}},"take"),HV=HU(class extends UU{constructor(e,t){super(e);let r=new UU(e);r.next=()=>{r.doDefer(),e.complete()},r.complete=OU,r.subscribe(t)}},"takeUntil"),WV=HU(class extends UU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),jV=e=>MV(((t,r)=>(t.push(r),t.length>e&&t.shift(),t)),[]),GV=HU(class extends UU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),zV=HU(class extends UU{constructor(e,t){super(e),e.next=DU;let r=new UU(e);r.next=()=>{r.doDefer(),e.resetNext()},r.complete=OU,r.subscribe(t)}},"skipUntil"),KV=HU(class extends UU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),qV={leading:!0,trailing:!1},YV=class extends UU{constructor(e,t,r){super(e),this.durationSelector=t,this.trailing=r}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},JV=class extends UU{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qV;super(e),this.durationSelector=t,this.config=r,this._throttle=new YV(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=DU,this._throttle.complete(),super.complete()}},XV=HU(JV,"throttle"),$V={leading:!1,trailing:!0},QV=e=>HU(JV,"audit")(e,$V),ZV=class extends UU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},eF=class extends UU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new ZV(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},tF=HU(eF,"debounce"),rF=e=>HU(eF,"debounceTime")((t=>_V(e))),iF=HU(class extends UU{constructor(e,t,r){super(e),this.count=t,this.defaultValue=r}next(e){0==this.count--&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),oF=e=>t=>BV(1)(KV((t=>!e(t)))(t)),nF=HU(class extends UU{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),aF=HU(class extends UU{constructor(e,t,r){super(e),this.f=t,this.defaultValue=r,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),sF=HU(class extends UU{constructor(e,t,r){super(e),this.f=t,this.defaultValue=r,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),cF=HU(class extends UU{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),lF=HU(class extends UU{constructor(e,t,r){super(e),this.f=t,void 0===r?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),dF=HU(class extends UU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),uF=class extends UU{constructor(e,t,r){super(e),this.mapper=t,this.thisArg=r}next(e){super.next(this.mapper.call(this.thisArg,e))}},hF=HU(uF,"map"),pF=e=>HU(uF,"mapTo")((t=>e)),mF=class extends UU{constructor(e,t,r){super(e),this.data=t,this.context=r}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},fF=class e extends UU{constructor(e,t,r){super(e),this.makeSource=t,this.combineResults=r,this.index=0}subInner(t,r){let i=this.currentSink=new r(this.sink,t,this);this.complete===e.prototype.complete&&(this.complete=this.tryComplete),i.complete=i.tryComplete,i.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},_F=class extends mF{},gF=class extends fF{next(e){this.subInner(e,_F),this.next=e=>{this.currentSink.dispose(),this.subInner(e,_F)}}},EF=HU(gF,"switchMap");function vF(e){return(t,r)=>e((()=>t),r)}var yF=vF(HU(gF,"switchMapTo")),TF=class extends mF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},IF=class extends fF{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),TF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},AF=HU(IF,"concatMap"),SF=vF(HU(IF,"concatMapTo")),RF=class extends mF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},bF=class extends fF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,RF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},wF=HU(bF,"mergeMap"),CF=vF(HU(bF,"mergeMapTo")),DF=class extends mF{dispose(){this.context.resetNext(),super.dispose()}},NF=class extends fF{next(e){this.next=DU,this.subInner(e,DF)}},kF=HU(NF,"exhaustMap"),OF=vF(HU(NF,"exhaustMapTo")),MF=HU(class extends UU{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),r=this.groups.get(t);void 0===r&&(r=aV(),r.key=t,this.groups.set(t,r),super.next(r)),r.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},"groupBy"),LF=HU(class extends UU{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),PF=HU(class extends UU{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval((()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0}),this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),xF=HU(class extends UU{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout((()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}}),e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout((()=>super.complete()),this.delayTime)}},"delay"),UF=HU(class extends UU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),VF=class extends mF{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},FF=HU(class extends fF{constructor(e,t){super(e,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(e){this.sink.next(e),this.expandValue(e)}expandValue(e){let t=new VF(this.sink,e,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(e,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&0===this.inners.size&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),BF=()=>e=>new Promise(((t,r)=>{let i;new VU(e,(e=>i=e),r,(()=>t(i)))})),HF=()=>e=>{let t;return new ReadableStream({start(r){t=new VU(e,r.enqueue.bind(r),r.error.bind(r),r.close.bind(r))},cancel(){t.dispose()}})},WF=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:DU,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:DU,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:DU;return i=>new VU(i,e,t,r)},jF=HU(class extends UU{constructor(e,t){super(e),t instanceof Function?this.next=r=>{t(r),e.next(r)}:(t.next&&(this.next=r=>{t.next(r),e.next(r)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=r=>{t.error(r),e.error(r)}))}},"tap"),GF=HU(class extends UU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new zU(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),zF=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof PU){let r=BU((i=>{let o=e,n=new UU(i);n.error=e=>{o-- >0?n.subscribe(t):i.error(e)},n.sourceId=r.id,n.subscribe(t)}),"retry",[e]);return r.source=t,GU.pipe(r),r}return r=>{let i=e,o=new UU(r);o.error=e=>{i-- >0?t(o):r.error(e)},t(o)}}},KF=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(KF||{}),qF=class e extends uU{constructor(e,t){super({mediaType:e,PlayerClass:t}),rw(this,"isRemote",!1),rw(this,"deviceId"),rw(this,"groupId",""),rw(this,"label",""),rw(this,"sourceTrack"),rw(this,"enableAutoSwitchWhenRecapturing",!0),rw(this,"_isRecapturing",!1),rw(this,"_lastRecaptureTime",0),rw(this,"_onMuteTimeoutId",-1),rw(this,"_encodeCheckTimeoutId",-1),rw(this,"recaptureMode",0),rw(this,"profile"),rw(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){zP(e,e).add($w.MUTE,this.onTrackMuted).add($w.UNMUTE,this.onTrackUnmuted).add($w.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===$w.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){KP(e)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ow(this,null,(function*(){var r;let i=this.sourceTrack;try{let i,o=ZD();WO.emit(GO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(t||null==(r=this.sourceTrack)||r.stop(),i=yield EU(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),WO.emit(GO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ZD()-o}),i}catch(Sw){throw WO.emit(GO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Sw}),this.log.error("getUserMedia error observed ".concat(Sw)),Sw}finally{t&&(null==i||i.stop())}}))}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}get hasFlag(){var e,t;let r=oN((null==(e=this.room)?void 0:e.localPublishFlag)||0,(null==(t=this.room)?void 0:t.userId)||"");return 4===this.mediaType&&r.hasVideo||1===this.mediaType&&r.hasAudio||2===this.mediaType&&r.hasAuxiliary}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),Promise.all([t,new Promise(((t,r)=>ow(this,null,(function*(){var i,o;this.hasFlag?t():FU(vV(e,"local-publish-flag-changed"),VV((()=>this.hasFlag)),HV(YU(vV(this,PP.INIT),vV(this,"ready"))),WF(t)),!(((null==(o=null==(i=this.room)?void 0:i.networkQuality)?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>ow(this,null,(function*(){var e,t,i,o,n,a;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this.isPublished||this.isPublishing)&&this.isMediaTrackActive){let e=this.kind===$w.AUDIO,t=this.stat.bytesSent>0;if(EL[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(o=null==(i=this.room)?void 0:i.videoCodec)?void 0:o.toUpperCase())||"H264"];e&&EL[t?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!t){if(EL.addEnum({key:e?503701:513703,value:xO()}),qP.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(OO()||VO()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(a=null==(n=this.room)?void 0:n.videoCodec)?void 0:a.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield vN(5e3),this.stat.bytesSent>0||this.hasFlag)))return;this.emit("6",this),r(new pw({message:"".concat(this.strMediaType," encode failed"),code:e?uw.AUDIO_ENCODE_FAILED:uw.VIDEO_ENCODE_FAILED}))}}}))),5e3))}))))])}unpublish(){this.room&&this.room.localTracks.delete(this),WO.emit(GO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return ow(this,null,(function*(){if(this.sourceTrack&&iP){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield function(e){return ow(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:r,oldGroupId:i,oldLabel:o,kind:n}=e;return function*(){return t===r&&(n!==$w.AUDIO||t!==GC||(yield nU(i,o)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),Zx().then((r=>{let i=r.find((r=>{let i=r.deviceId===e;return t&&(i=i&&r.groupId===t),i}));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.sourceTrack||this.kind===$w.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 r="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat($w.AUDIO_INPUT);return!!oU.has(r)}(this.sourceTrack)||this.kind===$w.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 r="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat($w.VIDEO_INPUT);return!!oU.has(r)}(this.sourceTrack)||this._isRecapturing||e&&Uk&&uO)}onTrackMuted(){if(super.onTrackMuted(),TU(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<XC)return void setTimeout((()=>this.onTrackMuted()),XC);this._onMuteTimeoutId=setTimeout((()=>ow(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((tk||rk)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return ow(this,null,(function*(){if(iw(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<XC)return void setTimeout((()=>this.onTrackEnded()),XC);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ow(this,null,(function*(){var r;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let i=this.sourceTrack;t||null==(r=this.sourceTrack)||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let o={useExactDeviceId:!0};if("user"===e||"environment"===e)o.facingMode=e;else{let t;("audio"===this.kind?yield eU():yield tU()).find((t=>t.deviceId===e))&&(t=e),o.deviceId=t}return this.capture(o,t).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),WO.emit(GO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),WO.emit(GO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})})).finally((()=>{t&&(null==i||i.stop())}))}))}getRecoverCaptureDeviceId(){return ow(this,null,(function*(){let e=this instanceof eB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(JF.get(t)||0)+1;if(JF.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let i=e?(yield tU()).find((e=>!JF.has(e.deviceId))):(yield eU()).find((e=>!JF.has(e.deviceId)));i&&(this.log.warn("".concat(t," capture fail ").concat(r," times, change new ").concat(i.deviceId)),t=i.deviceId)}}return t}))}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};tw([OP(PP.INIT,"ready",{ignoreError:!0,sync:!0})],qF.prototype,"setStateToReady",1),tw([bU()],qF.prototype,"capture",1),tw([OP("ready","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),WO.emit(GO.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error";if(e.cause instanceof pw){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===uw.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),wU(521714,!1)],qF.prototype,"publish",1),tw([yU((e=>function(){return ow(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"}),clearTimeout(this._encodeCheckTimeoutId)}))})),OP([],"ready",{sync:!0})],qF.prototype,"unpublish",1);var YF=qF,JF=new Map;WO.on(GO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&JF.delete(e.track.deviceId)}));var XF=class e extends YF{constructor(e){super(1,lU),rw(this,"mediaType",1),rw(this,"volume",0),rw(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),rw(this,"playerMuted",!0),rw(this,"pipeline"),rw(this,"earMonitorGainNode",new xx),rw(this,"_output",new xx),rw(this,"codecPipeline",[]),rw(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),rw(this,"mixedAudioReferenceMap",new Map),rw(this,"isAudioContextLongSuspended",!1),this.manager=e,this.pipeline=new Fx(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),WO.on(GO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return Kx.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}setInputMediaStreamTrack(t){return ow(this,null,(function*(){let r=this.trackSettings||{};EL.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),EL.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),EL.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:o}=r;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:o}))),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(t),yield iw(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(t){return ow(this,arguments,(function(t){var r=this;let{deviceId:i,customSource:o,useExactDeviceId:n=!0,retryWhenExactFailed:a}=t,s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield iw(e.prototype,r,"capture").call(r,{video:!1,audio:!0,microphoneId:i,echoCancellation:r.profile.echoCancellation,autoGainControl:r.profile.autoGainControl,noiseSuppression:r.profile.noiseSuppression,sampleRate:r.profile.sampleRate,channelCount:r.profile.channelCount,useExactDeviceId:n,retryWhenExactFailed:a,customSource:o},s);return Lx(),t}()}))}switchDevice(e){return ow(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==GC)return;if(yield nU(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),WO.emit(GO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(RC){throw this.log.error("switch microphone failed ".concat(RC)),this.deviceId&&this.recapture(this.deviceId),RC}}}))}listenDeviceChange(){$x&&!$x.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&$x.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return ow(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(KF[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){HB(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield eU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&$x.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||($x.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return ow(this,arguments,(function(e){var t=this;let{echoCancellation:r,noiseSuppression:i,autoGainControl:o}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let n=e.getConstraints(),a=!1;!FD(r)&&r!==t.profile.echoCancellation&&(t.profile.echoCancellation=r,n.echoCancellation=r,a=!0),!FD(i)&&i!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=i,n.noiseSuppression=i,a=!0),!FD(o)&&o!==t.profile.autoGainControl&&(t.profile.autoGainControl=o,n.autoGainControl=o,a=!0),a&&(ak||uO?yield e.applyConstraints(n).catch((e=>t._log.warn("update3A failed: ",e))):t.deviceId&&(yield t.recapture(t.deviceId,!0)))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&EL.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),tk&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Px().createGain()),this._output.setNode(Px().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!uO&&!tk)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;cO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(EL.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info("mixAudioReference() => ".concat(t));let r=Wx(e);if(!r)return;let i=new xx,o=Px().createGain();o.gain.value=1;let n=new xx;i.pipeTo(n).pipeTo(this.pipeline.mixNode),i.setNode(r),n.setNode(o),this.mixedAudioReferenceMap.set(t,[i,n])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info("unMixAudioReference() => ".concat(e)),t.deleteNode(),null==r||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,i]=this.mixedAudioReferenceMap.get(e)||[];null!=i&&i.node&&(i.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(i.node.gain.value)))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach((e=>{let[t,r]=e;t.deleteNode(),r.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),$x.off("audioInputAdded",this.handleMicrophoneAdded,this),$x.off("audioInputRemoved",this.handleMicrophoneRemoved,this),WO.off(GO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ow(this,null,(function*(){try{yield iw(e.prototype,this,"recapture").call(this,t,r)}catch(iM){let i=(yield eU()).find((e=>e.deviceId!==t));if(!i)throw iM;yield iw(e.prototype,this,"recapture").call(this,i.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,ntp:fw()}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}handleAudioContextLongSuspended(e){let{isSuspended:t}=e;if(this.pipeline.isProcessEnabled)if(t){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(hO?"":", non-Safari"));let e=this.sourceTrack||this.mediaTrack;e&&this.setOutputMediaStreamTrack(e)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}},$F=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,r=[],i=0;for(let n=e;n<=t;n++){let e=this.dataView.getInt8(n);switch(e){case 0:case 1:case 2:case 3:2===i&&(r.push(3),i=0),0==e?i++:i=0,r.push(e);break;default:i=0,r.push(e)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...r]).buffer);this.dataView=o}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,r=[],i=0;for(let n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:i++,r.push(this.dataView.getInt8(n));break;case 3:2!==i&&r.push(this.dataView.getInt8(n)),i=0;break;default:r.push(this.dataView.getInt8(n)),i=0}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...r]).buffer);this.dataView=o}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 o=6;o<this.dataView.buffer.byteLength;o++){let r=this.dataView.getUint8(o);if(t++,255!==r){e+=r;break}e+=255}let r=new ArrayBuffer(e),i=new DataView(r);for(let o=0;o<r.byteLength;o++,t++)i.setInt8(o,this.dataView.getInt8(t));return i}},QF=class{constructor(){rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,r=parseInt(String(t/255),10),i=t%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<r;a++)o.push(255);o.push(i);let n=new DataView(e);return o.push(...new Uint8Array(n.buffer)),o.push(128),new $F(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}isEmpty(){return!this._seiMessageList.length}getNaluCount(e){let t=0,r=0,i=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(i.getUint8(o)){case 0:t++;break;case 1:(2===t||3===t)&&r++,t=0;break;default:t=0}return r}encode(e,t){let r=t?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let i=r.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),o=i.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(o+e.data.byteLength),a=new DataView(n),s=new DataView(e.data),c=0;for(let e=0;e<i.length;e++)for(let t=0;t<i[e].dataView.byteLength;t++)a.setInt8(c++,i[e].dataView.getInt8(t));for(let r=0;r<e.data.byteLength;r++)a.setInt8(c++,s.getInt8(r));return e.data=n,i.length}return 0}},ZF=class e extends YF{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,yx),rw(this,"profile",Xb({},Yw)),rw(this,"avoidCropping",!1),rw(this,"_scaleResolutionDownBy"),rw(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),rw(this,"small"),rw(this,"isNeedToSetBandwidth"),rw(this,"muteImage"),rw(this,"manager"),rw(this,"_seiCodec",new QF),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($b(Xb({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(iP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(t){return ow(this,null,(function*(){var r,i,o;if(BD(t)){if(this.muteImage===t)return;yield null==(r=this.manager)?void 0:r.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:t}),this.muteImage=t,iw(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(o=this.manager)?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),iw(e.prototype,this,"setMute").call(this,t)}))}capture(t){return ow(this,arguments,(function(t){var r=this;let{deviceId:i,facingMode:o,useExactDeviceId:n=!0,customSource:a,retryWhenExactFailed:s=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:o||r.facingMode,cameraId:i,width:r.profile.width,height:r.profile.height,frameRate:r.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:s,customSource:a};if("environment"===t.facingMode){let e=yield r.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return iw(e.prototype,r,"capture").call(r,t)}()}))}setProfile(e){let t=this.fallbackProfile(e);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($b(Xb({},this.profile),{width:1920,height:1080})))}applyProfile(){return ow(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:r=0}=(this.sourceTrack||this.mediaTrack).getSettings(),i=t*r,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(16===EO&&this.deviceId?yield this.recapture(this.deviceId):(yield null==(e=this.sourceTrack||this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),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){this.isNeedToSetBandwidth=!1;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t;return n&&r&&i&&r===i?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:$w.VIDEO,videoType:$w.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return iP&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:AN(this.settings,this.profile)}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 ow(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),WO.emit(GO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(RC){throw this.log.error("switch camera failed ".concat(RC)),this.deviceId&&this.recapture(this.deviceId),RC}}))}getDeviceIdWhenUsingBackCamera(){return ow(this,null,(function*(){let e;try{if(Kk&&!tO&&nP){let t=(yield tU(!0)).map((e=>{var t;return $b(Xb({},e),{capabilities:null==(t=e.getCapabilities)?void 0:t.call(e)})})).filter((e=>{var t,r;return null==(r=null==(t=e.capabilities)?void 0:t.facingMode)?void 0:r.includes("environment")})),r=t[0];t.forEach((e=>{var t,i,o,n;let{capabilities:a}=e;(null!=(t=a.width)&&t.max&&null!=(i=a.height)&&i.max?a.width.max*a.height.max:0)>(null!=(o=r.capabilities.width)&&o.max&&null!=(n=r.capabilities.height)&&n.max?r.capabilities.width.max*r.capabilities.height.max:0)&&(r=e)})),null!=r&&r.capabilities&&(this._log.info("use max resolution back camera",r),e=r.deviceId)}}catch(RC){this._log.warn("get max res camera failed",RC)}return e}))}updateSmallConfig(e){var t,r;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let i=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),i&&(null==(r=this.room)||r.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.width>e.height,i=Xb({},e);return e.width*e.height<=19200&&rk&&nO&&(this.log.warn("".concat(t?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),i.width=r?240:180,i.height=r?180:240,i.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&TO&&(i.width=r?1280:720,i.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),_O(fO,"14.3")&&gO(fO,"14.0",!0)&&this.on("7",(()=>{let e=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=e?640:480,this.profile.height=e?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=e?640:360,this.profile.height=e?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))})),!t&&this.avoidCropping&&(nO||ak)&&!CO()&&e.width*e.height<=230400&&e.width/e.height==16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),i}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){$x&&!$x.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&$x.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return ow(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(KF[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){HB(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield tU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&$x.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return ow(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||($x.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}))}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,mediaType:r}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return FD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){$x.off("videoInputAdded",this.handleCameraAdded,this),$x.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return ow(this,null,(function*(){try{yield iw(e.prototype,this,"recapture").call(this,t)}catch(RC){let i=(yield tU()).find((e=>e.deviceId!==t));if(!i)throw RC;yield iw(e.prototype,this,"recapture").call(this,i.deviceId)}}))}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||FD(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};tw([vU((function(e){this.setContentHint(e.contentHint||"motion")}))],ZF.prototype,"capture",1);var eB=ZF,tB={};Zb(tB,{REPORT_TYPE:()=>wN,buildSSOPackage:()=>CN,bytes2ms:()=>CD,calculateScaleResolutionDownNumber:()=>AN,concatArrayBuffers:()=>DN,convertObjectNumberToInt:()=>EN,copyProperties:()=>wD,deepClone:()=>cN,deepCloneBasic:()=>bN,deepMerge:()=>sN,delay:()=>vN,fibonacci:()=>PD,formatedTime:()=>uN,getConstructorName:()=>JD,getContainerFromElement:()=>dN,getEnv:()=>vD,getFirst16Bits:()=>kN,getInternalVersion:()=>tN,getLast16Bits:()=>NN,getLoggerUrl:()=>TD,getMediaStreamTrackInfo:()=>IN,getMuteStateFromFlag:()=>oN,getNetworkType:()=>AD,getNumNetworkType:()=>bD,getReconnectionTimeout:()=>xD,getStringByteLength:()=>mN,getTurnServer:()=>nN,getUint32Version:()=>gN,getValueType:()=>UD,getViewListFromView:()=>lN,glog:()=>OD,ipv4ToUint32:()=>aN,isArray:()=>GD,isAudioWorkletSupported:()=>XD,isBoolean:()=>WD,isConstructor:()=>YD,isEmpty:()=>iN,isFunction:()=>VD,isLangChinese:()=>MD,isMediaStreamTrack:()=>zD,isNumber:()=>HD,isObject:()=>jD,isOverseaSdkAppId:()=>yD,isPlainObject:()=>LD,isPortrait:()=>fN,isPromise:()=>qD,isRemoteTrack:()=>KD,isRotate90Or270:()=>SN,isSetSinkIdSupported:()=>$D,isString:()=>BD,isUndefined:()=>FD,loadImage:()=>_N,loadVideo:()=>RN,ms2bytes:()=>ND,ms2samples:()=>kD,normalizeUrl:()=>TN,performanceNow:()=>ZD,promiseAny:()=>QD,samples2ms:()=>DD,setNetworkType:()=>RD,stringify:()=>hN,stringifyIncludeValue:()=>pN,throttlePromise:()=>yN});var rB=[-1,-1,1,-1,-1,1,1,1],iB=[0,0,1,0,0,1,1,1],oB=class e extends PP{constructor(e,t){if(super(),this.context=e,rw(this,"name"),rw(this,"input"),rw(this,"output"),rw(this,"texture"),rw(this,"ctx2d",null),rw(this,"fbo"),rw(this,"width",0),rw(this,"height",0),rw(this,"x",0),rw(this,"y",0),rw(this,"program"),rw(this,"vertexShader"),rw(this,"fragmentShader"),rw(this,"totalFrames",0),rw(this,"dropFrames",0),rw(this,"matchInputSize",!0),rw(this,"texCoordBuffer"),rw(this,"positionBuffer"),rw(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),rw(this,"cost",0),rw(this,"_canvas",null),rw(this,"_image"),rw(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof TB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==EO?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(iB),this.positionBuffer=this.createBuffer(rB),!1!==t.createTexture&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(iM){this.context.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(iM.message||iM)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return e.addInput(this,...r),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 yB&&this.render(e)||this.context instanceof TB&&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)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];null==(e=this.output)||e.removeInput(this,...r),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 yB){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,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];r.forEach(((t,r)=>{t&&(e.activeTexture(e.TEXTURE0+r),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,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}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 r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];r.forEach(((t,r)=>{e.enableVertexAttribArray(r),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(r,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 r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.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 r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(t,r,i,o,n,a,s,c,l){let d=!(FD(a)||FD(s)||FD(c)||FD(l));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,r,i,a,s,c,l):this.ctx2d.putImageData(t,r,i),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,a,s,c,l,r,i,o,n):this.ctx2d.drawImage(t,r,i,o,n),this.emit(e.RENDER,t)),"undefined"!=typeof VideoFrame&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:t,x:r,y:i,width:o,height:n,name:a,cost:s}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:r,y:i,width:o,height:n,timestamp:c,fps:l,name:a,cost:s},Xb({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),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.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};rw(oB,"RENDER","render"),tw([OP(PP.INIT,"connected",{sync:!0})],oB.prototype,"connect",1),tw([OP("connected",PP.INIT,{ignoreError:!0,sync:!0})],oB.prototype,"disconnect",1),tw([OP([],"closed",{sync:!0})],oB.prototype,"close",1);var nB=oB,aB=FU(fV(250),hF((()=>performance.now())),qU()),sB=e=>t=>{let r=performance.now();FU(aB,KV((t=>t-r<e)),BV(1))(t)},cB=[0,1,1,1,0,0,1,0],lB=class extends nB{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),rw(this,"_intervalId",0),rw(this,"_sequence",0),rw(this,"checkGLError",!1),rw(this,"checkVisibilityChange"),e instanceof TB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(cB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),HP.clearTask(this._intervalId),this._intervalId=HP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(HP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof yB){let e=this.context.ctx.getError();e&&this.context.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:5,message:"".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(),this.emit(nB.RENDER,this.context._canvas),!0)}addInput(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];super.addInput(e,...r),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;"closed"!==this.state&&(this._intervalId&&(HP.clearTask(this._intervalId),this._intervalId=0,1===e&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),HP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),HP.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},dB=class extends lB{constructor(e,t){super(e,t),rw(this,"_videoTrack"),rw(this,"_muteOb"),rw(this,"_closedOb",vV(this,"closed")),rw(this,"_subscription"),rw(this,"_canvasContainer"),Number(pO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=vV(this._videoTrack,"mute"),FU(vV(this._videoTrack,"ended"),HV(this._closedOb),WF((()=>{this.context.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=FU(this._muteOb,HV(this._closedOb),yF(sB(5e3)),VV((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),WF((()=>{this.context.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},uB=class extends dB{render(e){var t;let r=!(null==(t=this.input)||!t.requestFrame(e));if(this.context._canvas2d){let e=this.context._canvas2d.getContext("2d");e.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),e.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return r}},hB=class extends dB{constructor(e,t,r){super(e,{name:"smallDestination",logger:r}),this.resolution=t}resize(e,t){let r,i=e*t,o=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),i>o?r=i/o:(this.log.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)),r=i/19200),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}},pB=class extends nB{constructor(e,t){super(e,Xb({name:"imageSource"},t)),rw(this,"_lastImage"),rw(this,"_totalFrames",0),rw(this,"_autoResize",!1),rw(this,"_canvasRendered"),rw(this,"videoCallbackId",0),rw(this,"waitingFirstFrame",!0),rw(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===EO&&(this._canvasRendered=aV(),FU(this._canvasRendered,tV(this._image),EF((e=>e instanceof HTMLCanvasElement?vV(e,"rendered"):kV())),HV(vV(this,"closed")),WF((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),EP()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var r;let{width:i,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:i,videoHeight:o}=n),!i||!o)return!1;n.width=i,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:i,height:o}=n),n!==this._lastImage)this._lastImage=n;else if(i===this.width&&o===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?(({width:i,height:o}=n),this._lastImage=n):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame&&(({displayWidth:i,displayHeight:o}=n),null==(r=this._lastImage)||r.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===i&&this.height===o&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(i,o)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},mB=class extends pB{constructor(e,t,r){super(e,r),this._player=t,this.name="videoPlayerSource",FU(vV(this._player,WP.PLAYER_STATE_CHANGED),HV(vV(this,"closed")),VV((e=>{let{state:t}=e;return"PLAYING"===t})),WF((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},fB=class extends mB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,r){super(e,new yx({id:r.name,track:t,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},_B=class extends nB{constructor(e,t,r){super(e,$b(Xb({name:"textSource"},r),{create2d:!0})),rw(this,"hasChange",!0),rw(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return(null==(e=this.ctx2d)?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return(null==(e=this.ctx2d)?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:i}=this;super.resize(e,t),this.color=r,this.font=i}drawMultilineText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1.2;if(!this.ctx2d)return;let i=this.ctx2d.measureText(this.content);t+=i.fontBoundingBoxAscent||i.actualBoundingBoxAscent||0;let o=this.font.match(/(\d+)px/),n=(o?parseInt(o[1],10):16)*r,a=this.content.split("\n");for(let s=0;s<a.length;s++)this.ctx2d.fillText(a[s],e,t+s*n)}},gB=class extends PP{constructor(e){super(),rw(this,"frameRate"),rw(this,"_canvas"),rw(this,"log"),rw(this,"hasAlpha",!1),rw(this,"name"),rw(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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,t){return new fB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new dB(this,e)}createVideoImageSource(e,t){return new pB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new mB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new _B(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};rw(gB,"_ids",0);var EB={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},vB=class extends gB{constructor(){super(...arguments),rw(this,"defaultProgam"),rw(this,"defaultVShader"),rw(this,"defaultFShader"),rw(this,"ctx"),rw(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(gB._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",EB),!this.ctx)throw new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:2,message:"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 pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,EL.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;null==(r=this.ctx)||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,i=r.createShader(e);return r.shaderSource(i,t),r.compileShader(i),i}createProgram(e,t){let r=this.ctx,i=r.createProgram();return r.attachShader(i,e),r.attachShader(i,t),r.linkProgram(i),r.getProgramParameter(i,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(i)),i}};rw(vB,"UNAVAILABLE","unavailable"),tw([OP(PP.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),EL.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),EL.addSuccessEvent({key:512700})}})],vB.prototype,"create",1),tw([OP("created",PP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(vB.UNAVAILABLE,e),this.removeAllListeners()}})],vB.prototype,"destroy",1);var yB=vB,TB=class extends gB{constructor(){super(...arguments),rw(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(gB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",(()=>{this.log.error("2d context lost")})),this._canvas.addEventListener("contextrestored",(()=>{this.log.warn("2d context restored")}))}destroy(e){let t="";e&&(t=e.message,this.error=e,EL.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),EL.addSuccessEvent({key:512703})}};function IB(e,t,r,i,o){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([r,i]=[i,r]);let n={sWidth:e,sHeight:t,dWidth:r,dHeight:i,sx:0,sy:0,dx:0,dy:0};if(0===e||0===t)return n;switch(o){case void 0:case"fill":break;case"contain":{let o=Math.min(r/e,i/t);n.dWidth=e*o,n.dHeight=t*o,n.dx=(r-n.dWidth)/2,n.dy=(i-n.dHeight)/2;break}case"cover":{let o=Math.max(r/e,i/t),a=r/o,s=i/o;n.sx=(e-a)/2,n.sy=(t-s)/2,n.sWidth=a,n.sHeight=s;break}}return n}tw([OP(PP.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),EL.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),EL.addSuccessEvent({key:512701})}})],TB.prototype,"create",1),tw([OP("created",PP.INIT,{ignoreError:!0,sync:!0})],TB.prototype,"destroy",1);var AB=class{constructor(e,t){this.node=e,this.layout=t,rw(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}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},SB=class extends nB{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),rw(this,"inputs",[]),rw(this,"backgroundColor","black")}addInput(e,t){let r=0,i=this.inputs.length;for(;r<i;){let e=Math.floor((r+i)/2);if(this.inputs[e].layout.zIndex<t.zIndex)r=e+1;else{if(!(this.inputs[e].layout.zIndex>t.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));i=e}}let o=new AB(e,t);this.inputs.splice(r,0,o)}changeInputLayout(e,t){let r=this.inputs.findIndex((t=>t.node===e));if(r<0)return;let{x:i,y:o,width:n,height:a,zIndex:s,fillMode:c,rotation:l,hidden:d}=t;if(!FD(s)&&this.inputs.some((t=>t.layout.zIndex===s&&t.node!==e)))throw new Error("input already exists at zIndex ".concat(t.zIndex));let u=this.inputs[r];FD(i)||(u.layout.x=i),FD(o)||(u.layout.y=o),FD(n)||(u.layout.width=n),FD(a)||(u.layout.height=a),FD(l)||(u.layout.rotation=l),FD(d)||(u.layout.hidden=d),c&&(u.layout.fillMode=c),!FD(s)&&s!==u.layout.zIndex&&(u.layout.zIndex=s,this.inputs.sort(((e,t)=>e.layout.zIndex-t.layout.zIndex)))}hasInput(e){return this.inputs.some((t=>t.node===e))}hasNoInput(){return 0===this.inputs.length}resize(e,t){if(!this.matchInputSize)return void super.resize(e,t);let r=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(r.width,r.height),this.context instanceof yB&&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,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return super.connect(e,...r),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter((t=>t.node!==e)),0===this.inputs.length&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce(((t,r)=>r.node.requestFrame(e)||t),!1)&&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.forEach((t=>t.node.requestFrame(e))),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(t.hidden)continue;let r=IB(t.node.width,t.node.height,t.width,t.height,t.fillMode,SN(t.rotation));this.draw2d(t.node.image,t.x+r.dx,t.y+r.dy,r.dWidth,r.dHeight,r.sx,r.sy,r.sWidth,r.sHeight)}return!0}return!1}debugLayout(e,t,r,i){let o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(o&&([r,i]=[i,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,i),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:i,height:o,name:n}=this,a=Date.now(),s=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:r,width:i,height:o,timestamp:a,fps:s,name:n},Xb({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}removeAllInputs(){this.inputs.forEach((e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof yB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(iM){}}))}close(){super.close(),this.removeAllInputs()}},RB=[1,0,0,0,1,1,0,1],bB=class extends nB{constructor(e,t,r,i){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),rw(this,"mirror",!1),rw(this,"rotation",0),r&&(this.mirror=r),i&&(this.rotation=i),e instanceof yB)try{this.setTexBuffer(RB)}catch(Sw){e.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Sw.message||Sw)}))}}draw2d(e,t,r,i,o){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),90===this.rotation?(this.ctx2d.translate(i,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(o/i,i/o)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,o),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(o/i,i/o));let n=super.draw2d(e,t,r,i,o);return this.ctx2d.restore(),n}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(e,t){SN(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},wB=class extends YF{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,yx),rw(this,"inputLocalVideoTracks",new Map),rw(this,"inputLocalScreenTracks",new Map),rw(this,"cameraNodeMap",new Map),rw(this,"screenNodeMap",new Map),rw(this,"textNodeMap",new Map),rw(this,"imageNodeMap",new Map),rw(this,"videoNodeMap",new Map),rw(this,"endedIds",new Set),rw(this,"videoContext"),rw(this,"mixNode"),rw(this,"destination"),rw(this,"manager"),rw(this,"stat"),rw(this,"_checkId",0),rw(this,"autoSetFps",!0),this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(nB.RENDER,(e=>{this.emit("render",e)})),this.mixNode=new SB(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=HP.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new TB({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout((()=>{var e;return null==(e=this.destination)?void 0:e.start(this.videoContext.frameRate)}),500)}setFpsAuto(){var e;if(!this.autoSetFps)return;for(let o of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])o.shouldUpdate=!1;let t=null,r=0,i=!0;for(let[o,n]of this.inputLocalVideoTracks)if(n.profile.frameRate>r){if(this.endedIds.has(o)){let e=this.cameraNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}r=n.profile.frameRate,t=o}for(let[o,n]of this.inputLocalScreenTracks)if(n.profile.frameRate>r){if(this.endedIds.has(o)){let e=this.screenNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}r=n.profile.frameRate,t=o,i=!1}if(null!==t){let e=i?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);e&&(e.shouldUpdate=!0,e.tryVideoFrameCallback()),this.log.info("set mix fps: ",r)}else null==(e=this.destination)||e.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;null==(r=this.mixNode)||r.resize(e,t)}startMix(){return ow(this,null,(function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),hO&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),null==(e=this.manager)||e.changeInput(this)}))}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error("There is already a cameraSource with the same ID: ".concat(e));let i,{mediaTrack:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,zP(this,$x).add("videoInputRemoved",(r=>{r.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())})),t.on("output-media-track-changed",(()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)})),i=16===EO&&o instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),i.resize(t.settings.width,t.settings.height),i.shouldUpdate=!1,this._connectMix(i,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,i),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error("There is already a screenSource with the same ID: ".concat(e));let{mediaTrack:i}=t;if(!i)throw new Error("no mediaTrack, add cameraSource failed");let o=this.videoContext.createVideoTrackSource(i,"screenNodeSource");o.resize(t.settings.width,t.settings.height),o.shouldUpdate=!1,this._connectMix(o,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,o),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:i,color:o,layout:n}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let a=this.videoContext.createTextSource({content:r,font:i,color:o});a.resize(n.width,n.height),this._connectMix(a,n),this.textNodeMap.set(t,a)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error("There is already a imageSource with the same ID: ".concat(e));let i=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});i.resize(t.width,t.height),this._connectMix(i,r),this.imageNodeMap.set(e,i)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error("There is already a videoSource with the same ID: ".concat(e));let i=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});i.resize(t.videoWidth,t.videoHeight),i.shouldUpdate=!1,this._connectMix(i,r),this.videoNodeMap.set(e,i)}updateCameraSource(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3?arguments[3]:void 0,o=this.cameraNodeMap.get(e);if(o){if(r){if(16===EO&&r instanceof CanvasCaptureMediaStreamTrack)if(o instanceof fB){let t=o.output;o.close(),o=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),o.connect(t),this.cameraNodeMap.set(e,o)}else o.image=r.canvas;else if(o instanceof fB)o.replaceTrack(r);else{let t=o.output;o.close(),o=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),o.connect(t),this.cameraNodeMap.set(e,o)}let{width:t,height:i}=r.getSettings();t&&i&&o.resize(t,i)}i&&o.resize(i.width,i.height),(i||r)&&this.setFpsAuto(),this._changeMixLayout(o,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:i,color:o,layout:n}=e,a=this.textNodeMap.get(t);a&&(FD(r)||(a.content=r),FD(i)||(a.font=i),FD(o)||(a.color=o),a.resize(n.width,n.height),this._changeMixLayout(a,n))}updateImageSource(e,t,r){let i=this.imageNodeMap.get(e);i&&(r&&(i.image=r,i.resize(r.width,r.height)),this._changeMixLayout(i,t))}updateVideoSource(e,t,r){let i=this.videoNodeMap.get(e);if(i){if(r){let e=i.image;e instanceof HTMLVideoElement&&this.stopVideoElement(e),i.image=r,i.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(i,t)}}_connectMix(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:i,rotation:o}=t;e.disconnect();let n=new bB(this.videoContext,this.log,i,o);n=e.connect(n),t.fillMode||(t.fillMode=r),n.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:i}=t,o=e.output||e;o instanceof bB&&(FD(r)||(o.mirror=r),FD(i)||(o.rotation=i),o.resize(e.width,e.height)),this.mixNode.changeInputLayout(o,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof bB&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof bB&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof bB&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof bB&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof bB&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),HP.clearTask(this._checkId),null==(e=this.videoContext)||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),KP(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},CB=YO();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:CB,exposeOrigin:!0,permittedOrigins:["*"]})}catch(yH){}var DB=function(e){return ow(this,null,(function*(){let t=null,r=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},r={width:uO?{max:e.width}:{ideal:e.width,max:e.width},height:uO?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=r,e.systemAudio){let{echoCancellation:r=!0,noiseSuppression:i=!1,autoGainControl:o=!1}=e;t.audio={echoCancellation:r,noiseSuppression:i,autoGainControl:o,sampleRate:48e3}}return t}(e);qO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(r)));let i=yield navigator.mediaDevices.getDisplayMedia(r);e.systemAudio&&0===i.getAudioTracks().length&&(aO&&cO<74||uO||ak)&&qO.warn("Your browser not support capture system audio");let o=i.getVideoTracks()[0];if(o){if(e.frameRate)try{yield o.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(aM){qO.warn("screen applyConstraints failed: ".concat(aM))}e.captureElement&&(yield function(e,t){return ow(this,null,(function*(){var r;if("CropTarget"in window&&"fromElement"in CropTarget&&VD(e.cropTo))try{if((null==(r=e.getCaptureHandle())?void 0:r.handle)!==CB)return;let i=yield CropTarget.fromElement(t);yield e.cropTo(i)}catch(i){qO.warn("cropTo target failed ".concat(i))}}))}(o,e.captureElement))}if(e.audio){let r=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return FD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);qO.info("getUserMedia with constraints: ".concat(JSON.stringify(r))),t=yield navigator.mediaDevices.getUserMedia(r),i.addTrack(t.getAudioTracks()[0])}return i}))},NB=class extends eB{constructor(e){super(e,2),rw(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),rw(this,"objectFit","contain"),rw(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return CB===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(iM){return}}capture(e){return ow(this,arguments,(function(e){var t=this;let{systemAudio:r=!1,autoGainControl:i,echoCancellation:o,noiseSuppression:n,audioTrack:a,videoTrack:s,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return s||a?(e=new MediaStream,s&&e.addTrack(s),a&&e.addTrack(a)):(e=yield DB({audio:!1,systemAudio:r,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:i,echoCancellation:o,noiseSuppression:n,captureElement:c,preferDisplaySurface:l}),t.sourceTrack=e.getVideoTracks()[0]),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof pw?e:new pw({code:uw.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return ow(this,null,(function*(){throw new Error("Method not implemented.")}))}};tw([vU((function(e){this.setContentHint(e.contentHint||"detail")}))],NB.prototype,"capture",1);var kB,OB=class extends XF{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function MB(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3?arguments[3]:void 0;return ow(this,null,(function*(){let o=Px();kB||(kB=Tx(o,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),yield kB;let n=o.sampleRate,a=new AudioWorkletNode(o,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:n,targetSampleRate:t}});return a.channelCountMode="explicit",a.channelCount=r,i&&a.port.postMessage({port:i},[i]),e.forEach(((e,t)=>e.connect(a,0,t))),new ReadableStream({start(e){a.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(a))),a.port.close()}})}))}var LB=class extends Bx{constructor(e){super(),this.room=e,rw(this,"_localAudioTrack"),rw(this,"_localScreenAudioTrack"),rw(this,"log",qO.createLogger({id:"am"})),rw(this,"denoiser"),rw(this,"voiceChanger"),rw(this,"mixChangedDebounce"),rw(this,"audioProcessor"),rw(this,"encodePipeline",[]),rw(this,"decodePipeline",[]),rw(this,"getPCMAbortCtrlMap",new Map),rw(this,"audioFrameEventConfigMap",new Map),rw(this,"audioReferenceMap",new Map),rw(this,"isLocalAudioNeedAudioProcess",!1),rw(this,"isScreenAudioNeedAudioProcess",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return null==(e=this._localScreenAudioTrack)?void 0:e.pipeline}dump(e){var t,r;if(!this._localAudioTrack)return;let i=[],o=[];null!=(t=this._localAudioPipline)&&t.source.node&&(i.push(this._localAudioPipline.source.node),o.push("mic")),null!=(r=this._localAudioPipline)&&r.denoiser.node&&(i.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(i.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info("dump audio track ".concat(o,", duration: ").concat(e));let n=new AbortController,a=[],s=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<o.length;e++){let t=URL.createObjectURL(new Blob(a[e])),r=document.createElement("a");r.href=t,r.download="".concat(o[e],".pcm"),r.style.display="none",document.body.appendChild(r),r.click(),URL.revokeObjectURL(t),r.remove()}clearTimeout(s),n.abort("download")},l=MB(i).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>a[t]=a[t]?a[t].concat(e[0]):[e[0]]))}}),n).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e,t){var r,i,o;if("undefined"==typeof WritableStream)return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:n,sampleRate:a=48e3,channelCount:s=1,port:c}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!n)return;this.log.info("getPCM ".concat(t||"local"));let l,d,u=Math.floor(.04*a),h=new Float32Array(u),p=new Float32Array(u),m=0,f=new AbortController,_=""===t?null==(r=this._localAudioTrack)?void 0:r.mediaTrack:null==(o=null==(i=this.room)?void 0:i.remotePublishedUserMap.get(t))?void 0:o.remoteAudioTrack.mediaTrack;if(_)return MB([Px().createMediaStreamSource(new MediaStream([_]))],a,s,c).then((r=>r.pipeTo(new WritableStream({write(r){r[0][0]&&(m+r[0][0].length>u?(h.set(r[0][0].subarray(0,u-m),m),l=r[0][0].subarray(u-m),r[0][1]&&(p.set(r[0][1].subarray(0,u-m),m),d=r[0][1].subarray(u-m)),m+=u-m):(l&&(h.set(l,m),m+=l.length,l=void 0),d&&(p.set(d,m),d=void 0),h.set(r[0][0],m),r[0][1]&&p.set(r[0][1],m),m+=r[0][0].length),m>=u&&(m=0,e({userId:t,sampleRate:a,channelCount:s,data:1===s?h:[h,p]}),h=new Float32Array(u),p=new Float32Array(u)))}}),f).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),f;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!FD(this._localScreenAudioTrack)}get hasAudioTrack(){return!FD(this._localAudioTrack)}changeInput(e){var t,r;return e instanceof OB?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&null!=(t=this.audioProcessor)&&t.screenAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,r)=>{e.mixAudioReference(t,r)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof XF?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&null!=(r=this.audioProcessor)&&r.localAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,r)=>{e.mixAudioReference(t,r)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof UB?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixAudioReference(e,t){var r;null==(r=this._localAudioTrack)||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;null==(t=this._localAudioTrack)||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;null==(r=this._localAudioTrack)||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([null==(e=this._localAudioTrack)?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}removeInput(e){e instanceof OB?delete this._localScreenAudioTrack:e instanceof XF&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,r,i){var o;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:i},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach(((e,t)=>{var r;null==(r=this._localAudioTrack)||r.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&i&&(null==(o=this._localScreenAudioTrack)||o.addAudioProcessor(i,e,t),this.audioReferenceMap.forEach(((e,t)=>{var r;null==(r=this._localScreenAudioTrack)||r.mixAudioReference(e,t)})))}removeDenoiser(e){var t;return delete this.denoiser,null==(t=this._localAudioTrack)?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],null==(r=this._localAudioTrack)||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,i;delete this.audioProcessor,null==(r=this._localAudioTrack)||r.removeAudioProcessor(e),null==(i=this._localScreenAudioTrack)||i.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach((e=>null==e?void 0:e.abort("destroy"))),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(e){let{processor:t,type:r}=e;var i;this.encodePipeline.includes(t)||(this.encodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:r}=e;var i;this.decodePipeline.includes(t)||(this.decodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}handleLocalTrackStarted(e){let{room:t,userId:r}=e;var i;if(t!==this.room||this.getPCMAbortCtrlMap.get(r))return;let o=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(r,o),this.getPCMAbortCtrlMap.get(r)&&(null==(i=this._localAudioTrack)||i.on("input-media-track-changed",(()=>{let e=this.getPCMAbortCtrlMap.get(r);e&&(e.abort("inputMediaTrackChanged"),e=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),""),this.getPCMAbortCtrlMap.set(r,e))})))}handleLocalTrackStopped(e){let{room:t,userId:r}=e;if(t!==this.room)return;let i=this.getPCMAbortCtrlMap.get(r);i&&(i.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(r))}handleRemoteTrackStarted(e){let{room:t,userId:r}=e;if(t===this.room&&!this.getPCMAbortCtrlMap.get(r)){let e=this.room.audioManager.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),r);this.getPCMAbortCtrlMap.set(r,e)}}handleRemoteTrackStopped(e){let{room:t,userId:r}=e;if(t!==this.room)return;let i=this.getPCMAbortCtrlMap.get(r);i&&(i.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(r))}installEvent(){WO.on("113",this.handleLocalTrackStarted,this),WO.on("114",this.handleLocalTrackStopped,this),WO.on("115",this.handleRemoteTrackStarted,this),WO.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){WO.off("113",this.handleLocalTrackStarted),WO.off("114",this.handleLocalTrackStopped),WO.off("115",this.handleRemoteTrackStarted),WO.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:r,refId:i,volume:o}=e;if("add"===t){if(this.audioReferenceMap.get(i)||!r||(this.audioReferenceMap.set(i,r),!this.audioProcessor))return;this.mixAudioReference(r,i)}else if("remove"===t)this.audioReferenceMap.get(i)&&(this.audioReferenceMap.delete(i),this.unMixAudioReference(i));else if("updateVolume"===t){if(!this.audioProcessor||FD(o))return;this.setAudioReferenceVolume(i,o)}}};var PB=class e extends uU{constructor(t,r,i){super({userId:r.userId,sdkAppId:t.sdkAppId,mediaType:i,room:t}),this.room=t,this.user=r,rw(this,"tinyId"),rw(this,"isRemote",!0),rw(this,"jitterBufferDelay",0),rw(this,"availableState"),rw(this,"remotePublishState"),rw(this,"_triggerCheckDecodeSubject",aV(vV(this,e.STATE_SUBSCRIBE))),this.tinyId=r.tinyId,this.availableState=new PP("".concat(r.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new PP("".concat(r.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),FU(YU(vV(this,PP.STATECHANGED),vV(this.remotePublishState,PP.STATECHANGED)),hF((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),WF((e=>{this.availableState.state!==(e?PP.ON:PP.OFF)&&(this.availableState.state=e?PP.ON:PP.OFF),this.updatePlayingState(e)})));let o=FU(vV(this.player,WP.ERROR),VV((e=>e.code===MediaError.MEDIA_ERR_DECODE))),n=FU(_V(5e3),VV((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===$w.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),a=FU(JU(o,n),HV(vV(this,PP.INIT)));FU(this._triggerCheckDecodeSubject,VV((()=>!this.ignoreDecodeError)),yF(a),WF((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===PP.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var r,i;let o=this.kind===$w.AUDIO;if(EL[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let t=(null==(r=this.room)?void 0:r.downlinkVideoCodec.toUpperCase())||"H264";EL[e?"addSuccessEvent":"addFailedEvent"]({key:fL["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(i=this.room)?void 0:i.downlinkVideoCodec," decode failed"))}e||(EL.addEnum({key:o?504701:514703,value:xO()}),qP.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(OO()||VO()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===$w.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?PP.ON:PP.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};rw(PB,"STATE_SUBSCRIBE","subscribe"),tw([function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return yU(((r,i)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];return new Promise(((o,a)=>{let s=setTimeout((()=>{let r=new pw({code:uw.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(i,"() timeout ").concat(e,"s")});(this.log||this._log||qO).warn(r),2===t?a(r):1===t&&o()}),1e3*e);r.apply(this,n).then(o,a).finally((()=>{clearTimeout(s)}))}))}))}(5,1)],PB.prototype,"waitHasMediaTrack",1),tw([OP(PP.INIT,PB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),WO.emit(GO.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),wU(521716,!1)],PB.prototype,"subscribe",1),tw([OP(PB.STATE_SUBSCRIBE,PP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),WO.emit(GO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],PB.prototype,"unsubscribe",1);var xB=PB,UB=class extends xB{constructor(e,t){super(e,t,1),rw(this,"volume",0),rw(this,"mediaType",1),rw(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return Kx.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return!!this.manager&&(this.manager.decodePipeline.some((e=>e))||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&dP().AudioDecoder&&aP)}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,i]of this.manager.decodePipeline.entries()){if(!i)continue;let o={frame:e,track:this};if(1===r&&this.isAvailable&&"audience"===this.room.role&&(o.onAudioFrameNTPTime=e=>{let{ntp:t,frame:r,hasLeavingTag:i}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:r,hasLeavingTag:i})}),t=i(o),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var VB=class extends xB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),rw(this,"mediaType",4),rw(this,"source"),rw(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(WD(null==t?void 0:t.canvasRender)?t.canvasRender:17===EO)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new TB({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new lB(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),EP()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=(i=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e)));var i;!HD(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):r!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(r,", current: ").concat(e.frameRate)),e.frameRate=r):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(r," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},r=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let i=t.find((e=>e.uint32_video_stream_type===r));return(null==i?void 0:i.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},FB=class extends VB{constructor(e,t){super(e,t,2),rw(this,"mediaType",2),rw(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},BB=new Map;function HB(e,t){let r=$b(Xb({},t),{timestamp:fw()});BB.has(e)?BB.get(e).push(r):BB.set(e,[r])}function WB(e){if(BB.has(e)){let t=BB.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType})));return BB.delete(e),t}return[]}function jB(e,t,r,i){try{if(GD(e))for(let o=0;o<e.length;o++)GB.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:r,className:i});else GB.call(this,{rule:e,value:t[0],key:e.name,fnName:r,className:i})}catch(iM){throw qO.error(iM),iM}}function GB(e){let{rule:t,value:r,key:i,fnName:o,className:n}=e;if(FD(r)){if(t.required)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_REQUIRED,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(FD(t.defaultValue))return;r=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let i=0;i<t.type.length;i++)null===t.type[i]&&null===r&&(e=!0),VD(t.type[i])&&r instanceof t.type[i]&&(e=!0),BD(t.type[i])&&UD(r)===t.type[i].toLowerCase()&&(e=!0);if(!e)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_TYPE,data:{key:i,rule:{type:t.type.map((e=>YD(e)?JD(e):BD(e)?e:UD(e)))},fnName:o,value:r},link:{className:n,fnName:o}})})}else if(!FD(t.type)&&UD(r)!==t.type)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_TYPE,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(!1===t.allowEmpty){let e=HD(r)&&(0===r||Number.isNaN(r)),a=BD(r)&&""===r.trim();if(e||a)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_EMPTY,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})})}if(t.notLessThanZero&&HD(r)&&r<0)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.CANNOT_LESS_THAN_ZERO,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(!FD(t.min)&&HD(r)&&r<t.min)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_MIN,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(!FD(t.max)&&HD(r)&&r>t.max)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_MAX,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(BD(t.instanceOf)){if(!r||r._name!==t.instanceOf)throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_INSTANCE,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})})}else if(VD(t.instanceOf)&&!(r instanceof t.instanceOf))throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_INSTANCE,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});if(t.values&&!t.values.includes(r))throw new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.INVALID_PARAMETER_RANGE,data:{key:i,rule:t,fnName:o,value:r},link:{className:n,fnName:o}})});let{properties:a}=t;LD(a)&&jD(r)&&Object.keys(a).forEach((e=>{GB.call(this,{rule:a[e],value:r&&r[e],key:"".concat(i,".").concat(e),fnName:o,className:n})}));let{arrayItem:s}=t;LD(s)&&GD(r)&&r.forEach(((e,t)=>{GB.call(this,{rule:s,value:e,key:"".concat(i,"[").concat(t,"]"),fnName:o,className:n})})),VD(t.validate)&&t.validate.call(this,r,i,o,n,this)}WO.on(GO.JOIN_SUCCESS,(e=>{let{room:t}=e;HB(t.userId,{eventId:32788})})),WO.on(GO.LEAVE_START,(e=>{let{room:t}=e;HB(t.userId,{eventId:32789})})),WO.on(GO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),HB(t.room.userId,{eventId:e})}})),WO.on(GO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),HB(t.room.userId,{eventId:e})}})),WO.on(GO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===$w.AUDIO?HB(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):HB(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),WO.on(GO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===$w.AUDIO?HB(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):HB(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),WO.on(GO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&HB(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&HB(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&HB(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),WO.on(GO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&HB(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&HB(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&HB(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),WO.on(GO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&HB(t.room.userId,{eventId:t.kind===$w.VIDEO?32780:32781})})),WO.on(GO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&HB(t.room.userId,{eventId:t.kind===$w.VIDEO?32782:32783})})),WO.on(GO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:r,prevState:i,state:o}=e;switch(o){case"CONNECTED":t="RECONNECTING"===i?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===i?32796:32790;break;case"RECONNECTING":t=32794}t&&HB(r.userId,{eventId:t})})),WO.on(GO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:r,prevState:i,state:o,remoteUserId:n}=e,a=!!n;switch(o){case"CONNECTED":t="RECONNECTING"===i?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===i&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&HB(r.userId,{eventId:t,remoteUserId:n})})),WO.on(GO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:r,remoteUserId:i,codec:o,isHWCodec:n,prevImplementation:a,streamType:s}=e,c=n?1:0;a||(c=n?3:2);let l={H264:0,H265:1,VP8:2}[o.toUpperCase()],d={eventId:4004,param1:c,param2:l,streamType:s||2};i&&(d.remoteUserId=i,d.eventId=4005),HB(r,d),EL.addEnum({key:i?514701:513701,value:c}),EL.addEnum({key:i?514700:513700,value:l})})),WO.on(GO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:r}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===$w.AUDIO?(e.streamType=1,r&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,r&&(e.param1=8)),HB(t.userId,e)}})),ew(nw(),1);var zB=Object.create,KB=Object.defineProperty,qB=Object.defineProperties,YB=Object.getOwnPropertyDescriptor,JB=Object.getOwnPropertyDescriptors,XB=Object.getOwnPropertyNames,$B=Object.getOwnPropertySymbols,QB=Object.getPrototypeOf,ZB=Object.prototype.hasOwnProperty,eH=Object.prototype.propertyIsEnumerable,tH=(e,t,r)=>t in e?KB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,rH=(e,t)=>{for(var r in t||(t={}))ZB.call(t,r)&&tH(e,r,t[r]);if($B)for(var r of $B(t))eH.call(t,r)&&tH(e,r,t[r]);return e},iH=(e,t)=>qB(e,JB(t)),oH=(e,t,r,i)=>{for(var o,n=i>1?void 0:i?YB(t,r):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(i?o(t,r,n):o(n))||n);return i&&n&&KB(t,r,n),n},nH=(e,t,r)=>tH(e,"symbol"!=typeof t?t+"":t,r),aH=((e,t)=>function(){return t||(0,e[XB(e)[0]])((t={exports:{}}).exports,t),t.exports})({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){var r=Object.prototype.hasOwnProperty,i="~";function o(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,r,o,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new n(r,o||e,a),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function c(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(i=!1)),c.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)r.call(e,t)&&o.push(i?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},c.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,n=r.length,a=new Array(n);o<n;o++)a[o]=r[o].fn;return a},c.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},c.prototype.emit=function(e,t,r,o,n,a){var s=i?i+e:e;if(!this._events[s])return!1;var c,l,d=this._events[s],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,r),!0;case 4:return d.fn.call(d.context,t,r,o),!0;case 5:return d.fn.call(d.context,t,r,o,n),!0;case 6:return d.fn.call(d.context,t,r,o,n,a),!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,r);break;case 4:d[l].fn.call(d[l].context,t,r,o);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,r){return a(this,e,t,r,!1)},c.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},c.prototype.removeListener=function(e,t,r,o){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return s(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||s(this,n);else{for(var c=0,l=[],d=a.length;c<d;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[n]=1===l.length?l[0]:l:s(this,n)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=i,c.EventEmitter=c,void 0!==t&&(t.exports=c)}}),sH=((e,t,r)=>(r=null!=e?zB(QB(e)):{},((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of XB(t))ZB.call(e,o)||o===r||KB(e,o,{get:()=>t[o],enumerable:!(i=YB(t,o))||i.enumerable});return e})(!t&&e&&e.__esModule?r:KB(r,"default",{value:e,enumerable:!0}),e)))(aH(),1),cH=Symbol("instance"),lH=Symbol("cacheResult"),dH=class{constructor(e,t,r){this.oldState=e,this.newState=t,this.action=r,this.aborted=!1}abort(e){this.aborted=!0,fH.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},uH=class extends Error{constructor(e,t,r){super(t),this.state=e,this.message=t,this.cause=r}};var hH=new Map;function pH(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(i,o,n)=>{let a=r.action||o;if(!r.context){let r=hH.get(i)||[];hH.has(i)||hH.set(i,r),r.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let i=this;for(var o=arguments.length,n=new Array(o),c=0;c<o;c++)n[c]=arguments[c];if(r.context&&(i=_H.get("function"==typeof r.context?r.context.call(this,...n):r.context)),i.state===t)return r.sync?i[lH]:Promise.resolve(i[lH]);i.state instanceof dH&&i.state.action==r.abortAction&&i.state.abort(i);let l=null;Array.isArray(e)?0==e.length?i.state instanceof dH&&i.state.abort(i):"string"==typeof i.state&&e.includes(i.state)||(l=new uH(i._state,"".concat(i.name," ").concat(a," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e.join("|")))):e!==i.state&&(l=new uH(i._state,"".concat(i.name," ").concat(a," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e)));let d=e=>{if(r.fail&&r.fail.call(this,e),r.sync){if(r.ignoreError)return e;throw e}return r.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=i.state,h=new dH(u,t,a);fH.call(i,h);let p=e=>{var o;return i[lH]=e,h.aborted||(fH.call(i,t),null===(o=r.success)||void 0===o||o.call(this,i[lH])),e},m=e=>(fH.call(i,u,e),d(e));try{let e=s.apply(this,n);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):r.sync?p(e):Promise.resolve(p(e))}catch(sM){return m(new uH(i._state,"".concat(i.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(sM),sM instanceof Error?sM:new Error(String(sM))))}}}}var mH="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 fH(e,t){let r=this._state;this._state=e;let i=e.toString();e&&this.emit(i,r),this.emit(_H.STATECHANGED,e,r,t),this.updateDevTools({value:e,old:r,err:t instanceof Error?t.message:String(t)})}var _H=class e extends sH.default{constructor(t,r,i){super(),this.name=t,this.groupName=r,this._state=e.INIT,t||(t=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let o=i[cH];o?this.name=o.name+"-"+o.count++:i[cH]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=hH.get(e)||[],r=new Set,i=[],o=[],n=new Set,a=Object.getPrototypeOf(e);hH.has(a)&&(a.stateDiagram.forEach((e=>r.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:r,action:n}=e;"string"==typeof t?i.push({from:t,to:r,action:n}):t.length?t.forEach((e=>{i.push({from:e,to:r,action:n})})):o.push({to:r,action:n})})),i.forEach((e=>{let{from:t,to:i,action:o}=e;n.add(t),n.add(i),n.add(o+"ing"),r.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),r.add("".concat(o,"ing --\x3e ").concat(i," : ").concat(o," 🟢")),r.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:i}=e;r.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🟢")),n.forEach((e=>{e!==t&&r.add("".concat(e," --\x3e ").concat(i,"ing : ").concat(i))}))}));let s=[...r];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}static get(t){let r;return"string"==typeof t?(r=e.instances.get(t),r||e.instances.set(t,r=new e(t,void 0,Object.create(e.prototype)))):(r=e.instances2.get(t),r||e.instances2.set(t,r=new e(t.constructor.name,void 0,Object.create(e.prototype)))),r}static getState(t){var r;return null===(r=e.get(t))||void 0===r?void 0:r.state}updateDevTools(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};mH(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){fH.call(this,e)}};_H.STATECHANGED="stateChanged",_H.UPDATEAFSM="updateAFSM",_H.INIT="[*]",_H.ON="on",_H.OFF="off",_H.instances=new Map,_H.instances2=new WeakMap;var gH=class extends _H{constructor(){super(...arguments),nH(this,"decoder"),nH(this,"config")}initialize(){return ow(this,null,(function*(){this.decoder=new VideoDecoder({output:e=>{this.emit("videoFrame",e)},error:e=>{this.close(),this.emit("error",e)}})}))}configure(e){this.config=e,this.decoder.configure(iH(rH({},e),{codec:this.getCodec(e)}))}getCodec(e){switch(e.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return e.codec}}decode(e){"configured"===this.decoder.state&&this.decoder.decode(new EncodedVideoChunk(e))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){"closed"!==this.decoder.state&&this.decoder.close()}};function EH(){var e;self.onmessage=t=>{if("init"===t.data.type){let{canvas:r,wasmScript:i,wasmBinary:o}=t.data,n=null==r?void 0:r.getContext("2d"),a=0,s=0,c={wasmBinary:o,postRun:()=>{e=new c.VideoDecoder({videoInfo(e,t){a=e,s=t,console.log("video info",e,t)},yuvData(e,t){let i=a*s,o=i>>2,l=c.HEAPU32[e>>2],d=c.HEAPU32[1+(e>>2)],u=c.HEAPU32[2+(e>>2)],h=c.HEAPU8.subarray(l,l+i),p=c.HEAPU8.subarray(d,d+o),m=c.HEAPU8.subarray(u,u+o),f=new Uint8Array(i+o+o);f.set(h),f.set(p,i),f.set(m,i+o);let _=new VideoFrame(f,{codedWidth:a,codedHeight:s,format:"I420",timestamp:t});r?(null==n||n.drawImage(_,0,0,r.width,r.height),null==n||n.commit()):self.postMessage({type:"yuvData",videoFrame:_},[_])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+i)()(c)}else if("decode"===t.data.type){let{packet:r}=t.data;null==e||e.decode(r.data,"key"==r.type,r.timestamp)}else if("setCodec"===t.data.type){let{codec:r,format:i,description:o}=t.data;null==e||e.setCodec(r,i,null!=o?o:"")}}}oH([pH([_H.INIT,"closed"],"initialized")],gH.prototype,"initialize",1),oH([pH("initialized","configured",{sync:!0})],gH.prototype,"configure",1),oH([function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return(e,r,i)=>{let o=i.value,n=r;i.value=function(){if(!t.includes(this.state.toString()))throw new uH(this.state,"".concat(this.name," ").concat(n," failed: current state ").concat(this.state," not in ").concat(t));for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];return o.apply(this,r)}}}("configured")],gH.prototype,"decode",1),oH([pH([],_H.INIT,{sync:!0})],gH.prototype,"reset",1),oH([pH([],"closed",{ignoreError:!0,sync:!0})],gH.prototype,"close",1);var vH=class extends _H{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.createModule=e,this.wasmBinary=t,this.workerMode=r,this.canvas=i,this.yuvMode=o,nH(this,"worker"),nH(this,"decoder"),nH(this,"config"),nH(this,"module",{}),nH(this,"width",0),nH(this,"height",0)}initialize(e){return ow(this,null,(function*(){var t;if(this.workerMode){let e=new RegExp("\\{(.+)\\}","s").exec(EH.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"text/javascript"})));let r=null==(t=this.canvas)?void 0:t.transferControlToOffscreen(),i=yield this.wasmBinary;return console.warn("worker mode",i),this.worker.postMessage({type:"init",canvas:r,wasmScript:this.createModule.toString(),wasmBinary:i},r?[r,i]:[i]),new Promise((e=>{this.worker.onmessage=t=>{if("ready"===t.data.type)delete this.wasmBinary,e(),console.warn("worker mode initialize success");else if("yuvData"===t.data.type){let{videoFrame:e}=t.data;this.emit("videoFrame",e)}}}))}let r=this.module;return this.wasmBinary&&(r.wasmBinary=yield this.wasmBinary),r.print=e=>console.log(e),r.printErr=e=>console.log("[JS] ERROR: ".concat(e)),r.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise((t=>{r.postRun=e=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),t()},e&&Object.assign(r,e),this.createModule(r)}))}))}configure(e){var t,r,i;this.config=e;let o=this.config.codec.startsWith("avc")?"avc":"hevc",n=this.config.description?"avc"==o?"avcc":"hvcc":"annexb";null==(r=this.decoder)||r.setCodec(o,n,null!=(t=this.config.description)?t:""),null==(i=this.worker)||i.postMessage({type:"setCodec",codec:o,format:n,description:this.config.description})}decode(e){var t,r;null==(t=this.decoder)||t.decode(e.data,"key"==e.type,e.timestamp),"configured"===this.state&&(null==(r=this.worker)||r.postMessage({type:"decode",packet:e}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(e,t){this.width=e,this.height=t;let r={width:e,height:t};this.emit("videoCodecInfo",r)}yuvData(e,t){if(!this.module)return;let r=this.width*this.height,i=r>>2,o=this.module.HEAPU32[e>>2],n=this.module.HEAPU32[1+(e>>2)],a=this.module.HEAPU32[2+(e>>2)],s=this.module.HEAPU8.subarray(o,o+r),c=this.module.HEAPU8.subarray(n,n+i),l=this.module.HEAPU8.subarray(a,a+i);if(this.yuvMode)return void this.emit("videoFrame",{y:s,u:c,v:l,timestamp:t});let d=new Uint8Array(r+i+i);d.set(s),d.set(c,r),d.set(l,r+i),this.emit("videoFrame",new VideoFrame(d,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(e){let t={errMsg:e};this.emit("error",t)}};oH([pH([_H.INIT,"closed"],"initialized")],vH.prototype,"initialize",1),oH([pH("initialized","configured",{sync:!0})],vH.prototype,"configure",1),oH([pH([],_H.INIT,{sync:!0})],vH.prototype,"reset",1),oH([pH([],"closed",{sync:!0})],vH.prototype,"close",1);var yH,TH=(yH="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,r,i=e;i.ready=new Promise(((e,i)=>{t=e,r=i}));var o,n,a,s=Object.assign({},i),c="./this.program",l="object"==typeof window,d="function"==typeof importScripts,u=("object"==typeof process&&"object"==typeof process.versions&&process.versions.node,"");(l||d)&&(d?u=self.location.href:"undefined"!=typeof document&&document.currentScript&&(u=document.currentScript.src),yH&&(u=yH),u=0!==u.indexOf("blob:")?u.substr(0,u.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},d&&(a=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),n=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var h,p,m=i.print||console.log.bind(console),f=i.printErr||console.error.bind(console);Object.assign(i,s),s=null,i.arguments&&i.arguments,i.thisProgram&&(c=i.thisProgram),i.quit&&i.quit,i.wasmBinary&&(h=i.wasmBinary),i.noExitRuntime,"object"!=typeof WebAssembly&&U("no native wasm support detected");var _,g,E,v,y,T,I,A,S,R,b,w,C,D=!1,N=[],k=[],O=[],M=0,L=null;function P(e){M++,i.monitorRunDependencies&&i.monitorRunDependencies(M)}function x(e){if(M--,i.monitorRunDependencies&&i.monitorRunDependencies(M),0==M&&L){var t=L;L=null,t()}}function U(e){i.onAbort&&i.onAbort(e),f(e="Aborted("+e+")"),D=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw r(t),t}function V(e){return e.startsWith("data:application/octet-stream;base64,")}function F(e){if(e==R&&h)return new Uint8Array(h);if(a)return a(e);throw"both async and sync fetching of the wasm failed"}function B(e,t,r){return(i=e,h||!l&&!d||"function"!=typeof fetch?Promise.resolve().then((()=>F(i))):fetch(i,{credentials:"same-origin"}).then((e=>{if(!e.ok)throw"failed to load wasm binary file at '"+i+"'";return e.arrayBuffer()})).catch((()=>F(i)))).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(r,(e=>{f("failed to asynchronously prepare wasm: "+e),U(e)}));var i}V(R="videodec.wasm")||(b=R,R=i.locateFile?i.locateFile(b,u):u+b);var H=e=>{for(;e.length>0;)e.shift()(i)};function W(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){T[this.ptr+4>>2]=e},this.get_type=function(){return T[this.ptr+4>>2]},this.set_destructor=function(e){T[this.ptr+8>>2]=e},this.get_destructor=function(){return T[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,_[this.ptr+12|0]=e},this.get_caught=function(){return 0!=_[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,_[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=_[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){T[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return T[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Rt(this.get_type()))return T[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var j={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var o=e[i];"."===o?e.splice(i,1):".."===o?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=j.isAbs(e),r="/"===e.substr(-1);return(e=j.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=j.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=j.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return j.normalize(e.join("/"))},join2:(e,t)=>j.normalize(e+"/"+t)},G=e=>(G=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);U("initRandomDevice")})())(e),z={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:ie.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=j.isAbs(i)}return(t?"/":"")+(e=j.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=z.resolve(e).substr(1),t=z.resolve(t).substr(1);for(var i=r(e.split("/")),o=r(t.split("/")),n=Math.min(i.length,o.length),a=n,s=0;s<n;s++)if(i[s]!==o[s]){a=s;break}var c=[];for(s=a;s<i.length;s++)c.push("..");return(c=c.concat(o.slice(a))).join("/")}},K="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,q=(e,t,r)=>{for(var i=t+r,o=t;e[o]&&!(o>=i);)++o;if(o-t>16&&e.buffer&&K)return K.decode(e.subarray(t,o));for(var n="";t<o;){var a=e[t++];if(128&a){var s=63&e[t++];if(192!=(224&a)){var c=63&e[t++];if((a=224==(240&a)?(15&a)<<12|s<<6|c:(7&a)<<18|s<<12|c<<6|63&e[t++])<65536)n+=String.fromCharCode(a);else{var l=a-65536;n+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else n+=String.fromCharCode((31&a)<<6|s)}else n+=String.fromCharCode(a)}return n},Y=[],J=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i<=127?t++:i<=2047?t+=2:i>=55296&&i<=57343?(t+=4,++r):t+=3}return t},X=(e,t,r,i)=>{if(!(i>0))return 0;for(var o=r,n=r+i-1,a=0;a<e.length;++a){var s=e.charCodeAt(a);if(s>=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(r>=n)break;t[r++]=s}else if(s<=2047){if(r+1>=n)break;t[r++]=192|s>>6,t[r++]=128|63&s}else if(s<=65535){if(r+2>=n)break;t[r++]=224|s>>12,t[r++]=128|s>>6&63,t[r++]=128|63&s}else{if(r+3>=n)break;t[r++]=240|s>>18,t[r++]=128|s>>12&63,t[r++]=128|s>>6&63,t[r++]=128|63&s}}return t[r]=0,r-o};function $(e,t,r){var i=r>0?r:J(e)+1,o=new Array(i),n=X(e,o,0,o.length);return t&&(o.length=n),o}var Q={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){Q.ttys[e]={input:[],output:[],ops:t},ie.registerDevice(e,Q.stream_ops)},stream_ops:{open:function(e){var t=Q.ttys[e.node.rdev];if(!t)throw new ie.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,r,i,o){if(!e.tty||!e.tty.ops.get_char)throw new ie.ErrnoError(60);for(var n=0,a=0;a<i;a++){var s;try{s=e.tty.ops.get_char(e.tty)}catch(c){throw new ie.ErrnoError(29)}if(void 0===s&&0===n)throw new ie.ErrnoError(6);if(null==s)break;n++,t[r+a]=s}return n&&(e.node.timestamp=Date.now()),n},write:function(e,t,r,i,o){if(!e.tty||!e.tty.ops.put_char)throw new ie.ErrnoError(60);try{for(var n=0;n<i;n++)e.tty.ops.put_char(e.tty,t[r+n])}catch(a){throw new ie.ErrnoError(29)}return i&&(e.node.timestamp=Date.now()),n}},default_tty_ops:{get_char:function(e){return(()=>{if(!Y.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;Y=$(e,!0)}return Y.shift()})()},put_char:function(e,t){null===t||10===t?(m(q(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(m(q(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,r){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(f(q(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(f(q(e.output,0)),e.output=[])}}},Z=e=>{U()},ee={ops_table:null,mount:e=>ee.createNode(null,"/",16895,0),createNode(e,t,r,i){if(ie.isBlkdev(r)||ie.isFIFO(r))throw new ie.ErrnoError(63);ee.ops_table||(ee.ops_table={dir:{node:{getattr:ee.node_ops.getattr,setattr:ee.node_ops.setattr,lookup:ee.node_ops.lookup,mknod:ee.node_ops.mknod,rename:ee.node_ops.rename,unlink:ee.node_ops.unlink,rmdir:ee.node_ops.rmdir,readdir:ee.node_ops.readdir,symlink:ee.node_ops.symlink},stream:{llseek:ee.stream_ops.llseek}},file:{node:{getattr:ee.node_ops.getattr,setattr:ee.node_ops.setattr},stream:{llseek:ee.stream_ops.llseek,read:ee.stream_ops.read,write:ee.stream_ops.write,allocate:ee.stream_ops.allocate,mmap:ee.stream_ops.mmap,msync:ee.stream_ops.msync}},link:{node:{getattr:ee.node_ops.getattr,setattr:ee.node_ops.setattr,readlink:ee.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ee.node_ops.getattr,setattr:ee.node_ops.setattr},stream:ie.chrdev_stream_ops}});var o=ie.createNode(e,t,r,i);return ie.isDir(o.mode)?(o.node_ops=ee.ops_table.dir.node,o.stream_ops=ee.ops_table.dir.stream,o.contents={}):ie.isFile(o.mode)?(o.node_ops=ee.ops_table.file.node,o.stream_ops=ee.ops_table.file.stream,o.usedBytes=0,o.contents=null):ie.isLink(o.mode)?(o.node_ops=ee.ops_table.link.node,o.stream_ops=ee.ops_table.link.stream):ie.isChrdev(o.mode)&&(o.node_ops=ee.ops_table.chrdev.node,o.stream_ops=ee.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=ie.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,ie.isDir(e.mode)?t.size=4096:ie.isFile(e.mode)?t.size=e.usedBytes:ie.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&ee.resizeFileStorage(e,t.size)},lookup(e,t){throw ie.genericErrors[44]},mknod:(e,t,r,i)=>ee.createNode(e,t,r,i),rename(e,t,r){if(ie.isDir(e.mode)){var i;try{i=ie.lookupNode(t,r)}catch(n){}if(i)for(var o in i.contents)throw new ie.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=ie.lookupNode(e,t);for(var i in r.contents)throw new ie.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var i=ee.createNode(e,t,41471,0);return i.link=r,i},readlink(e){if(!ie.isLink(e.mode))throw new ie.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,i,o){var n=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,i);if(a>8&&n.subarray)t.set(n.subarray(o,o+a),r);else for(var s=0;s<a;s++)t[r+s]=n[o+s];return a},write(e,t,r,i,o,n){if(!i)return 0;var a=e.node;if(a.timestamp=Date.now(),t.subarray&&(!a.contents||a.contents.subarray)){if(n)return a.contents=t.subarray(r,r+i),a.usedBytes=i,i;if(0===a.usedBytes&&0===o)return a.contents=t.slice(r,r+i),a.usedBytes=i,i;if(o+i<=a.usedBytes)return a.contents.set(t.subarray(r,r+i),o),i}if(ee.expandFileStorage(a,o+i),a.contents.subarray&&t.subarray)a.contents.set(t.subarray(r,r+i),o);else for(var s=0;s<i;s++)a.contents[o+s]=t[r+s];return a.usedBytes=Math.max(a.usedBytes,o+i),i},llseek(e,t,r){var i=t;if(1===r?i+=e.position:2===r&&ie.isFile(e.node.mode)&&(i+=e.node.usedBytes),i<0)throw new ie.ErrnoError(28);return i},allocate(e,t,r){ee.expandFileStorage(e.node,t+r),e.node.usedBytes=Math.max(e.node.usedBytes,t+r)},mmap(e,t,r,i,o){if(!ie.isFile(e.node.mode))throw new ie.ErrnoError(43);var n,a,s=e.node.contents;if(2&o||s.buffer!==_.buffer){if((r>0||r+t<s.length)&&(s=s.subarray?s.subarray(r,r+t):Array.prototype.slice.call(s,r,r+t)),a=!0,!(n=Z()))throw new ie.ErrnoError(48);_.set(s,n)}else a=!1,n=s.byteOffset;return{ptr:n,allocated:a}},msync:(e,t,r,i,o)=>(ee.stream_ops.write(e,t,0,i,r,!1),0)}},te=i.preloadPlugins||[];function re(e,t){var r=0;return e&&(r|=365),t&&(r|=146),r}var ie={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(e=z.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new ie.ErrnoError(32);for(var r=e.split("/").filter((e=>!!e)),i=ie.root,o="/",n=0;n<r.length;n++){var a=n===r.length-1;if(a&&t.parent)break;if(i=ie.lookupNode(i,r[n]),o=j.join2(o,r[n]),ie.isMountpoint(i)&&(!a||a&&t.follow_mount)&&(i=i.mounted.root),!a||t.follow)for(var s=0;ie.isLink(i.mode);){var c=ie.readlink(o);if(o=z.resolve(j.dirname(o),c),i=ie.lookupPath(o,{recurse_count:t.recurse_count+1}).node,s++>40)throw new ie.ErrnoError(32)}}return{path:o,node:i}},getPath:e=>{for(var t;;){if(ie.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?"".concat(r,"/").concat(t):r+t:r}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i)|0;return(e+r>>>0)%ie.nameTable.length},hashAddNode:e=>{var t=ie.hashName(e.parent.id,e.name);e.name_next=ie.nameTable[t],ie.nameTable[t]=e},hashRemoveNode:e=>{var t=ie.hashName(e.parent.id,e.name);if(ie.nameTable[t]===e)ie.nameTable[t]=e.name_next;else for(var r=ie.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=ie.mayLookup(e);if(r)throw new ie.ErrnoError(r,e);for(var i=ie.hashName(e.id,t),o=ie.nameTable[i];o;o=o.name_next){var n=o.name;if(o.parent.id===e.id&&n===t)return o}return ie.lookup(e,t)},createNode:(e,t,r,i)=>{var o=new ie.FSNode(e,t,r,i);return ie.hashAddNode(o),o},destroyNode:e=>{ie.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>ie.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>ie.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return ie.lookupNode(e,t),20}catch(r){}return ie.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=ie.lookupNode(e,t)}catch(n){return n.errno}var o=ie.nodePermissions(e,"wx");if(o)return o;if(r){if(!ie.isDir(i.mode))return 54;if(ie.isRoot(i)||ie.getPath(i)===ie.cwd())return 10}else if(ie.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?ie.isLink(e.mode)?32:ie.isDir(e.mode)&&("r"!==ie.flagsToPermissionString(t)||512&t)?31:ie.nodePermissions(e,ie.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=ie.MAX_OPEN_FDS;e++)if(!ie.streams[e])return e;throw new ie.ErrnoError(33)},getStreamChecked:e=>{var t=ie.getStream(e);if(!t)throw new ie.ErrnoError(8);return t},getStream:e=>ie.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ie.FSStream||(ie.FSStream=function(){this.shared={}},ie.FSStream.prototype={},Object.defineProperties(ie.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new ie.FSStream,e),-1==t&&(t=ie.nextfd()),e.fd=t,ie.streams[t]=e,e},closeStream:e=>{ie.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=ie.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new ie.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{ie.devices[e]={stream_ops:t}},getDevice:e=>ie.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),ie.syncFSRequests++,ie.syncFSRequests>1&&f("warning: ".concat(ie.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var r=ie.getMounts(ie.root.mount),i=0;function o(e){return ie.syncFSRequests--,t(e)}function n(e){if(e)return n.errored?void 0:(n.errored=!0,o(e));++i>=r.length&&o(null)}r.forEach((t=>{if(!t.type.syncfs)return n(null);t.type.syncfs(t,e,n)}))},mount:(e,t,r)=>{var i,o="/"===r,n=!r;if(o&&ie.root)throw new ie.ErrnoError(10);if(!o&&!n){var a=ie.lookupPath(r,{follow_mount:!1});if(r=a.path,i=a.node,ie.isMountpoint(i))throw new ie.ErrnoError(10);if(!ie.isDir(i.mode))throw new ie.ErrnoError(54)}var s={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(s);return c.mount=s,s.root=c,o?ie.root=c:i&&(i.mounted=s,i.mount&&i.mount.mounts.push(s)),c},unmount:e=>{var t=ie.lookupPath(e,{follow_mount:!1});if(!ie.isMountpoint(t.node))throw new ie.ErrnoError(28);var r=t.node,i=r.mounted,o=ie.getMounts(i);Object.keys(ie.nameTable).forEach((e=>{for(var t=ie.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&ie.destroyNode(t),t=r}})),r.mounted=null;var n=r.mount.mounts.indexOf(i);r.mount.mounts.splice(n,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=ie.lookupPath(e,{parent:!0}).node,o=j.basename(e);if(!o||"."===o||".."===o)throw new ie.ErrnoError(28);var n=ie.mayCreate(i,o);if(n)throw new ie.ErrnoError(n);if(!i.node_ops.mknod)throw new ie.ErrnoError(63);return i.node_ops.mknod(i,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,ie.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,ie.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",o=0;o<r.length;++o)if(r[o]){i+="/"+r[o];try{ie.mkdir(i,t)}catch(n){if(20!=n.errno)throw n}}},mkdev:(e,t,r)=>(void 0===r&&(r=t,t=438),t|=8192,ie.mknod(e,t,r)),symlink:(e,t)=>{if(!z.resolve(e))throw new ie.ErrnoError(44);var r=ie.lookupPath(t,{parent:!0}).node;if(!r)throw new ie.ErrnoError(44);var i=j.basename(t),o=ie.mayCreate(r,i);if(o)throw new ie.ErrnoError(o);if(!r.node_ops.symlink)throw new ie.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,o=j.dirname(e),n=j.dirname(t),a=j.basename(e),s=j.basename(t);if(r=ie.lookupPath(e,{parent:!0}).node,i=ie.lookupPath(t,{parent:!0}).node,!r||!i)throw new ie.ErrnoError(44);if(r.mount!==i.mount)throw new ie.ErrnoError(75);var c,l=ie.lookupNode(r,a),d=z.relative(e,n);if("."!==d.charAt(0))throw new ie.ErrnoError(28);if("."!==(d=z.relative(t,o)).charAt(0))throw new ie.ErrnoError(55);try{c=ie.lookupNode(i,s)}catch(p){}if(l!==c){var u=ie.isDir(l.mode),h=ie.mayDelete(r,a,u);if(h)throw new ie.ErrnoError(h);if(h=c?ie.mayDelete(i,s,u):ie.mayCreate(i,s))throw new ie.ErrnoError(h);if(!r.node_ops.rename)throw new ie.ErrnoError(63);if(ie.isMountpoint(l)||c&&ie.isMountpoint(c))throw new ie.ErrnoError(10);if(i!==r&&(h=ie.nodePermissions(r,"w")))throw new ie.ErrnoError(h);ie.hashRemoveNode(l);try{r.node_ops.rename(l,i,s)}catch(p){throw p}finally{ie.hashAddNode(l)}}},rmdir:e=>{var t=ie.lookupPath(e,{parent:!0}).node,r=j.basename(e),i=ie.lookupNode(t,r),o=ie.mayDelete(t,r,!0);if(o)throw new ie.ErrnoError(o);if(!t.node_ops.rmdir)throw new ie.ErrnoError(63);if(ie.isMountpoint(i))throw new ie.ErrnoError(10);t.node_ops.rmdir(t,r),ie.destroyNode(i)},readdir:e=>{var t=ie.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new ie.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=ie.lookupPath(e,{parent:!0}).node;if(!t)throw new ie.ErrnoError(44);var r=j.basename(e),i=ie.lookupNode(t,r),o=ie.mayDelete(t,r,!1);if(o)throw new ie.ErrnoError(o);if(!t.node_ops.unlink)throw new ie.ErrnoError(63);if(ie.isMountpoint(i))throw new ie.ErrnoError(10);t.node_ops.unlink(t,r),ie.destroyNode(i)},readlink:e=>{var t=ie.lookupPath(e).node;if(!t)throw new ie.ErrnoError(44);if(!t.node_ops.readlink)throw new ie.ErrnoError(28);return z.resolve(ie.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=ie.lookupPath(e,{follow:!t}).node;if(!r)throw new ie.ErrnoError(44);if(!r.node_ops.getattr)throw new ie.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>ie.stat(e,!0),chmod:(e,t,r)=>{var i;if(!(i="string"==typeof e?ie.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new ie.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{ie.chmod(e,t,!0)},fchmod:(e,t)=>{var r=ie.getStreamChecked(e);ie.chmod(r.node,t)},chown:(e,t,r,i)=>{var o;if(!(o="string"==typeof e?ie.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new ie.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,t,r)=>{ie.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=ie.getStreamChecked(e);ie.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new ie.ErrnoError(28);var r;if(!(r="string"==typeof e?ie.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new ie.ErrnoError(63);if(ie.isDir(r.mode))throw new ie.ErrnoError(31);if(!ie.isFile(r.mode))throw new ie.ErrnoError(28);var i=ie.nodePermissions(r,"w");if(i)throw new ie.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=ie.getStreamChecked(e);if(!(2097155&r.flags))throw new ie.ErrnoError(28);ie.truncate(r.node,t)},utime:(e,t,r)=>{var i=ie.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(e,t,r)=>{if(""===e)throw new ie.ErrnoError(44);var o;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?function(e){var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error("Unknown file open mode: ".concat(e));return t}(t):t)?4095&r|32768:0,"object"==typeof e)o=e;else{e=j.normalize(e);try{o=ie.lookupPath(e,{follow:!(131072&t)}).node}catch(c){}}var n=!1;if(64&t)if(o){if(128&t)throw new ie.ErrnoError(20)}else o=ie.mknod(e,r,0),n=!0;if(!o)throw new ie.ErrnoError(44);if(ie.isChrdev(o.mode)&&(t&=-513),65536&t&&!ie.isDir(o.mode))throw new ie.ErrnoError(54);if(!n){var a=ie.mayOpen(o,t);if(a)throw new ie.ErrnoError(a)}512&t&&!n&&ie.truncate(o,0),t&=-131713;var s=ie.createStream({node:o,path:ie.getPath(o),flags:t,seekable:!0,position:0,stream_ops:o.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!i.logReadFiles||1&t||(ie.readFiles||(ie.readFiles={}),e in ie.readFiles||(ie.readFiles[e]=1)),s},close:e=>{if(ie.isClosed(e))throw new ie.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{ie.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(ie.isClosed(e))throw new ie.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new ie.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new ie.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,o)=>{if(i<0||o<0)throw new ie.ErrnoError(28);if(ie.isClosed(e))throw new ie.ErrnoError(8);if(1==(2097155&e.flags))throw new ie.ErrnoError(8);if(ie.isDir(e.node.mode))throw new ie.ErrnoError(31);if(!e.stream_ops.read)throw new ie.ErrnoError(28);var n=void 0!==o;if(n){if(!e.seekable)throw new ie.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,t,r,i,o);return n||(e.position+=a),a},write:(e,t,r,i,o,n)=>{if(i<0||o<0)throw new ie.ErrnoError(28);if(ie.isClosed(e))throw new ie.ErrnoError(8);if(!(2097155&e.flags))throw new ie.ErrnoError(8);if(ie.isDir(e.node.mode))throw new ie.ErrnoError(31);if(!e.stream_ops.write)throw new ie.ErrnoError(28);e.seekable&&1024&e.flags&&ie.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new ie.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,r,i,o,n);return a||(e.position+=s),s},allocate:(e,t,r)=>{if(ie.isClosed(e))throw new ie.ErrnoError(8);if(t<0||r<=0)throw new ie.ErrnoError(28);if(!(2097155&e.flags))throw new ie.ErrnoError(8);if(!ie.isFile(e.node.mode)&&!ie.isDir(e.node.mode))throw new ie.ErrnoError(43);if(!e.stream_ops.allocate)throw new ie.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,o)=>{if(2&i&&!(2&o)&&2!=(2097155&e.flags))throw new ie.ErrnoError(2);if(1==(2097155&e.flags))throw new ie.ErrnoError(2);if(!e.stream_ops.mmap)throw new ie.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,o)},msync:(e,t,r,i,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,o):0,munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new ie.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'.concat(t.encoding,'"'));var r,i=ie.open(e,t.flags),o=ie.stat(e).size,n=new Uint8Array(o);return ie.read(i,n,0,o,0),"utf8"===t.encoding?r=q(n,0):"binary"===t.encoding&&(r=n),ie.close(i),r},writeFile:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.flags=r.flags||577;var i=ie.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(J(t)+1),n=X(t,o,0,o.length);ie.write(i,o,0,n,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ie.write(i,t,0,t.byteLength,void 0,r.canOwn)}ie.close(i)},cwd:()=>ie.currentPath,chdir:e=>{var t=ie.lookupPath(e,{follow:!0});if(null===t.node)throw new ie.ErrnoError(44);if(!ie.isDir(t.node.mode))throw new ie.ErrnoError(54);var r=ie.nodePermissions(t.node,"x");if(r)throw new ie.ErrnoError(r);ie.currentPath=t.path},createDefaultDirectories:()=>{ie.mkdir("/tmp"),ie.mkdir("/home"),ie.mkdir("/home/web_user")},createDefaultDevices:()=>{ie.mkdir("/dev"),ie.registerDevice(ie.makedev(1,3),{read:()=>0,write:(e,t,r,i,o)=>i}),ie.mkdev("/dev/null",ie.makedev(1,3)),Q.register(ie.makedev(5,0),Q.default_tty_ops),Q.register(ie.makedev(6,0),Q.default_tty1_ops),ie.mkdev("/dev/tty",ie.makedev(5,0)),ie.mkdev("/dev/tty1",ie.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=G(e).byteLength),e[--t]);ie.createDevice("/dev","random",r),ie.createDevice("/dev","urandom",r),ie.mkdir("/dev/shm"),ie.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{ie.mkdir("/proc");var e=ie.mkdir("/proc/self");ie.mkdir("/proc/self/fd"),ie.mount({mount:()=>{var t=ie.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=ie.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{i.stdin?ie.createDevice("/dev","stdin",i.stdin):ie.symlink("/dev/tty","/dev/stdin"),i.stdout?ie.createDevice("/dev","stdout",null,i.stdout):ie.symlink("/dev/tty","/dev/stdout"),i.stderr?ie.createDevice("/dev","stderr",null,i.stderr):ie.symlink("/dev/tty1","/dev/stderr"),ie.open("/dev/stdin",0),ie.open("/dev/stdout",1),ie.open("/dev/stderr",1)},ensureErrnoError:()=>{ie.ErrnoError||(ie.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ie.ErrnoError.prototype=new Error,ie.ErrnoError.prototype.constructor=ie.ErrnoError,[44].forEach((e=>{ie.genericErrors[e]=new ie.ErrnoError(e),ie.genericErrors[e].stack="<generic error, no stack>"})))},staticInit:()=>{ie.ensureErrnoError(),ie.nameTable=new Array(4096),ie.mount(ee,{},"/"),ie.createDefaultDirectories(),ie.createDefaultDevices(),ie.createSpecialDirectories(),ie.filesystems={MEMFS:ee}},init:(e,t,r)=>{ie.init.initialized=!0,ie.ensureErrnoError(),i.stdin=e||i.stdin,i.stdout=t||i.stdout,i.stderr=r||i.stderr,ie.createStandardStreams()},quit:()=>{ie.init.initialized=!1;for(var e=0;e<ie.streams.length;e++){var t=ie.streams[e];t&&ie.close(t)}},findObject:(e,t)=>{var r=ie.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=ie.lookupPath(e,{follow:!t})).path}catch(o){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=ie.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=j.basename(e),i=ie.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(o){r.error=o.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:ie.getPath(e);for(var o=t.split("/").reverse();o.length;){var n=o.pop();if(n){var a=j.join2(e,n);try{ie.mkdir(a)}catch(s){}e=a}}return a},createFile:(e,t,r,i,o)=>{var n=j.join2("string"==typeof e?e:ie.getPath(e),t),a=re(i,o);return ie.create(n,a)},createDataFile:(e,t,r,i,o,n)=>{var a=t;e&&(e="string"==typeof e?e:ie.getPath(e),a=t?j.join2(e,t):e);var s=re(i,o),c=ie.create(a,s);if(r){if("string"==typeof r){for(var l=new Array(r.length),d=0,u=r.length;d<u;++d)l[d]=r.charCodeAt(d);r=l}ie.chmod(c,146|s);var h=ie.open(c,577);ie.write(h,r,0,r.length,0,n),ie.close(h),ie.chmod(c,s)}return c},createDevice:(e,t,r,i)=>{var o=j.join2("string"==typeof e?e:ie.getPath(e),t),n=re(!!r,!!i);ie.createDevice.major||(ie.createDevice.major=64);var a=ie.makedev(ie.createDevice.major++,0);return ie.registerDevice(a,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,o,n)=>{for(var a=0,s=0;s<o;s++){var c;try{c=r()}catch(l){throw new ie.ErrnoError(29)}if(void 0===c&&0===a)throw new ie.ErrnoError(6);if(null==c)break;a++,t[i+s]=c}return a&&(e.node.timestamp=Date.now()),a},write:(e,t,r,o,n)=>{for(var a=0;a<o;a++)try{i(t[r+a])}catch(s){throw new ie.ErrnoError(29)}return o&&(e.node.timestamp=Date.now()),a}}),ie.mkdev(o,n,a)},forceLoadFile:e=>{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!o)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=$(o(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new ie.ErrnoError(29)}},createLazyFile:(e,t,r,i,o)=>{function n(){this.lengthKnown=!1,this.chunks=[]}if(n.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},n.prototype.setDataGetter=function(e){this.getter=e},n.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,n=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,a=1048576;o||(a=i);var s=this;s.setDataGetter((e=>{var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,i-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),i!==a&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):$(o.responseText||"",!0)})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!n&&i||(a=i=1,i=this.getter(0).length,a=i,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=a,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!d)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var a=new n;Object.defineProperties(a,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:a}}else s={isDevice:!1,url:r};var c=ie.createFile(e,t,s,i,o);s.contents?c.contents=s.contents:s.url&&(c.contents=null,c.url=s.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var l={};function u(e,t,r,i,o){var n=e.node.contents;if(o>=n.length)return 0;var a=Math.min(n.length-o,i);if(n.slice)for(var s=0;s<a;s++)t[r+s]=n[o+s];else for(s=0;s<a;s++)t[r+s]=n.get(o+s);return a}return Object.keys(c.stream_ops).forEach((e=>{var t=c.stream_ops[e];l[e]=function(){return ie.forceLoadFile(c),t.apply(null,arguments)}})),l.read=(e,t,r,i,o)=>(ie.forceLoadFile(c),u(e,t,r,i,o)),l.mmap=(e,t,r,i,o)=>{ie.forceLoadFile(c);var n=Z();if(!n)throw new ie.ErrnoError(48);return u(e,_,n,t,r),{ptr:n,allocated:!0}},c.stream_ops=l,c}},oe=(e,t)=>e?q(g,e,t):"",ne={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if(j.isAbs(t))return t;var i;if(i=-100===e?ie.cwd():ne.getStreamFromFD(e).path,0==t.length){if(!r)throw new ie.ErrnoError(44);return i}return j.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(s){if(s&&s.node&&j.normalize(t)!==j.normalize(ie.getPath(s.node)))return-54;throw s}y[r>>2]=i.dev,y[r+4>>2]=i.mode,T[r+8>>2]=i.nlink,y[r+12>>2]=i.uid,y[r+16>>2]=i.gid,y[r+20>>2]=i.rdev,C=[i.size>>>0,(w=i.size,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[r+24>>2]=C[0],y[r+28>>2]=C[1],y[r+32>>2]=4096,y[r+36>>2]=i.blocks;var o=i.atime.getTime(),n=i.mtime.getTime(),a=i.ctime.getTime();return C=[Math.floor(o/1e3)>>>0,(w=Math.floor(o/1e3),+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[r+40>>2]=C[0],y[r+44>>2]=C[1],T[r+48>>2]=o%1e3*1e3,C=[Math.floor(n/1e3)>>>0,(w=Math.floor(n/1e3),+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[r+56>>2]=C[0],y[r+60>>2]=C[1],T[r+64>>2]=n%1e3*1e3,C=[Math.floor(a/1e3)>>>0,(w=Math.floor(a/1e3),+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[r+72>>2]=C[0],y[r+76>>2]=C[1],T[r+80>>2]=a%1e3*1e3,C=[i.ino>>>0,(w=i.ino,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[r+88>>2]=C[0],y[r+92>>2]=C[1],0},doMsync:function(e,t,r,i,o){if(!ie.isFile(t.node.mode))throw new ie.ErrnoError(43);if(2&i)return 0;var n=g.slice(e,e+r);ie.msync(t,n,o,r,i)},varargs:void 0,get:()=>(ne.varargs+=4,y[ne.varargs-4>>2]),getStr:e=>oe(e),getStreamFromFD:function(e){return ie.getStreamChecked(e)}};function ae(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: ".concat(e))}}var se=void 0;function ce(e){for(var t="",r=e;g[r];)t+=se[g[r++]];return t}var le={},de={},ue={},he=void 0;function pe(e){throw new he(e)}var me=void 0;function fe(e){throw new me(e)}function _e(e,t,r){function i(t){var i=r(t);i.length!==e.length&&fe("Mismatched type converter count");for(var o=0;o<e.length;++o)ge(e[o],i[o])}e.forEach((function(e){ue[e]=t}));var o=new Array(t.length),n=[],a=0;t.forEach(((e,t)=>{de.hasOwnProperty(e)?o[t]=de[e]:(n.push(e),le.hasOwnProperty(e)||(le[e]=[]),le[e].push((()=>{o[t]=de[e],++a===n.length&&i(o)})))})),0===n.length&&i(o)}function ge(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i=t.name;if(e||pe('type "'.concat(i,'" must have a positive integer typeid pointer')),de.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;pe("Cannot register type '".concat(i,"' twice"))}if(de[e]=t,delete ue[e],le.hasOwnProperty(e)){var o=le[e];delete le[e],o.forEach((e=>e()))}}(e,t,r)}function Ee(e){pe(e.$$.ptrType.registeredClass.name+" instance already deleted")}var ve=!1;function ye(e){}function Te(e){var t;e.count.value-=1,0===e.count.value&&((t=e).smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr))}function Ie(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=Ie(e,t,r.baseClass);return null===i?null:r.downcast(i)}var Ae={},Se=[];function Re(){for(;Se.length;){var e=Se.pop();e.$$.deleteScheduled=!1,e.delete()}}var be=void 0,we={};function Ce(e,t){return t.ptrType&&t.ptr||fe("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&fe("Both smartPtrType and smartPtr must be specified"),t.count={value:1},De(Object.create(e,{$$:{value:t}}))}var De=function(e){return"undefined"==typeof FinalizationRegistry?(De=e=>e,e):(ve=new FinalizationRegistry((e=>{Te(e.$$)})),ye=e=>ve.unregister(e),(De=e=>{var t=e.$$;if(t.smartPtr){var r={$$:t};ve.register(e,r,e)}return e})(e))};function Ne(){}function ke(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=48&&t<=57?"_".concat(e):e}function Oe(e,t){return e=ke(e),{[e]:function(){return t.apply(this,arguments)}}[e]}function Me(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||pe("Function '".concat(r,"' called with an invalid number of arguments (").concat(arguments.length,") - expects one of (").concat(e[t].overloadTable,")!")),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function Le(e,t,r,i,o,n,a,s){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=o,this.getActualType=n,this.upcast=a,this.downcast=s,this.pureVirtualFunctions=[]}function Pe(e,t,r){for(;t!==r;)t.upcast||pe("Expected null or instance of ".concat(r.name,", got an instance of ").concat(t.name)),e=t.upcast(e),t=t.baseClass;return e}function xe(e,t){if(null===t)return this.isReference&&pe("null is not a valid ".concat(this.name)),0;t.$$||pe('Cannot pass "'.concat(tt(t),'" as a ').concat(this.name)),t.$$.ptr||pe("Cannot pass deleted object as a pointer of type ".concat(this.name));var r=t.$$.ptrType.registeredClass;return Pe(t.$$.ptr,r,this.registeredClass)}function Ue(e,t){var r;if(null===t)return this.isReference&&pe("null is not a valid ".concat(this.name)),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||pe('Cannot pass "'.concat(tt(t),'" as a ').concat(this.name)),t.$$.ptr||pe("Cannot pass deleted object as a pointer of type ".concat(this.name)),!this.isConst&&t.$$.ptrType.isConst&&pe("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));var i=t.$$.ptrType.registeredClass;if(r=Pe(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&pe("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:pe("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var o=t.clone();r=this.rawShare(r,et.toHandle((function(){o.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:pe("Unsupporting sharing policy")}return r}function Ve(e,t){if(null===t)return this.isReference&&pe("null is not a valid ".concat(this.name)),0;t.$$||pe('Cannot pass "'.concat(tt(t),'" as a ').concat(this.name)),t.$$.ptr||pe("Cannot pass deleted object as a pointer of type ".concat(this.name)),t.$$.ptrType.isConst&&pe("Cannot convert argument of type ".concat(t.$$.ptrType.name," to parameter type ").concat(this.name));var r=t.$$.ptrType.registeredClass;return Pe(t.$$.ptr,r,this.registeredClass)}function Fe(e){return this.fromWireType(y[e>>2])}function Be(e,t,r,i,o,n,a,s,c,l,d){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=o,this.pointeeType=n,this.sharingPolicy=a,this.rawGetPointee=s,this.rawConstructor=c,this.rawShare=l,this.rawDestructor=d,o||void 0!==t.baseClass?this.toWireType=Ue:i?(this.toWireType=xe,this.destructorFunction=null):(this.toWireType=Ve,this.destructorFunction=null)}var He=[],We=e=>{var t=He[e];return t||(e>=He.length&&(He.length=e+1),He[e]=t=S.get(e)),t};function je(e,t){var r,o,n,a=(e=ce(e)).includes("j")?(r=e,o=t,n=[],function(){return n.length=0,Object.assign(n,arguments),((e,t,r)=>{return e.includes("j")?(o=t,n=r,a=i["dynCall_"+e],n&&n.length?a.apply(null,[o].concat(n)):a.call(null,o)):We(t).apply(null,r);var o,n,a})(r,o,n)}):We(t);return"function"!=typeof a&&pe("unknown function pointer with signature ".concat(e,": ").concat(t)),a}var Ge=void 0;function ze(e){var t=St(e),r=ce(t);return It(t),r}function Ke(e,t){var r=[],i={};throw t.forEach((function e(t){i[t]||de[t]||(ue[t]?ue[t].forEach(e):(r.push(t),i[t]=!0))})),new Ge("".concat(e,": ")+r.map(ze).join([", "]))}function qe(e,t){for(var r=[],i=0;i<e;i++)r.push(T[t+4*i>>2]);return r}function Ye(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function Je(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type ".concat(typeof e," which is not a function"));var r=Oe(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,o=e.apply(i,t);return o instanceof Object?o:i}function Xe(e,t,r,i,o,n){var a=t.length;a<2&&pe("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var s=null!==t[1]&&null!==r,c=!1,l=1;l<t.length;++l)if(null!==t[l]&&void 0===t[l].destructorFunction){c=!0;break}var d="void"!==t[0].name,u="",h="";for(l=0;l<a-2;++l)u+=(0!==l?", ":"")+"arg"+l,h+=(0!==l?", ":"")+"arg"+l+"Wired";var p="\n return function ".concat(ke(e),"(").concat(u,") {\n if (arguments.length !== ").concat(a-2,") {\n throwBindingError('function ").concat(e," called with ").concat(arguments.length," arguments, expected ").concat(a-2," args!');\n }");c&&(p+="var destructors = [];\n");var m=c?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[pe,i,o,Ye,t[0],t[1]];for(s&&(p+="var thisWired = classParam.toWireType("+m+", this);\n"),l=0;l<a-2;++l)p+="var arg"+l+"Wired = argType"+l+".toWireType("+m+", arg"+l+"); // "+t[l+2].name+"\n",f.push("argType"+l),_.push(t[l+2]);if(s&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||n?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",c)p+="runDestructors(destructors);\n";else for(l=s?1:2;l<t.length;++l){var g=1===l?"thisWired":"arg"+(l-2)+"Wired";null!==t[l].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[l].name+"\n",f.push(g+"_dtor"),_.push(t[l].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),Je(Function,f).apply(null,_)}function $e(){this.allocated=[void 0],this.freelist=[]}var Qe=new $e;function Ze(e){e>=Qe.reserved&&0==--Qe.get(e).refcount&&Qe.free(e)}var et={toValue:e=>(e||pe("Cannot use deleted val. handle = "+e),Qe.get(e).value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Qe.allocate({refcount:1,value:e})}}};function tt(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function rt(e,t){switch(t){case 2:return function(e){return this.fromWireType(I[e>>2])};case 3:return function(e){return this.fromWireType(A[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function it(e,t,r){switch(t){case 0:return r?function(e){return _[e]}:function(e){return g[e]};case 1:return r?function(e){return E[e>>1]}:function(e){return v[e>>1]};case 2:return r?function(e){return y[e>>2]}:function(e){return T[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var ot,nt,at="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,st=(e,t)=>{for(var r=e,i=r>>1,o=i+t/2;!(i>=o)&&v[i];)++i;if((r=i<<1)-e>32&&at)return at.decode(g.subarray(e,r));for(var n="",a=0;!(a>=t/2);++a){var s=E[e+2*a>>1];if(0==s)break;n+=String.fromCharCode(s)}return n},ct=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,o=(r-=2)<2*e.length?r/2:e.length,n=0;n<o;++n){var a=e.charCodeAt(n);E[t>>1]=a,t+=2}return E[t>>1]=0,t-i},lt=e=>2*e.length,dt=(e,t)=>{for(var r=0,i="";!(r>=t/4);){var o=y[e+4*r>>2];if(0==o)break;if(++r,o>=65536){var n=o-65536;i+=String.fromCharCode(55296|n>>10,56320|1023&n)}else i+=String.fromCharCode(o)}return i},ut=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t,o=i+r-4,n=0;n<e.length;++n){var a=e.charCodeAt(n);if(a>=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++n)),y[t>>2]=a,(t+=4)+4>o)break}return y[t>>2]=0,t-i},ht=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i>=55296&&i<=57343&&++r,t+=4}return t},pt={},mt=[],ft=[],_t={},gt=()=>{if(!gt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:c||"./this.program"};for(var t in _t)void 0===_t[t]?delete e[t]:e[t]=_t[t];var r=[];for(var t in e)r.push("".concat(t,"=").concat(e[t]));gt.strings=r}return gt.strings},Et=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=ie.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i};Object.defineProperties(Et.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return ie.isDir(this.mode)}},isDevice:{get:function(){return ie.isChrdev(this.mode)}}}),ie.FSNode=Et,ie.createPreloadedFile=function(e,t,r,i,o,a,s,c,l,d){var u=t?z.resolve(j.join2(e,t)):e;function h(r){function n(r){d&&d(),c||ie.createDataFile(e,t,r,i,o,l),a&&a(),x()}(function(e,t,r,i){"undefined"!=typeof Browser&&Browser.init();var o=!1;return te.forEach((function(n){o||n.canHandle(t)&&(n.handle(e,t,r,i),o=!0)})),o})(r,u,n,(()=>{s&&s(),x()}))||n(r)}P(),"string"==typeof r?((e,t,r,i)=>{var o=i?"":"al ".concat(e);n(e,(r=>{var i;i='Loading data file "'.concat(e,'" failed (no arrayBuffer).'),r||U(i),t(new Uint8Array(r)),o&&x()}),(t=>{if(!r)throw'Loading data file "'.concat(e,'" failed.');r()})),o&&P()})(r,(e=>h(e)),s):h(r)},ie.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);se=e}(),he=i.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},me=i.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},Ne.prototype.isAliasOf=function(e){if(!(this instanceof Ne&&e instanceof Ne))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,o=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)o=i.upcast(o),i=i.baseClass;return t===i&&r===o},Ne.prototype.clone=function(){if(this.$$.ptr||Ee(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=De(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},Ne.prototype.delete=function(){this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pe("Object already scheduled for deletion"),ye(this),Te(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},Ne.prototype.isDeleted=function(){return!this.$$.ptr},Ne.prototype.deleteLater=function(){return this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pe("Object already scheduled for deletion"),Se.push(this),1===Se.length&&be&&be(Re),this.$$.deleteScheduled=!0,this},i.getInheritedInstanceCount=function(){return Object.keys(we).length},i.getLiveInheritedInstances=function(){var e=[];for(var t in we)we.hasOwnProperty(t)&&e.push(we[t]);return e},i.flushPendingDeletes=Re,i.setDelayFunction=function(e){be=e,Se.length&&be&&be(Re)},Be.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},Be.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},Be.prototype.argPackAdvance=8,Be.prototype.readValueFromPointer=Fe,Be.prototype.deleteObject=function(e){null!==e&&e.delete()},Be.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=function(e,t){return t=function(e,t){for(void 0===t&&pe("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),we[t]}(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function o(){return this.isSmartPointer?Ce(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):Ce(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var n,a=this.registeredClass.getActualType(t),s=Ae[a];if(!s)return o.call(this);n=this.isConst?s.constPointerType:s.pointerType;var c=Ie(t,this.registeredClass,n.registeredClass);return null===c?o.call(this):this.isSmartPointer?Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:c,smartPtrType:this,smartPtr:e}):Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:c})},Ge=i.UnboundTypeError=(ot=Error,(nt=Oe("UnboundTypeError",(function(e){this.name="UnboundTypeError",this.message=e;var t=new Error(e).stack;void 0!==t&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))}))).prototype=Object.create(ot.prototype),nt.prototype.constructor=nt,nt.prototype.toString=function(){return void 0===this.message?this.name:"".concat(this.name,": ").concat(this.message)},nt),Object.assign($e.prototype,{get(e){return this.allocated[e]},has(e){return void 0!==this.allocated[e]},allocate(e){var t=this.freelist.pop()||this.allocated.length;return this.allocated[t]=e,t},free(e){this.allocated[e]=void 0,this.freelist.push(e)}}),Qe.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Qe.reserved=Qe.allocated.length,i.count_emval_handles=function(){for(var e=0,t=Qe.reserved;t<Qe.allocated.length;++t)void 0!==Qe.allocated[t]&&++e;return e};var vt,yt={p:function(e,t,r){throw new W(e).init(t,r),e},C:function(e,t,r){ne.varargs=r;try{var i=ne.getStreamFromFD(e);switch(t){case 0:return(o=ne.get())<0?-28:ie.createStream(i,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var o=ne.get();return i.flags|=o,0;case 5:return o=ne.get(),E[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return y[At()>>2]=28,-1}}catch(n){if(void 0===ie||"ErrnoError"!==n.name)throw n;return-n.errno}},w:function(e,t,r,i){ne.varargs=i;try{t=ne.getStr(t),t=ne.calculateAt(e,t);var o=i?ne.get():0;return ie.open(t,r,o).fd}catch(n){if(void 0===ie||"ErrnoError"!==n.name)throw n;return-n.errno}},t:function(e,t,r,i,o){},n:function(e,t,r,i,o){var n=ae(r);ge(e,{name:t=ce(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:o},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=_;else if(2===r)i=E;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=y}return this.fromWireType(i[e>>n])},destructorFunction:null})},r:function(e,t,r,o,n,a,s,c,l,d,u,h,p){u=ce(u),a=je(n,a),c&&(c=je(s,c)),d&&(d=je(l,d)),p=je(h,p);var m,f,_,g=ke(u);m=g,f=function(){Ke("Cannot construct ".concat(u," due to unbound types"),[o])},i.hasOwnProperty(m)?(pe("Cannot register public name '".concat(m,"' twice")),Me(i,m,m),i.hasOwnProperty(_)&&pe("Cannot register multiple overloads of a function with the same number of arguments (".concat(_,")!")),i[m].overloadTable[_]=f):i[m]=f,_e([e,t,r],o?[o]:[],(function(t){var r,n;t=t[0],n=o?(r=t.registeredClass).instancePrototype:Ne.prototype;var s=Oe(g,(function(){if(Object.getPrototypeOf(this)!==l)throw new he("Use 'new' to construct "+u);if(void 0===h.constructor_body)throw new he(u+" has no accessible constructor");var e=h.constructor_body[arguments.length];if(void 0===e)throw new he("Tried to invoke ctor of ".concat(u," with invalid number of parameters (").concat(arguments.length,") - expected (").concat(Object.keys(h.constructor_body).toString(),") parameters instead!"));return e.apply(this,arguments)})),l=Object.create(n,{constructor:{value:s}});s.prototype=l;var h=new Le(u,s,l,p,r,a,c,d);h.baseClass&&(void 0===h.baseClass.__derivedClasses&&(h.baseClass.__derivedClasses=[]),h.baseClass.__derivedClasses.push(h));var m,f,_,E=new Be(u,h,!0,!1,!1),v=new Be(u+"*",h,!1,!1,!1),y=new Be(u+" const*",h,!1,!0,!1);return Ae[e]={pointerType:v,constPointerType:y},m=g,f=s,i.hasOwnProperty(m)||fe("Replacing nonexistant public symbol"),i[m].overloadTable,i[m]=f,i[m].argCount=_,[E,v,y]}))},q:function(e,t,r,i,o,n){var a=qe(t,r);o=je(i,o),_e([],[e],(function(e){var r="constructor ".concat((e=e[0]).name);if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new he("Cannot register multiple constructors with identical number of parameters (".concat(t-1,") for class '").concat(e.name,"'! Overload resolution is currently only performed using the parameter count, not actual type info!"));return e.registeredClass.constructor_body[t-1]=()=>{Ke("Cannot construct ".concat(e.name," due to unbound types"),a)},_e([],a,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=Xe(r,i,null,o,n),[]})),[]}))},d:function(e,t,r,i,o,n,a,s,c){var l=qe(r,i);t=ce(t),n=je(o,n),_e([],[e],(function(e){var i="".concat((e=e[0]).name,".").concat(t);function o(){Ke("Cannot call ".concat(i," due to unbound types"),l)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),s&&e.registeredClass.pureVirtualFunctions.push(t);var d=e.registeredClass.instancePrototype,u=d[t];return void 0===u||void 0===u.overloadTable&&u.className!==e.name&&u.argCount===r-2?(o.argCount=r-2,o.className=e.name,d[t]=o):(Me(d,t,i),d[t].overloadTable[r-2]=o),_e([],l,(function(o){var s=Xe(i,o,e,n,a,c);return void 0===d[t].overloadTable?(s.argCount=r-2,d[t]=s):d[t].overloadTable[r-2]=s,[]})),[]}))},D:function(e,t){ge(e,{name:t=ce(t),fromWireType:function(e){var t=et.toValue(e);return Ze(e),t},toWireType:function(e,t){return et.toHandle(t)},argPackAdvance:8,readValueFromPointer:Fe,destructorFunction:null})},k:function(e,t,r){var i=ae(r);ge(e,{name:t=ce(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:rt(t,i),destructorFunction:null})},c:function(e,t,r,i,o){t=ce(t);var n=ae(r),a=e=>e;if(0===i){var s=32-8*r;a=e=>e<<s>>>s}var c=t.includes("unsigned");ge(e,{name:t,fromWireType:a,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:it(t,n,0!==i),destructorFunction:null})},b:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function o(e){var t=T,r=t[e>>=2],o=t[e+1];return new i(t.buffer,o,r)}ge(e,{name:r=ce(r),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var r="std::string"===(t=ce(t));ge(e,{name:t,fromWireType:function(e){var t,i=T[e>>2],o=e+4;if(r)for(var n=o,a=0;a<=i;++a){var s=o+a;if(a==i||0==g[s]){var c=oe(n,s-n);void 0===t?t=c:(t+="\0",t+=c),n=s+1}}else{var l=new Array(i);for(a=0;a<i;++a)l[a]=String.fromCharCode(g[o+a]);t=l.join("")}return It(e),t},toWireType:function(e,t){var i;t instanceof ArrayBuffer&&(t=new Uint8Array(t));var o="string"==typeof t;o||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||pe("Cannot pass non-string to std::string"),i=r&&o?J(t):t.length;var n=Tt(4+i+1),a=n+4;if(T[n>>2]=i,r&&o)X(t,g,a,i+1);else if(o)for(var s=0;s<i;++s){var c=t.charCodeAt(s);c>255&&(It(a),pe("String has UTF-16 code units that do not fit in 8 bits")),g[a+s]=c}else for(s=0;s<i;++s)g[a+s]=t[s];return null!==e&&e.push(It,n),n},argPackAdvance:8,readValueFromPointer:Fe,destructorFunction:function(e){It(e)}})},f:function(e,t,r){var i,o,n,a,s;r=ce(r),2===t?(i=st,o=ct,a=lt,n=()=>v,s=1):4===t&&(i=dt,o=ut,a=ht,n=()=>T,s=2),ge(e,{name:r,fromWireType:function(e){for(var r,o=T[e>>2],a=n(),c=e+4,l=0;l<=o;++l){var d=e+4+l*t;if(l==o||0==a[d>>s]){var u=i(c,d-c);void 0===r?r=u:(r+="\0",r+=u),c=d+t}}return It(e),r},toWireType:function(e,i){"string"!=typeof i&&pe("Cannot pass non-string to C++ string type ".concat(r));var n=a(i),c=Tt(4+n+t);return T[c>>2]=n>>s,o(i,c+4,n+t),null!==e&&e.push(It,c),c},argPackAdvance:8,readValueFromPointer:Fe,destructorFunction:function(e){It(e)}})},o:function(e,t){ge(e,{isVoid:!0,name:t=ce(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,r,i){var o,n;(e=mt[e])(t=et.toValue(t),r=void 0===(n=pt[o=r])?ce(o):n,null,i)},m:Ze,l:function(e,t){var r=function(e,t){for(var r,i,o,n=new Array(e),a=0;a<e;++a)n[a]=(r=T[t+4*a>>2],i="parameter "+a,void 0===(o=de[r])&&pe(i+" has unknown type "+ze(r)),o);return n}(e,t),i=r[0],o=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",n=ft[o];if(void 0!==n)return n;for(var a=["retType"],s=[i],c="",l=0;l<e-1;++l)c+=(0!==l?", ":"")+"arg"+l,a.push("argType"+l),s.push(r[1+l]);var d,u,h="return function "+ke("methodCaller_"+o)+"(handle, name, destructors, args) {\n",p=0;for(l=0;l<e-1;++l)h+=" var arg"+l+" = argType"+l+".readValueFromPointer(args"+(p?"+"+p:"")+");\n",p+=r[l+1].argPackAdvance;for(h+=" var rv = handle[name]("+c+");\n",l=0;l<e-1;++l)r[l+1].deleteObject&&(h+=" argType"+l+".deleteObject(arg"+l+");\n");return i.isVoid||(h+=" return retType.toWireType(destructors, rv);\n"),h+="};\n",a.push(h),d=Je(Function,a).apply(null,s),u=mt.length,mt.push(d),n=u,ft[o]=n,n},a:()=>{U("")},e:function(){return Date.now()},v:()=>g.length,A:(e,t,r)=>g.copyWithin(e,t,t+r),u:e=>{g.length,U("OOM")},y:(e,t)=>{var r=0;return gt().forEach((function(i,o){var n=t+r;T[e+4*o>>2]=n,((e,t)=>{for(var r=0;r<e.length;++r)_[0|t++]=e.charCodeAt(r);_[0|t]=0})(i,n),r+=i.length+1})),0},z:(e,t)=>{var r=gt();T[e>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),T[t>>2]=i,0},i:function(e){try{var t=ne.getStreamFromFD(e);return ie.close(t),0}catch(r){if(void 0===ie||"ErrnoError"!==r.name)throw r;return r.errno}},x:function(e,t){try{var r=ne.getStreamFromFD(e),i=r.tty?2:ie.isDir(r.mode)?3:ie.isLink(r.mode)?7:4;return _[0|t]=i,E[t+2>>1]=0,C=[0,(w=0,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[t+8>>2]=C[0],y[t+12>>2]=C[1],C=[0,(w=0,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[t+16>>2]=C[0],y[t+20>>2]=C[1],0}catch(o){if(void 0===ie||"ErrnoError"!==o.name)throw o;return o.errno}},B:function(e,t,r,i){try{var o=((e,t,r,i)=>{for(var o=0,n=0;n<r;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var c=ie.read(e,_,a,s,i);if(c<0)return-1;if(o+=c,c<s)break;void 0!==i&&(i+=c)}return o})(ne.getStreamFromFD(e),t,r);return T[i>>2]=o,0}catch(n){if(void 0===ie||"ErrnoError"!==n.name)throw n;return n.errno}},s:function(e,t,r,i,o){var n,a,s=(a=r)+2097152>>>0<4194305-!!(n=t)?(n>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var c=ne.getStreamFromFD(e);return ie.llseek(c,s,i),C=[c.position>>>0,(w=c.position,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[o>>2]=C[0],y[o+4>>2]=C[1],c.getdents&&0===s&&0===i&&(c.getdents=null),0}catch(l){if(void 0===ie||"ErrnoError"!==l.name)throw l;return l.errno}},h:function(e,t,r,i){try{var o=((e,t,r,i)=>{for(var o=0,n=0;n<r;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var c=ie.write(e,_,a,s,i);if(c<0)return-1;o+=c,void 0!==i&&(i+=c)}return o})(ne.getStreamFromFD(e),t,r);return T[i>>2]=o,0}catch(n){if(void 0===ie||"ErrnoError"!==n.name)throw n;return n.errno}}},Tt=(function(){var e,t,o,n,a={a:yt};function s(e,t){var r,o,n=e.exports;return r=(p=n).E.buffer,i.HEAP8=_=new Int8Array(r),i.HEAP16=E=new Int16Array(r),i.HEAP32=y=new Int32Array(r),i.HEAPU8=g=new Uint8Array(r),i.HEAPU16=v=new Uint16Array(r),i.HEAPU32=T=new Uint32Array(r),i.HEAPF32=I=new Float32Array(r),i.HEAPF64=A=new Float64Array(r),S=p.H,o=p.F,k.unshift(o),x(),n}if(P(),i.instantiateWasm)try{return i.instantiateWasm(a,s)}catch(c){f("Module.instantiateWasm callback failed with error: "+c),r(c)}(e=h,t=R,o=a,n=function(e){s(e.instance)},e||"function"!=typeof WebAssembly.instantiateStreaming||V(t)||"function"!=typeof fetch?B(t,o,n):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,o).then(n,(function(e){return f("wasm streaming compile failed: "+e),f("falling back to ArrayBuffer instantiation"),B(t,o,n)}))))).catch(r)}(),e=>(Tt=p.G)(e)),It=e=>(It=p.I)(e),At=()=>(At=p.J)(),St=e=>(St=p.K)(e),Rt=(i.__embind_initialize_bindings=()=>(i.__embind_initialize_bindings=p.L)(),e=>(Rt=p.M)(e));function bt(){function e(){vt||(vt=!0,i.calledRun=!0,D||(i.noFSInit||ie.init.initialized||ie.init(),ie.ignorePermissions=!1,H(k),t(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for("function"==typeof i.postRun&&(i.postRun=[i.postRun]);i.postRun.length;)e=i.postRun.shift(),O.unshift(e);var e;H(O)}()))}M>0||(function(){if(i.preRun)for("function"==typeof i.preRun&&(i.preRun=[i.preRun]);i.preRun.length;)e=i.preRun.shift(),N.unshift(e);var e;H(N)}(),M>0||(i.setStatus?(i.setStatus("Running..."),setTimeout((function(){setTimeout((function(){i.setStatus("")}),1),e()}),1)):e()))}if(i.dynCall_jiji=(e,t,r,o,n)=>(i.dynCall_jiji=p.N)(e,t,r,o,n),i._ff_h264_cabac_tables=67061,L=function e(){vt||bt(),vt||(L=e)},i.preInit)for("function"==typeof i.preInit&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return bt(),e.ready}),IH=TH,AH=class extends vH{constructor(e){super(IH,null!=e&&e.wasmPath?fetch(null==e?void 0:e.wasmPath).then((e=>e.arrayBuffer())):void 0,null==e?void 0:e.workerMode,null==e?void 0:e.canvas,null==e?void 0:e.yuvMode)}};(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0})();var SH=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(SH||{});function RH(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var bH=class e{constructor(e){this.core=e,nH(this,"contextMap",new Map),nH(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(e){return null!=e&&e.track?"".concat(e.track.userId).concat(e.track.streamType):"*"}getName(){return e.Name}getValidateRule(e){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(e,t){var r;switch(e){case"wasm":let e=(null==(r=this.core.assetsPath)?void 0:r.replace(/\/+$/,""))||".";return new AH(iH(rH({},t),{wasmPath:"".concat(e,"/videodec.wasm")}));case"webCodecs":return new gH;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(e){this.decodeProcessorMap.set(e.track,this.decode(e)),this.core.room.videoManager.addDecodeProcessor({processor:e=>{let{frame:t,track:r}=e;var i;return(null==(i=this.decodeProcessorMap.get(r))?void 0:i({frame:t,track:r}))||t},type:3})}decode(e){let{pipe:t,take:r,subscribe:i}=this.core.rx;return o=>{let{frame:n,track:a}=o;if(a!==e.track||"empty"===n.type)return n;if(this.contextMap.has(a))return this.contextMap.get(a).decode(n);let s=this.core.room.videoManager.createDecodeContext(iH(rH({},e),{createDecoder:this.createDecoder}));return t(s.trackDoneOB,r(1),i((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:a})}))),this.contextMap.set(a,s),s.decode(n)}}stop(e){if(null!=e&&e.track){let t=this.contextMap.get(e.track);t&&(t.close("stop"),this.report(t,e.track),this.contextMap.delete(e.track))}else this.contextMap.forEach(((e,t)=>{e.close("stop"),this.contextMap.delete(t)}));0===this.contextMap.size&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(e,t){if(e.isReported)return;e.isReported=!0;let r=RH()-e.startPerformanceTime,{renderFreezeTotal:i,dataFreezeTotal:o}=this.getRemoteTrackFreezeDuration(t,e),n="report health data: ".concat(e.track.userId," ").concat(e.track.streamType," ").concat(e.type,"+").concat(e.renderer," goodType:").concat(e.goodType," ").concat(e.failedReason?"failedReason: ".concat(e.failedReason):"");r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(i/r*100),split:1,max:100}),n+=" RENDER_FREEZE_RATE: ".concat(Math.floor(i/r*100),"%")),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(o/r*100),split:1,max:100}),n+=" DATA_FREEZE_RATE: ".concat(Math.floor(o/r*100),"%")),e.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(e.decodedFrameCount/e.inputFrameCount*100),split:1,max:100}),n+=" VIDEO_CONSUME_RENDER_RATE: ".concat(Math.floor(e.decodedFrameCount/e.inputFrameCount*100),"%")),this.core.log.info(n)}addKVReportBeforeExitRoom(e){let{room:t}=e;t===this.core.room&&this.contextMap.forEach(((e,t)=>{this.report(e,t)}))}update(e){let t=this.contextMap.get(e.track);t&&("mock"!==e.type?(t.close("update"),this.contextMap.set(e.track,this.core.room.videoManager.createDecodeContext(iH(rH({},e),{createDecoder:this.createDecoder})))):t.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(e,t){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get("".concat(e.userId,"_").concat(e.streamType)),i=this.core.room.badCaseDetector.getDataFreezeMap().get("".concat(e.userId,"_").concat(e.streamType)),o=0;r&&r.freezeTimeline.forEach((e=>{let{startTime:r,endTime:i}=e;r>t.startPerformanceTime&&(o+=0===i?RH()-r:i-r)}));let n=0;return i&&i.durationItemList.forEach((e=>{e.startTime>t.startPerformanceTime&&(n+=e.getDuration())})),{renderFreezeTotal:o,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};nH(bH,"Name","TRTCVideoDecoder");var wH=bH,CH=ew(nw());function DH(e){let{timesInSecond:t,maxSizeInSecond:r,getSize:i}=e;return yU(((e,o)=>{let n=new WeakMap;return WO.on(GO.ROOM_DESTROY,(e=>{let{room:t}=e;return n.delete(t)})),function(){let a=n.get(this);for(var s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.set(this,a)),0===a.timestamp?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),i&&(a.totalSizeInSecond+=i(...c)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>r))throw new pw({code:uw.INVALID_OPERATION,message:sL({key:iL.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>r,name:o,timesInSecond:t,maxSizeInSecond:r}})});a.callCountInSecond++,e.call(this,...c)}}))}var NH,kH=!0,OH={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",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},MH={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},LH=((NH=LH||{})[NH.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",NH[NH.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",NH[NH.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",NH[NH.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",NH[NH.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",NH[NH.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",NH[NH.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",NH[NH.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",NH[NH.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",NH[NH.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",NH[NH.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",NH[NH.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",NH[NH.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",NH[NH.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",NH[NH.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",NH[NH.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",NH[NH.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",NH[NH.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",NH[NH.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",NH[NH.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",NH[NH.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",NH[NH.INVALID_OPERATION=5100]="INVALID_OPERATION",NH[NH.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",NH[NH.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",NH[NH.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",NH[NH.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",NH[NH.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",NH[NH.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",NH[NH.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",NH[NH.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",NH[NH.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",NH[NH.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",NH[NH.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",NH[NH.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",NH[NH.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",NH[NH.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",NH[NH.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",NH[NH.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",NH[NH.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",NH[NH.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",NH[NH.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",NH[NH.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",NH[NH.DEVICE_ERROR=5300]="DEVICE_ERROR",NH[NH.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",NH[NH.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",NH[NH.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",NH[NH.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",NH[NH.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",NH[NH.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",NH[NH.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",NH[NH.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",NH[NH.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",NH[NH.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",NH[NH.SERVER_ERROR=5400]="SERVER_ERROR",NH[NH.NEED_TO_BUY=5401]="NEED_TO_BUY",NH[NH.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",NH[NH.OPERATION_FAILED=5500]="OPERATION_FAILED",NH[NH.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",NH[NH.REJOIN_FAILED=5502]="REJOIN_FAILED",NH[NH.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",NH[NH.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",NH[NH.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",NH[NH.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",NH[NH.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",NH[NH.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",NH[NH.OPERATION_ABORT=5998]="OPERATION_ABORT",NH[NH.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",NH);var PH=$b(Xb({},oL),{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:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' is a required param when calling ").concat(i,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:r,fnName:i,value:o}=e,n="".concat(t||r.name),a="";return a=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(i,"(), received type: ").concat(UD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' cannot be '").concat(o,"' when calling ").concat(i,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:r,fnName:i,value:o}=e,n="".concat(t||r.name),a="".concat(r.instanceOf.name||r.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(i,"(), received type: ").concat(UD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:r,fnName:i,value:o}=e;return"'".concat(t||r.name,"' must be one of ").concat(r.values.join("|")," when calling ").concat(i,"(), received: ").concat(o,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:r,fnName:i}=e;return"'".concat(t||r.name,"' cannot be less than 0 when calling ").concat(i,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:r,value:i}=e;return"the min value of ".concat(t||r.name," is ").concat(r.min,", received: ").concat(i,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:r,value:i}=e;return"the max value of ".concat(t||r.name," is ").concat(r.max,", received: ").concat(i,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:r}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(r,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:r,type:i}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(r,"(), received: ").concat(i,".")},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_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(e){let{key:t}=e;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat("strRoomId"===t?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(e){let{key:t}=e;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},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:r}=e;return"cannot ".concat(t," because remote user(userId: ").concat(r.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:r}=e;return"cannot ".concat(t," because remote user(userId: ").concat(r.userId,") does not publishing ").concat(r.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 or screen share is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},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:r}=e;return"'".concat(t,"' got device exception").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=e;return"NotFoundError, no ".concat(r," detected, please check your device and the configuration on '").concat(t,"'").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=e;return"NotAllowedError, you have disabled ".concat(r," access, please allow the current application to use the ").concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=e;return"NotReadableError, the ".concat(r," 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:r=xH(t),error:i}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(r,", and it is recommended to turn on the ").concat(r," after the user interacts with the page").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:r=xH(t),error:i}=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(i?" error: ".concat(i.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:r}=e;return"'".concat(t,"' failed, reason: ").concat(null==r?void 0:r.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:r}=e;return"video context error ".concat(t," ").concat((null==r?void 0:r.name)||""," ").concat((null==r?void 0:r.message)||"")},SERVER_ERROR(e){let{fnName:t,error:r}=e;return"'".concat(t,"' got server error: ").concat(null==r?void 0:r.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:r}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(r)},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:r}=e;return"'".concat(t,"' throw unknown exception").concat(r?", error: ".concat(r.toString(),"."):".")}});function xH(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var UH=class e extends Error{constructor(e){let{code:t,extraCode:r,message:i="",messageParams:o,fnName:n="",originError:a,data:s}=e;var c;let l;l=i||function(e){let t,{code:r,params:i,enableDocLink:o=!1}=e,a="",s=LH[r];try{t=PH[s]}catch(n){t=PH.UNKNOWN_ERROR}return VD(t)?a=t(i):BD(t)&&(a=t),i.fnName&&!a.includes(i.fnName)&&("."!==a[a.length-1]&&(a+="."),a+=" thrown from ".concat(i.fnName,"()")),o&&(a+=" doc:"),a}({code:t===MH.SERVER_ERROR?t:r||t,params:Xb({fnName:n,error:a},o)}),super(l),rw(this,"name","RtcError"),rw(this,"code"),rw(this,"extraCode"),rw(this,"functionName"),rw(this,"message"),rw(this,"data"),rw(this,"handler"),rw(this,"originError"),this.name=LH[t],this.code=t,this.extraCode=r,this.functionName=n,this.originError=a,this.message=l,this.data=s,5302===this.extraCode&&null!=(c=this.originError)&&c.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");xk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):Uk&&(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(t,r,i){let o=t;if(t instanceof pw){let{stack:n}=t,a={code:MH.UNKNOWN_ERROR,fnName:r,originError:t};switch(t.getCode()){case uw.INVALID_PARAMETER:a.code=MH.INVALID_PARAMETER,a.message=t.message;break;case uw.INVALID_OPERATION:a.code=MH.INVALID_OPERATION;break;case uw.NOT_SUPPORTED:case uw.NOT_SUPPORTED_H264:a.code=MH.ENV_NOT_SUPPORTED,t.getCode()===uw.NOT_SUPPORTED_H264&&(a.extraCode=t.message.includes(oL.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case uw.JOIN_ROOM_FAILED:a.messageParams={fnParams:i};case uw.SERVER_TIMEOUT:case uw.SWITCH_ROLE_FAILED:case uw.SWITCH_ROOM_FAILED:a.code=MH.SERVER_ERROR,a.extraCode=t.getExtraCode();break;case uw.API_CALL_ABORTED:a.code=MH.OPERATION_ABORT;break;case uw.DEVICE_NOT_FOUND:case uw.DEVICE_AUTO_RECOVER_FAILED:case uw.INITIALIZE_FAILED:a.code=5300,t.name&&(a.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}(t.name));break;case uw.VIDEO_ENCODE_FAILED:a.extraCode=5505;case uw.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=MH.OPERATION_FAILED;break;case uw.UNKNOWN:break;default:a.code=MH.OPERATION_FAILED}o=new e(a),n&&(o.stack+=n.substr(n.indexOf("\n")))}else{if(t instanceof e)return t;o=new e({code:MH.UNKNOWN_ERROR,fnName:r,originError:t})}return o}};var VH=UH;function FH(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function BH(e){return e===OH.QOS_PREFERENCE_CLEAR?"detail":e===OH.QOS_PREFERENCE_SMOOTH?"motion":""}function HH(e,t){let r=t?Jw:Yw;return HN(e)?Xb(Xb({},r),e):qw[e]?qw[e]:r}var WH={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},jH={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}}},GH={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,r){if(BD(e)&&!document.getElementById(e))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5009,fnName:r,messageParams:{key:t}})}},zH={name:"userId",required:!0,type:"string"},KH={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function qH(e,t){if(!e)throw new VH({code:MH.INVALID_OPERATION,extraCode:5101,fnName:t})}function YH(e,t,r){if(!e)throw new VH({code:MH.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:r}})}function JH(e,t,r){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:r}})}function XH(e,t,r){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:r}})}function $H(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!zL())return qO.warn("small stream is not supported"),void delete e.option.small;let r=HH(e.option.profile),i=HH(e.option.small,!0);return((e,t)=>e.width*e.height>=t.width*t.height&&e.frameRate>=t.frameRate&&e.bitrate>=t.bitrate)(r,i)?void 0:(qO.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(r),", Small: ").concat(JSON.stringify(i))),void delete e.option.small)}var QH={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,r){if(this._room.isJoined)throw new VH({code:MH.INVALID_OPERATION,extraCode:5104,fnName:r});if(e.roomId){if(BD(e.roomId))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5016,fnName:r,messageParams:{key:t}});JH(e.roomId,r,t)}else{if(!e.strRoomId)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5015,fnName:r});XH(e.strRoomId,r,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"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:GH,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:WH},validate(e){var t,r;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&bL())throw new VH({code:MH.ENV_NOT_SUPPORTED,extraCode:5201});null!=(r=null==e?void 0:e.option)&&r.small&&$H(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:$b(Xb({},GH),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:WH},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&$H(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:KH},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&bL())throw new VH({code:MH.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:KH}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:GH,publish:{type:"boolean"},option:jH},validate(e,t,r,i,o){var n;if(null==(n=null==e?void 0:e.option)||!n.videoTrack){if(bL())throw new VH({code:MH.ENV_NOT_SUPPORTED,extraCode:5201});if(!ML())throw new VH({code:MH.ENV_NOT_SUPPORTED,fnName:r,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:GH,publish:{type:"boolean"},option:jH}},muteRemoteAudio:[zH,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[zH,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:GH,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,r){qH(this._room.isJoined,r);let i=this._room.remotePublishedUserMap.get(e.userId);if(YH(!!i,r,e),i&&("main"===e.streamType&&!i.muteState.videoAvailable||"sub"===e.streamType&&!i.muteState.hasAuxiliary))throw new VH({code:MH.INVALID_OPERATION,extraCode:5103,fnName:r,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:$b(Xb({},GH),{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,r){qH(this._room.isJoined,r);let i=this._room.remotePublishedUserMap.get(e.userId);if(YH(!!i,r,e),i&&("main"===e.streamType&&!i.muteState.videoAvailable||"sub"===e.streamType&&!i.muteState.hasAuxiliary))throw new VH({code:MH.INVALID_OPERATION,extraCode:5103,fnName:r,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,r){if("*"!==e.userId&&FD(e.streamType))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5014,fnName:r})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,r){qH(this._room.isJoining||this._room.isJoined,r)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,r,i){if(!cP)throw new VH({code:MH.ENV_NOT_SUPPORTED,fnName:r,extraCode:5207});if(!this._room.enableSEI)throw new VH({code:MH.INVALID_OPERATION,fnName:r,extraCode:5108});if(e.byteLength>1e3)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5018,fnName:r});if(0===e.byteLength)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:r});qH(this._room.isJoined,r)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,r){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new VH({code:MH.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:r})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,r,i){if(e.byteLength>1e3)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5018,fnName:r});if(0===e.byteLength)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5017,fnName:r,messageParams:{key:t}})}}},validate(e,t,r){if(qH(this._room.isJoined,r),"live"===this._room.scene&&"audience"===this._room.role)throw new VH({code:MH.INVALID_OPERATION,extraCode:5107,fnName:r,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,r){if(qH(this._room.isJoined,r),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new VH({code:MH.INVALID_PARAMETER,extraCode:5020,fnName:r,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5019,fnName:r,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)JH(e.roomId,r,t);else{if(!e.strRoomId)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5015,fnName:r});XH(e.strRoomId,r,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},ZH={TRTC:QH},eW=class extends Error{};function tW(e,t){let r=cN(e);for(let i=0;i<t.length;i++)sN(r[i],t[i]);return r}function rW(e){this._resolve=Promise.resolve(e)}function iW(e){this._reject=Promise.reject(e)}var oW=class e{constructor(t,r){this.instance=t,this.group=r,rw(this,"started",!1),rw(this,"ops",[]),rw(this,"startSame",(()=>!0)),rw(this,"mergeUpdate",tW);let i=e.instances.get(t);i?i.set(r,this):e.instances.set(t,new Map([[r,this]]))}static get(t,r){if(!r)return;let i=e.instances.get(t);return i&&i.get(r)||new e(t,r)}static gets(t,r){let i=e.instances.get(t),o=[];return i&&i.forEach(((e,t)=>{r.test(t)&&o.push(e)})),o}action(e,t,r){let i=t=>{var r;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(r=this.currentOp)||r.action(),t},o=t=>{var r,i;throw this.ops.shift(),0===e&&2===(null==(r=this.currentOp)?void 0:r.type)&&this.ops.shift().reject(new eW("start failed")),null==(i=this.currentOp)||i.action(),t},n={type:e,action:()=>t(...n.args).then(i,o),args:r,resolve:rW,reject:iW};try{switch(this.state){case 1:if(0===e)throw new eW("already started");break;case 4:if(2===e)throw new eW("not started");break;default:return this.cacheOp(n)}}catch(rM){return Promise.reject(rM)}return this.ops.push(n),n.promise=t(...n.args).then(i,o)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new eW("already start");break;case 3:switch(e.type){case 2:throw new eW("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new eW("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new eW("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 eW("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new eW("start not allowed after update");case 0:throw new eW("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new eW("keep start")),new eW("already start")}}e.promise=new Promise(((t,r)=>{e._resolve?e._resolve.then(t):e.resolve=t,e._reject?e._reject.catch(r):e.reject=r}));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}};rw(oW,"instances",new WeakMap);var nW=oW,aW=new WeakMap,sW=(e,t)=>{if(t instanceof eW){let{stack:r}=t;t=new VH({code:MH.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),r&&(t.stack+=r.substr(r.indexOf("\n")))}throw t};function cW(e,t){return yU(((r,i)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let s=nW.get(this,"string"==typeof e?e:e.call(this,...n));return s?(t&&(s.startSame=t.bind(this)),s.action(0,r.bind(this),n).catch(sW.bind(null,i))):r.apply(this,n)}))}function lW(e,t){let{merge:r,debounce:i}=t||{};return yU(((t,o)=>function(){for(var n=arguments.length,a=new Array(n),s=0;s<n;s++)a[s]=arguments[s];let c=nW.get(this,"string"==typeof e?e:e.call(this,...a));if(!c)return t.apply(this,a);if(r&&(c.mergeUpdate=r.bind(this)),i&&i.isNeedToDebounce.apply(this,a)){let{delay:e,getKey:r}=i;return new Promise(((i,n)=>{var s,l;let d=null==(s=aW.get(this))?void 0:s.get(r(...a));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return i();c.action(2,t.bind(this),a).catch(sW.bind(null,o)).then(i,n)}),e);aW.has(this)?null==(l=aW.get(this))||l.set(r(...a),{timeoutId:u,resolve:i}):aW.set(this,new Map([[r(...a),{timeoutId:u,resolve:i}]]))}))}return c.action(2,t.bind(this),a).catch(sW.bind(null,o))}))}function dW(e){return yU(((t,r)=>function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];let a="function"==typeof e?e.call(this,...o):e;if(a instanceof RegExp)return Promise.all(nW.gets(this,a).map((e=>e.action(3,(()=>Promise.resolve()),o)))).then((()=>t.call(this,...o)));let s=nW.get(this,a);return s?s.action(3,t.bind(this),o).catch(sW.bind(null,r)):t.apply(this,o)}))}var uW={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",AUDIO_FRAME:"audio-frame",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",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},hW=new Set([uW.ERROR,uW.AUTOPLAY_FAILED,uW.KICKED_OUT,uW.REMOTE_USER_ENTER,uW.REMOTE_USER_EXIT,uW.REMOTE_AUDIO_AVAILABLE,uW.REMOTE_AUDIO_UNAVAILABLE,uW.REMOTE_VIDEO_AVAILABLE,uW.REMOTE_VIDEO_UNAVAILABLE,uW.CONNECTION_STATE_CHANGED,uW.PUBLISH_STATE_CHANGED,uW.SCREEN_SHARE_STOPPED,uW.DEVICE_CHANGED,uW.FIRST_VIDEO_FRAME,uW.PERMISSION_STATE_CHANGE,uW.VIDEO_SIZE_CHANGED]),pW={};Zb(pW,{ScheduleRequestType:()=>yW,getAbilityConfig:()=>IW,getScheduleDomain:()=>AW,isNeedToSchedule:()=>fW,scheduleProxy:()=>EW,sendScheduleRequest:()=>gW,setIsNeedToSchedule:()=>_W,setScheduleProxy:()=>vW});var mW=null,fW=!0;function _W(e){WD(e)&&e!==fW&&(fW=e,qO.info("setIsNeedToSchedule ".concat(e)))}function gW(e){return ow(this,arguments,(function(e){let{userId:t,sdkAppId:r,useStringRoomId:i,roomId:o,userSig:n,version:a,frameWorkType:s,role:c,latencyLevel:l}=e;return function*(){var e;if(!fW&&mW)return{isCached:!0,result:mW};let d={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(t)),u.append("sdkAppId",String(r)),u.append("isStrGroupId",String(i)),u.append("groupId",String(o)),u.append("sdkVersion",a),u.append("userSig",String(n));let h=(null==(e=yield NO())?void 0:e.model)||MO();h&&u.append("model",h),c&&u.append("role",String(c)),l&&u.append("latencyLevel",String(l)),s&&u.append("frameWorkType",String(s));let p=ZD(),m=yield function(e,t,r){return new Promise(((i,o)=>{let n=null;QD([RW((e=>t.count[0]=e+1),(e=>{let{error:i,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[0]=i.message,n||(a>=1&&(s[0]=TW(r,"config",$w.MAIN,!0)),o())}))(TW(r,"config",$w.MAIN),e,{get timeout(){return 1e3*PD(2+t.count[0])}}),RW((e=>t.count[1]=e+1),(e=>{let{error:i,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[1]=i.message,n||(a>=2&&(s[0]=TW(r,"config",$w.BACKUP,!0)),o())}))(TW(r,"config",$w.BACKUP),e,{get timeout(){return 1e3*PD(2+t.count[1])}})]).then((e=>{n=e,i(n)})).catch(o)}))}(u,d,r);m.config&&(m.config.loggerDomain&&Dw(m.config.loggerDomain),WD(m.config.scheduleCache)&&_W(!m.config.scheduleCache)),d.delta=ZD()-p;let f=function(e,t,r){let i={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),n=TW(e,"config",$w.MAIN),a=TW(e,"config",$w.BACKUP);for(let e of o)if(e.startTime>=r&&(e.name===n||e.name===a)&&e.transferSize>0){let r=e.name===n?$w.MAIN:$w.BACKUP,o=Math.round(e.duration),a=Math.round(e.domainLookupStart-e.startTime),s=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];qP.uploadEvent({log:"stat-schedule-net:".concat(o,"(").concat(a,"(").concat(s,"->").concat(c,")->").concat(m.join("->"),") ").concat(r),userId:t}),i=$b(Xb({},i),{totalCost:o,local:a,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(n){qO.error("getScheduleDetailCost error",n)}return i}(Number(r),t,p);return mW=m,{isCached:!1,result:m,detailCost:f}}catch(QO){let t=GD(QO)?QO[0]:QO,r=HD(t.code)?t.code:0,i="schedule failed".concat(t.message?": ".concat(t.message):""),o=new pw({code:uw.SCHEDULE_FAILED,extraCode:r,message:sL({key:iL.JOIN_ROOM_FAILED,data:{error:i,code:r}})});throw qO.error(i,r),o}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(BC).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),WO.on("28",(()=>_W(!0))),WO.on("63",(()=>_W(!0))),WO.on("84",(()=>_W(!0))),WO.on("201",(e=>{"RECONNECTING"===e.state&&_W(!0)})),WO.on("202",(e=>{"RECONNECTING"===e.state&&_W(!0)}));var EW={main:"",backup:""};function vW(e){GD(e)?(EW.main=e[0],EW.backup=e[1]):EW.main=e}var yW=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(yW||{});function TW(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$w.MAIN,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(EW[r]||AW(e,r,i),"/api/v1/").concat(t)}function IW(e,t,r){let i=TW(e,t),o=TW(e,t,$w.BACKUP),n=new URLSearchParams(r).toString(),a=fetch("".concat(i,"?").concat(n)).then((e=>e.json())),s=fetch("".concat(o,"?").concat(n)).then((e=>e.json()));return QD([a,s])}function AW(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$w.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=yD(e)?i?r===$w.MAIN?BC.MAIN_OVERSEA_BACKUP:BC.BACKUP_OVERSEA:r===$w.MAIN?BC.MAIN_OVERSEA:BC.BACKUP_OVERSEA:r===$w.MAIN?BC.MAIN:BC.BACKUP,t}function SW(e,t,r){return new Promise(((i,o)=>{xN({url:e,body:t,timeout:r.timeout,priority:"high"}).then((e=>{0===e.data.code?i(e.data.data):o({code:e.data.code,message:e.data.msg})})).catch(o)}))}var RW=(e,t)=>WN({retryFunction:SW,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var bW=class{constructor(){rw(this,"_log"),this._log=qO.createLogger({id:"fd"})}download(e,t){return ow(this,null,(function*(){let{type:r="blob"}=t||{};e=TN(e);try{let t,i=ZD();if(t=VD(fetch)?yield this.downloadWithFetch(e,r):yield this.downloadWithXHR(e,r),!t||!t.data)throw new Error("data is empty");let o=ZD()-i;return this._log.info("downloaded: ".concat(e,", return type: ").concat(r,", cost: ").concat(o,"ms")),EL.addSuccessEvent({key:522700,cost:ZD()-i}),t.data}catch(iM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(iM)),EL.addFailedEvent({key:522700,error:iM}),iM}}))}downloadWithFetch(e,t){return ow(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let r,i=yield fetch(e);if(!i.ok){let e=new Error("network response was not ok: ".concat(i.status));throw e.status=i.status,e}return r="arraybuffer"===t?yield i.arrayBuffer():yield i.blob(),{data:r}}catch(RC){throw RC}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((r,i)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType=t,o.onload=()=>{if(200===o.status||0===o.status&&o.response)r({data:o.response});else{let e=new Error("XHR failed, status: ".concat(o.status));e.status=o.status,i(e)}},o.onerror=i,o.send(null)}))}loadWasm(e,t){return ow(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let r=ZD(),i=null,o=null;if(VD(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&VD(fetch))try{let r=fetch(e);i=(yield WebAssembly.instantiateStreaming(r,t)).instance}catch(Sw){o=Sw}if(!i)try{let r=yield this.download(e,{type:"arraybuffer"});i=(yield WebAssembly.instantiate(r,t)).instance}catch(Sw){o=Sw}if(i){let t=ZD()-r;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),EL.addSuccessEvent({key:522701,cost:t}),i}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(o)),EL.addFailedEvent({key:522701,error:o}),o}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=ZD();return new Promise(((r,i)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(ZD()-t,"ms")),EL.addSuccessEvent({key:522702,cost:ZD()-t,split:1e3}),r(o)},o.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),EL.addFailedEvent({key:522702}),i(t)},o.crossOrigin="anonymous",o.src=e,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)}))}};tw([JP({settings:{timeout:0,retries:3},onError(e,t,r){var i;404===(null==e?void 0:e.status)||null!=(i=null==e?void 0:e.message)&&i.includes("404")?(this._log.warn("download 404, stop retry"),r(e)):t()},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],bW.prototype,"download",1),tw([JP({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],bW.prototype,"loadScript",1);var wW=new bW;function CW(e){var t=this;let{TRTC:r,room:i,errorModule:o,assetsPath:n}=e;return{TRTC:r,LocalMixVideoTrack:wB,LocalVideoTrack:eB,LocalScreenTrack:NB,room:i,assetsPath:n,fileDownloader:wW,innerEmitter:WO,INNER_EVENT:GO,constants:vw,environment:GN,utils:tB,eventLogger:qP,log:this.room.getLogger(),loggerManager:qO,errorModule:o,kvStatManager:EL,rtcDectection:XO,trtc:this,rx:CU,enums:$O,schedule:pW,getDevices:Zx,initVisionTaskRegistry:function(e){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"/mediapipe/vision.js";return ow(t,null,(function*(){window.VisionTaskRegistry||(yield wW.loadScript("".concat(e,"/").concat(r).replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels([window.VisionTaskType.ImageSegmenter])}))},audioContext:Px(),deviceDetector:$x,AudioPlayer:cU,AutoPlayDialog:vx,Timer:HP,clearStarted:(e,t)=>{let r=e.getAlias(),i=nW.instances.get(this);if(i)if(t){let e=i.get(r+t);if(!e)return;e.started=!1}else i.forEach(((e,t)=>{t.startsWith(r)&&(e.started=!1)}))},startGetPCM:MB,createAudioNode:Wx,getNetworkTimeOffset:mw,validateSourceNode:()=>{var e;if(ak&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new VH({code:MH.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var DW=new WeakMap;var NW="5.13.2-wasm.5";function kW(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return yU(((e,r)=>function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];try{MW.call(this,t,o,r,this._name)}catch(iM){return Promise.reject(iM)}return e.apply(this,o)}))}function OW(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return yU(((e,r)=>function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];try{MW.call(this,t,o,r,this._name)}catch(iM){throw iM}return e.apply(this,o)}))}function MW(e,t,r,i){if(GD(e))for(let o=0;o<e.length;o++)LW.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:r,className:i});else LW.call(this,{rule:e,value:t[0],key:e.name,fnName:r,className:i})}function LW(e){let{rule:t,value:r,key:i,fnName:o,className:n}=e;function a(e){return{code:MH.INVALID_PARAMETER,extraCode:e,fnName:o,messageParams:{key:i,rule:t,value:r}}}if(FD(r)){if(t.required)throw new VH(a(5001));if(FD(t.defaultValue))return void(VD(t.validate)&&t.validate.call(this,r,i,o,n,this));r=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let i=0;i<t.type.length;i++)null===t.type[i]&&null===r&&(e=!0),VD(t.type[i])&&r instanceof t.type[i]&&(e=!0),BD(t.type[i])&&UD(r)===t.type[i].toLowerCase()&&(e=!0);if(!e)throw new VH({code:MH.INVALID_PARAMETER,extraCode:5002,fnName:o,messageParams:{key:i,rule:{type:t.type.map((e=>YD(e)?JD(e):BD(e)?e:UD(e)))},value:r}})}else if(!FD(t.type)&&UD(r)!==t.type)throw new VH(a(5002));if(!1===t.allowEmpty){let e=HD(r)&&(0===r||Number.isNaN(r)),t=BD(r)&&""===r.trim();if(e||t)throw new VH(a(5003))}if(t.notLessThanZero&&HD(r)&&r<0)throw new VH(a(5006));if(!FD(t.min)&&HD(r)&&r<t.min)throw new VH(a(5007));if(!FD(t.max)&&HD(r)&&r>t.max)throw new VH(a(5008));if(BD(t.instanceOf)){if(!r||r._name!==t.instanceOf)throw new VH(a(5004))}else if(VD(t.instanceOf)&&!(r instanceof t.instanceOf))throw new VH(a(5004));if(Array.isArray(t.values)&&!t.values.includes(r))throw new VH(a(5005));let{properties:s}=t;LD(s)&&jD(r)&&Object.keys(s).forEach((e=>{LW.call(this,{rule:s[e],value:r&&r[e],key:"".concat(e),fnName:o,className:n})}));let{arrayItem:c}=t;LD(c)&&GD(r)&&r.forEach(((e,t)=>{LW.call(this,{rule:c,value:e,key:"".concat(i,"[").concat(t,"]"),fnName:o,className:n})})),VD(t.validate)&&t.validate.call(this,r,i,o,n,this)}function PW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:r,getKVReportKey:i,ignoreLog:o,ignoreErrorLog:n}=e;return yU(((e,a)=>function(){for(var s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];var d,u,h;function p(e,t,i){if(i&&i.includes(e))return"hided";if(r){let e=r(...c);if(c[e.argIndex]===t)return e.value}if(t===c||e in c)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(UD(t)):t instanceof MediaStreamTrack?IN(t):(JSON.stringify(t),t)}catch(o){return"type:".concat(UD(t))}}let m=this._log||qO;if(null!=o&&o(...c))return e.apply(this,c);c.length>0?m.info("".concat(a,"() ").concat(JSON.stringify(c,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(a,"()"));let f=i?i(...c):uL[a],_=(null==n?void 0:n(...c))||!1;try{let r=e.apply(this,c),i=ZD();if(qD(r)){let e="".concat(a.includes("Plugin")?"".concat((null==(u=(d=c[0]).getName)?void 0:u.call(d))||""," "):" ");return r.then((r=>(m.info("".concat(a,"() success ").concat(e).concat(t.call(this,...c))),EL.addSuccessEvent({key:f,cost:ZD()-i}),r))).catch((r=>{var i;let o=(r=VH.convertFrom.call(this,r,a,1===c.length?c[0]:c)).extraCode||r.code,n=null!=(i=r.message)&&i.includes(o)?"":" code:".concat(o);throw _||m.error("".concat(a,"() failed ").concat(e).concat(t.call(this,...c)," ").concat(r).concat(n," params: ").concat(JSON.stringify(c,p))),EL.addFailedEvent({key:f,error:r}),r}))}return EL.addSuccessEvent({key:f}),r}catch(sM){let t=(sM=VH.convertFrom.call(this,sM,a)).extraCode||sM.code,r=null!=(h=sM.message)&&h.includes(t)?"":" code:".concat(t);throw _||m.error("".concat(a,"() failed ").concat(sM).concat(r," params: ").concat(JSON.stringify(c,p))),EL.addFailedEvent({key:f,error:sM}),sM}}))}var xW,UW=e=>yU(((t,r)=>function(i,o){return ow(this,null,(function*(){let n=this._plugins.get(i);if(!n)throw this._log.error("plugin ".concat(String(i)," is not found")),new VH({code:MH.OPERATION_ABORT,message:"plugin ".concat(String(i)," is not found"),fnName:r});if(VD(n.constructor.isSupported)&&!n.constructor.isSupported())throw this._log.error("plugin ".concat(String(i)," is not supported")),new VH({code:MH.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(i)," is not supported"),extraCode:5210,fnName:r});return MW.call(this,n.getValidateRule(e),[o],r,"TRTC"),t.call(this,n,o)}))})),VW=0,FW=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"customAudioReferenceMap",new Map),rw(this,"audioRefId",0),rw(this,"audioContext",Px()),rw(this,"localAudioWorkletNode"),rw(this,"screenAudioWorkletNode"),rw(this,"mixNode"),rw(this,"silentNode"),VW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(VW)}),this.log.info("created id=".concat(this.getAlias()).concat(VW)),this.installEvent()}static getStartValidateRule(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,r,i,o){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new VH({code:MH.INVALID_OPERATION,extraCode:5106,fnName:i})}}}preload(e){return xW||(xW=this.doPreload(e)),xW}doPreload(e){return ow(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),r=URL.createObjectURL(t);try{yield Tx(this.audioContext,r)}catch(iM){this.log.error("preload audioProcessor failed. ".concat(iM))}finally{URL.revokeObjectURL(r)}}))}getName(){return e.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return e.getStartValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return ow(this,null,(function*(){var t,r,i,o;let{room:n}=this.core,{sdkAppId:a,userId:s,userSig:c,assetsPath:l=this.core.assetsPath,audioReference:d,processLevel:u,enableDump:h,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:m=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!l)throw new VH({code:MH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(l,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:r}=yield this.getAuthData(a,s,c);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",a,s,r,e,t,n)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:r}=yield this.getAuthData(a,s,c);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",a,s,r,e,t,n)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"enable"}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"enable"}),n.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),FD(d)||d.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})})),FD(u)||null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),FD(h)||null==(o=this.localAudioWorkletNode)||o.port.postMessage({type:"dump",data:{enable:h}})}))}update(e){return ow(this,null,(function*(){var t,r,i;let{audioReference:o,enableDump:n,processLevel:a}=e;FD(o)||(this.customAudioReferenceMap.forEach(((e,t)=>{this.customAudioReferenceMap.delete(t),this.core.room.audioManager.updateAudioReference({type:"remove",refId:e})})),o.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})}))),FD(a)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),FD(n)||(null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:n}}),null==(i=this.screenAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:n}}))}))}stop(){return ow(this,null,(function*(){var e,t;let{room:r}=this.core;null==(e=this.localAudioWorkletNode)||e.port.postMessage({type:"disable"}),null==(t=this.screenAudioWorkletNode)||t.port.postMessage({type:"disable"}),yield r.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)}))}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,t,r){return ow(this,null,(function*(){let i=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:s}=yield function(e){return ow(this,arguments,(function(e){let{sdkAppId:t,userId:r,userSig:i,timestamp:o}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$w.MAIN;return"https://".concat(EW[t]||AW(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(r,"&userSig=").concat(i,"&timestamp=").concat(o),n=yield fetch(e),{data:{errCode:a,errMsg:s,sign:c,status:l}}=yield n.json();if("1"===l)return{auth:!0,sign:c,status:l,message:s};let d=yD(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",u="Init RTCAudioProcessor failed.",h="";switch(a){case 1:h="Please check your params.";break;case 2:h="You need to buy packages. Refer to: ".concat(d);break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h="Your packages is not active. Refer to: ".concat(d);break;case 5:h="Your packages is expired. Refer to: ".concat(d);break;case 6:h="Your version is not supported."}return{auth:!1,status:l,message:s?"".concat(u," Reason: ").concat(s,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}({sdkAppId:e,userSig:r,userId:t,timestamp:i});if(!o)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(o,". Message: ").concat(s)),new VH({code:MH.INVALID_PARAMETER,message:s});return{sign:n,status:a,timestamp:i}}))}initWorkletNode(e,t,r,i,o,n,a,s){e.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:i,timestamp:o,sign:n,status:a}}),e.port.onmessage=e=>{var r;let{data:i}=e;switch(i.type){case"cost":let e=(null==i?void 0:i.value)>10?"info":"debug";return void this.log[e]("".concat("localAudio"===t?"":"[".concat(t,"] "),"avg cost: ").concat(i.value," max: ").concat(null==i?void 0:i.max,"(").concat(gw(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(r=null==i?void 0:i.hist)?void 0:r.join(" ")));case"log":return void this.log[i.logLevel]("".concat("localAudio"===t?"":"[".concat(t,"] ")).concat(i.value));case"dump":return void WO.emit("265",{room:s,data:i.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(e){return ow(this,null,(function*(){var t;if(this.hitTest(e.room)&&!0===(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(RC){this.log.warn("audio processor auto start failed, error: ".concat(RC))}}))}handleLocalAudioStopped(e){return ow(this,null,(function*(){var t;!this.hitTest(e.room)||!0!==(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor)||(yield this.core.trtc.stopPlugin("AudioProcessor"))}))}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(e){return e===this.core.room}};rw(FW,"updateValidateRule",{type:"object"}),rw(FW,"stopValidateRule",{type:"object"}),rw(FW,"Name","AudioProcessor");var BW=FW;var HW=0,WW=class{constructor(e,t){rw(this,"audioObjectURL"),rw(this,"player"),rw(this,"publisher"),rw(this,"mixInput"),this.mixInput=new Fx(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()}updateSettings(e){this.player&&(FD(e.volume)||(this.volume=e.volume),FD(e.loop)||(this.loop=e.loop),FD(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{t(r.currentTime,r.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reload(e){return ow(this,null,(function*(){if(e.url){let t=yield wW.download(e.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(e),this.updateSettings(e))}else this.mixInput.replaceSource(e.track)}))}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 Promise.all([null==(e=this.player)?void 0:e.play(),null==(t=this.publisher)?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)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function jW(e,t){if(t&&"function"!=typeof t)throw new VH({code:MH.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var GW=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"mixedMusicMap",new Map),rw(this,"cacheMusicMap",new Map),HW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(HW)}),this.log.info("created id=".concat(this.getAlias()).concat(HW))}getName(){return e.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(t){switch(t){case"start":return e.startValidateRule;case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return ow(this,null,(function*(){let{room:t}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:r,url:i}=e;if(this.mixedMusicMap.has(r))return;let o=this.cacheMusicMap.get(r);o?e.url?o.reset():(o.mixInput.replaceSource(e.track),o.mixInput.connect()):(o=new WW(e,t.audioManager),this.cacheMusicMap.set(r,o)),o.updateListener(e),o.updateSettings(e);try{yield o.play()}catch(Sw){yield this.handleAutoPlayFailed(o,e,Sw)}this.mixedMusicMap.set(r,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:"ax-".concat(r)}),this.log.info("start mix audio track ".concat(r," success.")),EL.addEnum({key:502700,value:3}),this.kvUpload(e)}))}handleAutoPlayFailed(e,t,r){return ow(this,null,(function*(){if("NotSupportedError"===r.name)this.log.error("play failed, try to reload source. error: ".concat(r)),yield e.reload(t),yield e.play();else{if("NotAllowedError"!==r.name)throw r;if(this.core.room.enableAutoPlayDialog){let t=()=>{var r;null==(r=e.play())||r.finally((()=>{WO.off("154",t,this)}))};WO.on("154",t,this),new vx}else this.core.trtc.emit(uW.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>ow(this,null,(function*(){return e.play()}))})}}))}update(e){return ow(this,null,(function*(){let{id:t,operation:r,seekFrom:i,playbackRate:o}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let n=this.mixedMusicMap.get(t);n?(n.updateSettings(e),n.updateListener(e),FD(r)||n.setOperation(r),FD(i)||n.seek(i),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return ow(this,arguments,(function(e){var t=this;let{id:r}=e;return function*(){if(t.mixedMusicMap.has(r)){t.log.info("remove music source, music id: ".concat(r));let e=t.mixedMusicMap.get(r);null!=e&&e.mixInput.source.node&&t.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.source.node,refId:"ax-".concat(r)}),null==e||e.stop(),t.mixedMusicMap.delete(r)}"*"===r&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:r,volume:i,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:s,onDurationChange:c,onEnded:l}=e;t&&EL.addCount({key:502009}),r&&EL.addCount({key:502001}),i&&EL.addCount({key:502002}),o&&EL.addCount({key:502003}),n&&EL.addCount({key:502004}),a&&EL.addCount({key:502005}),"function"!=typeof s&&EL.addCount({key:502007}),"function"!=typeof l&&EL.addCount({key:502008}),"function"!=typeof c&&EL.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{null!=e&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId: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()}};rw(GW,"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,r){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],i=["mp3","ogg","wav","flac"],o=t.split(".").pop(),n=i.indexOf(o)>=0,a=t.startsWith("blob"),s=t.startsWith("data");if(!(n||a||s))throw new VH({code:MH.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!e.url&&!e.track)throw new VH({code:MH.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});jW("onTimeUpdate",e.onTimeUpdate),jW("onEnded",e.onEnded),jW("onDurationChange",e.onDurationChange)}}),rw(GW,"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"]}},validate(e,t,r){jW("onTimeUpdate",e.onTimeUpdate),jW("onEnded",e.onEnded),jW("onDurationChange",e.onDurationChange)}}),rw(GW,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),rw(GW,"Name","AudioMixer");var zW,KW=GW,qW=0,YW=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"audioContext",Px()),rw(this,"workletNode"),rw(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),qW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(qW)}),this.log.info("created id=".concat(this.getAlias()).concat(qW))}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(t,r,i,o){if(!e.room.audioManager.hasAudioTrack)throw new VH({code:MH.INVALID_OPERATION,extraCode:5106,fnName:i})}}}preload(e){return zW||(zW=this.doPreload(e)),zW}doPreload(e){return ow(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),r=URL.createObjectURL(t);try{yield Tx(this.audioContext,r)}catch(iM){throw this.log.error("load worklet failed",iM),iM}finally{URL.revokeObjectURL(r)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return ow(this,null,(function*(){let{room:t,schedule:r}=this.core,{assetsPath:i=this.core.assetsPath}=e;if(!i)throw new VH({code:MH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(i,"/denoiser-wasm").concat(pP()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:o,status:n,message:a}=yield function(e,t){return ow(this,arguments,(function(e,t){let{sdkAppId:r,userId:i,userSig:n,timestamp:a}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:s,status:c}}=yield e.getAbilityConfig(r,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:r,userId:i,userSig:n,timestamp:a});if("1"===c)return{auth:!0,sign:s,status:c,message:o};let l=yD(r)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",d="Init RTCAIDenoiser failed.",u="";switch(t){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: ".concat(l);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(l);break;case 5:u="Your packages is expired. Refer to: ".concat(l);break;case 6:u="Your version is not supported."}return{auth:!1,status:c,message:o?"".concat(d," Reason: ").concat(o,". ").concat(u):"".concat(d,", ").concat(u)}}catch(o){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(o)}}}()}))}(r,$b(Xb({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(a)),new VH({code:MH.INVALID_PARAMETER,message:a});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:o,status:n}}),this.workletNode.port.onmessage=e=>{var t;let{data:r}=e;if("cost"===r.type){let e=(null==r?void 0:r.max)>20?"warn":(null==r?void 0:r.max)>10?"info":"debug";this.log[e]("avg cost: ".concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(gw(new Date(null==r?void 0:r.maxCostTimestamp)),") hist: ").concat(null==(t=null==r?void 0:r.hist)?void 0:t.join(" ")))}else"log"===r.type&&this.log[r.logLevel]("".concat(r.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(e){return ow(this,null,(function*(){this.updateConfig(e)}))}stop(){return ow(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}updateConfig(e){if(!this.workletNode)return;let t=!1;FD(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),FD(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,t=!0),t&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};rw(YW,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),rw(YW,"stopValidateRule",{type:"object"}),rw(YW,"Name","AIDenoiser");var JW=YW;var XW=ew(nw(),1),$W=class extends XW.EventEmitter{constructor(){super(),rw(this,"observer"),rw(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return ow(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!rk&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Aw){qP.uploadEvent({log:"stat-pressure-detector-start-failed",error:Aw})}}))}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&qO.info("".concat(r.source,": ").concat(r.state)),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(RC){qP.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:RC})}}},QW=new $W;function ZW(e){let[t,r]=e,i=r.byteLength,o=parseInt(String(i/255),10),n=i%255,a=[];a.push(0,0,0,1,6,t);for(let c=0;c<o;c++)a.push(255);a.push(n);let s=new DataView(r);return a.push(...new Uint8Array(s.buffer)),a.push(128),new $F(new DataView(new Uint8Array(a).buffer),!0)}function ej(e){let{frame:t,seiMessageList:r}=e;if(!r||0===r.length||0===t.data.byteLength)return t;let i=9-function(e){let t=0,r=0,i=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(i.getUint8(o)){case 0:t++;break;case 1:(2===t||3===t)&&r++,t=0;break;default:t=0}return r}(t.data);if(i<=0)return t;let o=r.splice(0,i).reverse().map(ZW),n=o.reduce(((e,t)=>e+t.dataView.byteLength),0),a=new ArrayBuffer(n+t.data.byteLength),s=new DataView(a),c=new DataView(t.data),l=0;for(let d=0;d<o.length;d++)for(let e=0;e<o[d].dataView.byteLength;e++)s.setInt8(l++,o[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)s.setInt8(l++,c.getInt8(d));return t.data=a,t}function tj(e){let{frame:t,onSEI:r}=e;try{let e=new DataView(t.data);if(function(e){return"empty"===e.type||0===e.data.byteLength}(t)||!function(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}(e))return t;let i=[],o=0,n=-1,a=-1;for(let r=0;r<t.data.byteLength;r++){let s=e.getUint8(r);if(0===s)o++;else if(1===s){if(2===o||3===o){let s=r-o;if(-1===n?n=s:-1===a&&(a=s,i.push(new $F(new DataView(e.buffer.slice(n,a)))),n=s,a=-1),6!==e.getUint8(r+1)){t.data=e.buffer.slice(s);break}}o=0}else o=0}null==r||r(i.reverse())}catch(Aw){}return t}var rj=0,ij=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_subStreamSeiMessageList",[]),rj++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(rj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(rj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:r}=e;try{return ej({frame:t,seiMessageList:8===r?this._smallSeiMessageList:2===r?this._subStreamSeiMessageList:this._seiMessageList})}catch(RC){this.log.warn(RC)}return t}decode(e){let{frame:t,track:r}=e;return tj({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(uW.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:r.userId,streamType:2===r.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:aP?this.encode:ej,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:aP?this.decode:tj,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:t,options:r}=e;var i;let o=[r.seiPayloadType,t],n=!!r.small;r.toSubStream?this._subStreamSeiMessageList.push(o):(this._seiMessageList.push(o),n&&this._smallSeiMessageList.push(o)),null==(i=this.core.room.scriptTransformWorker)||i.postMessage({type:"sei",data:o,isMain:!r.toSubStream,small:n})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};rw(ij,"autoStart",!0),rw(ij,"Name","SEI");var oj=ij;function nj(e){let{frame:t,onDump:r}=e;return null==r||r(),t}function aj(e){let{frame:t,onDump:r}=e;return null==r||r(),t}var sj={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{sj["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var cj,lj=0,dj=class e{constructor(e){this.core=e,rw(this,"_core"),rw(this,"log"),rw(this,"dumpLocalVideoMap",{}),rw(this,"dumpRemoteVideoMap",{}),rw(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++lj)}),this.log.info("created")}getName(){return e.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return ow(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(e){return ow(this,arguments,(function(e){var t=this;let{visible:r}=e;return function*(){r?(yield t.openDebugDiaLog(),t.addVideoProcessor()):(t.closeDebugDiaLog(),t.removeVideoProcessor())}()}))}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return ow(this,null,(function*(){var e;if(!this.dialog)try{if(cj)yield cj;else{let t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(Tw,"/assets/debug-dialog.js");cj=this._core.fileDownloader.loadScript(t),yield cj}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(Aw){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Aw))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):nj,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):aj,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:r}=e;return nj({frame:t,onDump:()=>{if(!r)return;let e=2===r?"sub":"main",i=this.dumpLocalVideoMap[e];i&&(i.data.push(t.data.slice(0)),i.duration>0&&Date.now()-i.startTimestamp>1e3*i.duration&&i.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:r}=e;return aj({frame:t,onDump:()=>{if(!r)return;let e=this.dumpRemoteVideoMap["".concat(r.userId,"-").concat(r.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}};rw(dj,"Name","Debug"),rw(dj,"autoStart",!0);var uj=dj,hj=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},pj=class{constructor(e,t,r){rw(this,"trackDoneOB"),rw(this,"startOB"),rw(this,"stopOB"),rw(this,"inputFrameCount",0),rw(this,"decodedFrameCount",0),rw(this,"type","auto"),rw(this,"config"),rw(this,"decoder"),rw(this,"_decodeSink");let{kvStatManager:i,trtc:o}=e;this.config=r.config,this.trackDoneOB=vV(t,PP.INIT),this.stopOB=aV(),this.startOB=aV(),"auto"===r.type?this.type="webCodecs":this.type=r.type;let n=aV();FU(this.startOB,tV(0),EF((e=>{let r=this.pipe(t);return n.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),FU(r,HV(this.stopOB),WF((()=>{}),(r=>{t.log.error(r),i.addFailedEvent({key:hj(this.type),error:r}),e>4?this.startOB.error(r):this.startOB.next(e+1)}))),FU(r,BV(1),UF(kV))})),HV(this.stopOB),WF((()=>{t.player.setOutput(),n.next("STARTED")}),(e=>{n.next("FAILED")}),(()=>{i.addSuccessEvent({key:hj(this.type)}),i.addSuccessEvent({key:504702})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return qU()((t=>ow(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e;null==(e=this.decoder)||e.close()}));let{type:r}=this;try{if("webCodecs"===r)this.decoder=new AudioDecoder({error:r=>{e.log.error(r),t.error(4)},output:r=>{this.decodedFrameCount++,t.next(r),e.player.write(r)}});this.decoder.configure(this.config)}catch(iM){e.log.error(iM),t.error("webCodecs"===r?2:6)}}))))}decodeFrame(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},mj={type:"object"},fj=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"contextMap",new Map),rw(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return e.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return e.Name}getValidateRule(e){return mj}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:r}=e;return this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t},type:3})}decode(e){return t=>{let{frame:r,track:i}=t;if(i!==e.track)return r;if(this.contextMap.has(i))return this.contextMap.get(i).decodeFrame(r);let o=new pj(this.core,i,e);return FU(o.trackDoneOB,BV(1),WF((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:i})}))),this.contextMap.set(i,o),o.decodeFrame(r)}}stop(e){let{track:t}=e,r=this.contextMap.get(t);r&&(r.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new pj(this.core,e.track,e))}}};rw(fj,"Name","TRTCAudioDecoder");var _j=fj,gj=class{constructor(){rw(this,"log"),this.log=qO.createLogger({id:"exp"})}call(e,t){return ow(this,null,(function*(){return VD(this[e])?this[e](t):Promise.reject(new pw({code:uw.INVALID_PARAMETER,message:sL({key:iL.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return ow(this,null,(function*(){let{trtcInstance:t,enable:r,userId:i,sampleRate:o=48e3,channelCount:n=1,port:a}=e,{audioManager:s}=t.room,{getPCMAbortCtrlMap:c,audioFrameEventConfigMap:l}=s;if(l.set(i,{enable:r,sampleRate:o,channelCount:n,port:a}),r)if("*"===i)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(c.get(e.userId))return;let r=s.getPCM((e=>{t.emit(uW.AUDIO_FRAME,e)}),e.userId);c.set(e.userId,r)}}));else{if(c.get(i))return;let e=s.getPCM((e=>{t.emit(uW.AUDIO_FRAME,e)}),i);c.set(i,e)}else if("*"===i)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,r=c.get(t);null==r||r.abort("disable"),c.delete(t)}}));else{let e=c.get(i);null==e||e.abort("disable"),c.delete(i)}}))}resumeRemotePlayer(e){return ow(this,null,(function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach((r=>{let{remoteAudioTrack:i,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=r;e.streamType?"main"===e.streamType?(i.isAvailable&&t.push(i.player.resume()),o.isAvailable&&t.push(o.player.resume())):n.isAvailable&&t.push(n.player.resume()):(i.isAvailable&&t.push(i.player.resume()),o.isAvailable&&t.push(o.player.resume()),n.isAvailable&&t.push(n.player.resume()))})),Promise.all(t)}let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);if(t)return"main"===e.streamType?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()}))}pauseRemotePlayer(e){if("*"===e.userId)e.trtcInstance.room.remotePublishedUserMap.forEach((t=>{let{remoteAudioTrack:r,remoteVideoTrack:i,remoteAuxiliaryTrack:o}=t;e.streamType?"main"===e.streamType?(r.isAvailable&&r.player.pause(),i.isAvailable&&i.player.pause()):o.isAvailable&&o.player.pause():(r.isAvailable&&r.player.pause(),i.isAvailable&&i.player.pause(),o.isAvailable&&o.player.pause())}));else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause()):t.remoteAuxiliaryTrack.player.pause())}}};tw([function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return yU(((e,r)=>function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];return jB.call(this,t,o,r,this._name),e.apply(this,o)}))}({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],gj.prototype,"enableAudioFrameEvent",1);var Ej=new gj,vj=ew(nw(),1),yj=class extends vj.EventEmitter{constructor(){super(),rw(this,"states",{}),rw(this,"permissionChangeHandler"),rw(this,"log"),this.log=qO.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:null==(e=this.states.camera)?void 0:e.state,microphone:null==(t=this.states.microphone)?void 0:t.state})}}request(e){return ow(this,null,(function*(){if(this.log.info("request ".concat(e.join(", "))),0===e.length)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach((e=>e.stop()))}))}get(e){return ow(this,null,(function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(e," permission state: ").concat(this.states[e].state)),this.states[e].state}catch(RC){return this.log.error("get ".concat(e," permission failed, error: ").concat(RC instanceof Error?RC.message:RC)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},Tj=new yj,Ij=0,Aj=new Set,Sj=null;Iw(NW),JO.checkStorage();var Rj=class e extends CH.EventEmitter{constructor(t,r){super(),rw(this,"_room"),rw(this,"_eventListened",new Set),rw(this,"_localVideoTrack",null),rw(this,"_localAudioTrack",null),rw(this,"_localScreenTrack",null),rw(this,"_localScreenAudioTrack",null),rw(this,"_localVideoConfig",null),rw(this,"_localScreenConfig",null),rw(this,"_localAudioConfig",null),rw(this,"_remoteVideoConfigMap",new Map),rw(this,"_remoteAudioConfigMap",new Map),rw(this,"_remoteAudioVolumeMap",new Map),rw(this,"_remoteAudioMuteMap",new Map),rw(this,"_mediaTrackMap",new WeakMap),rw(this,"_log",qO.createLogger({id:"t".concat(++Ij)})),rw(this,"_plugins",new Map),rw(this,"_networkQuality",null),rw(this,"_speakerId"),rw(this,"enterRoomParams"),rw(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(Xb({logger:this._log,frameWorkType:e.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,WD(r.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=r.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(r,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),r.plugins&&r.plugins.forEach((e=>{this._use(e,r.assetsPath)})),this._use(KW,r.assetsPath),this._use(BW,r.assetsPath),this._use(JW,r.assetsPath),this._use(_j,r.assetsPath),this._use(uj),r.enableSEI&&cP&&this._use(oj),this._room.on("audio-volume",(e=>{var t,i;!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*(null!=(t=this._localAudioTrack.getInternalAudioLevelAfter3A())?t:this._localAudioTrack.getAudioLevel())),floatVolume:null!=(i=this._localAudioTrack.getInternalAudioLevelAfter3A())?i:this._localAudioTrack.getInternalAudioLevel()}),1===r.volumeType&&e.forEach((e=>{var t;let r=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;r&&(e.volume=r.dbVolume)})),r.enableDbVolume&&e.forEach((e=>{var t;let r=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;r&&(e.volume=r.dbVolume)})),this.emit(uW.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new VH({code:MH.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:r}=e;e.emit=function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];try{return r.apply(e,o)}catch(iM){let r=sL({key:iL.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return qO.warn("".concat(r,"\n\n").concat(iM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,r){!function(){var e;if(kH){kH=!1,5!==qO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Lw,"/en/index.html")),console.info("* Changelog: ".concat(Lw,"/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:",Tw),AO||qO.debug("Build Time:","2025-10-20 16:39:40");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(kO()),r=navigator.deviceMemory;r&&(t+=", minRAM: ".concat(r,"GB")),qO.info(t),qO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),NO().then((e=>{e&&qO.info(DO)}))}}();let i=new e(t,r||{});return Aj.add(i),i.__v_skip=!0,i}get room(){return this._room}_listenEvents(){zP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(uW.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(uW.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(uW.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(uW.ERROR,VH.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(uW.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=$b(Xb({},e),{uplinkRTT:Math.min(e.uplinkRTT,QC),downlinkRTT:Math.min(e.downlinkRTT,QC)});this.emit(uW.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{zP(t,t).add("player-state-changed",(r=>{let i=$b(Xb({},r),{userId:e.userId});t.kind===$w.VIDEO&&(i.streamType=FH(t.streamType)),this.emit(t.kind===$w.AUDIO?uW.AUDIO_PLAY_STATE_CHANGED:uW.VIDEO_PLAY_STATE_CHANGED,i)})).add("error",(e=>{e.getCode()===uw.PLAY_NOT_ALLOWED&&this.emit(uW.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{KP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:r}=e,{userId:i}=r,o=t.audioAvailable,n=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=r;a||this._remoteAudioConfigMap.delete(i),s||this._removeRemoteVideoConfig(i,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(i,"sub"),n!==s&&(s?this._onVideoAvailable({userId:i,streamType:"main"}):this._onVideoUnavailable({userId:i,streamType:"main"}),this.emit(s?uW.REMOTE_VIDEO_AVAILABLE:uW.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:i}):this._onAudioUnavailable({userId:i,muteState:r}),this.emit(a?uW.REMOTE_AUDIO_AVAILABLE:uW.REMOTE_AUDIO_UNAVAILABLE,{userId:i})),t.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:i,streamType:"sub"}):this._onVideoUnavailable({userId:i,streamType:"sub"}),this.emit(r.hasAuxiliary?uW.REMOTE_VIDEO_AVAILABLE:uW.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(uW.SEI_MESSAGE,$b(Xb({},e),{streamType:FH(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(uW.ERROR,new VH({code:MH.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,r,i,o,n,a,s;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(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==(r=this._networkQuality)?void 0:r.uplinkRTT)||(null==(i=this._networkQuality)?void 0:i.downlinkRTT)||0,QC),upLoss:(null==(o=this._networkQuality)?void 0:o.uplinkLoss)||0,downLoss:(null==(n=this._networkQuality)?void 0:n.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_level)||0)/jM},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)/jM,point2pointDelay:(e.msg_audio_status.uint32_audio_p2p_delay||0)+(e.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:e.msg_audio_status.uint32_audio_cache_ms||0},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],point2pointDelay:(e.uint32_video_p2p_delay||0)+(e.uint32_video_cache_ms||0),jitterBufferDelay:e.uint32_video_cache_ms||0,codec:e.uint32_video_codec})))})))};this.emit(uW.STATISTICS,l)})).add("custom-message",(e=>{this.emit(uW.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(uW.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(uW.FIRST_VIDEO_FRAME,$b(Xb({},e),{streamType:FH(e.streamType)}))})).add("audio-frame",(e=>{this.emit(uW.AUDIO_FRAME,e)})),zP(this,$x).add("audioInputAdded",(e=>{this.emit(uW.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(uW.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(uW.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(uW.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>ow(this,null,(function*(){if(this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Sj&&Sj.deviceId===zC){let e=(yield iU()).find((e=>e.deviceId===zC));e&&Sj.groupId!==e.groupId&&(Sj=e,this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>ow(this,null,(function*(){this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield iU())[0];if(!t||!Sj||Sj.groupId===t.groupId)return;let r=Sj.deviceId===e.deviceId,i=Sj.deviceId===zC&&Sj.deviceId===t.deviceId;(r||i)&&(Sj=t,this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),zP(this,Tj).add("permission-state-change",(e=>{this.emit(uW.PERMISSION_STATE_CHANGE,e)}))}getNetworkTime(){return fw()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,"Chorus"===t.Name&&(this.room.enableChorus=!0),this._use(t,r)}_use(t,r){let i=this._plugins.get(t.Name);if(i)return this._log.warn("duplicate install plugin",t.Name),i;let o=new t(CW.call(this,{TRTC:e,room:this._room,assetsPath:r,errorModule:{RtcError:VH,ErrorCode:MH,CoreErrorCode:uw,ErrorCodeDictionary:LH}}));return this._plugins.set(t.Name,o),o.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),o}enterRoom(t){return ow(this,null,(function*(){var r,i;this.enterRoomParams=t;let{scene:o="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:a=!0,autoReceiveVideo:s=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!BD(t.proxy)&&t.proxy.turnServer&&(null==(i=(r=this._room).setTurnServer)||i.call(r,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=a,this._room.autoReceiveVideo=s,WD(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,o,e.frameWorkType),this._checkTrackToPublish(),QW.start()}))}exitRoom(){return ow(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return ow(this,null,(function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(RC){if(!(RC instanceof hw)||RC.code!==uw.API_CALL_TIMEOUT&&RC.code!==uw.SWITCH_ROOM_FAILED)throw RC;this._log.warn("switchRoom ".concat(RC.code===uw.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)}))}_rejoinRoom(e){return ow(this,null,(function*(){yield this.exitRoom();let t=Xb(Xb({},this.enterRoomParams),e);yield this.enterRoom(t)}))}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch((()=>{}))})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",r=e.split("_".concat(t))[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch((()=>{}))})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(e){let t=DW.get(e);t&&(t.forEach((e=>clearTimeout(e))),DW.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{KP(e.remoteAudioTrack),KP(e.remoteVideoTrack),KP(e.remoteAuxiliaryTrack)}))}switchRole(e,t){return ow(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)})),this._plugins.clear(),KP(this),this.removeAllListeners(),this._room.destroy(),Aj.delete(this),0===Aj.size&&QW.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),WO.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return ow(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:r=!0,mute:i,option:o}=t,n=new XF(e._room.audioManager),a={},s={muted:!0};o&&(FD(o.microphoneId)?FD(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&HD(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),FD(o.profile)||(BD(o.profile)?Kw[o.profile]&&n.setProfile(Kw[o.profile]):n.setProfile(o.profile)),HD(o.earMonitorVolume)&&(s.muted=!(o.earMonitorVolume>0),s.volume=o.earMonitorVolume),FD(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),FD(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),FD(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl),WD(e._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),n.on("5",(t=>{e.emit(uW.ERROR,new VH({code:MH.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(uW.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let r;t.error&&(r=VH.convertFrom(t.error)),e.emit(uW.PUBLISH_STATE_CHANGED,$b(Xb({},t),{error:r}))})),n.on("6",(()=>{e.emit(uW.ERROR,new VH({code:MH.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))})),e._listenOutputTrackChanged(n),e._speakerId&&n.setAudioOutput(e._speakerId),yield n.capture(a),FD(i)||n.setMute(i),zP(n,n).add("player-state-changed",(t=>{e.emit(uW.AUDIO_PLAY_STATE_CHANGED,$b(Xb({},t),{userId:""}))})),r&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=$b(Xb({},t),{publish:r}),yield e._updateAudioPlayOption({playOption:s,track:n}),WO.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return ow(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:i}=e,o={};i&&(i.microphoneId?yield this._localAudioTrack.switchDevice(i.microphoneId):FD(i.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(i.audioTrack)),FD(i.captureVolume)||this._localAudioTrack.setCaptureVolume(i.captureVolume),FD(i.earMonitorVolume)||(o.muted=!(i.earMonitorVolume>0),o.volume=i.earMonitorVolume),yield this._localAudioTrack.update3A(i)),this._room.isJoined&&!FD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),FD(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),sN(this._localAudioConfig,e)}))}stopLocalAudio(){return ow(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),WO.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),KP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return ow(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var r;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:o=!0,capture:n=!0,mute:a,option:s}=t,c=new eB(e._room.videoManager),l={},d={};s&&(WD(s.avoidCropping)&&(c.avoidCropping=s.avoidCropping),s.cameraId?l.deviceId=s.cameraId:FD(s.useFrontCamera)?FD(s.videoTrack)||(l.customSource=s.videoTrack):l.facingMode=s.useFrontCamera?$w.FACING_MODE_USER:$w.FACING_MODE_ENVIRONMENT,FD(s.retryWhenExactFailed)||(l.retryWhenExactFailed=s.retryWhenExactFailed),s.qosPreference&&(l.contentHint=BH(s.qosPreference)),FD(s.profile)||(BD(s.profile)?qw[s.profile]&&c.setProfile(qw[s.profile]):c.setProfile(s.profile)),FD(s.fillMode)||(d.objectFit=s.fillMode),FD(s.mirror)||(d.mirror=s.mirror),FD(s.small)||(FD(s.smallMode)||(e._room.smallMode=s.smallMode),WD(s.small)&&!1===s.small?c.stopSmall():c.updateSmallConfig(HH(s.small,!0))),FD(s.rotation)||c.setRotation(s.rotation),WD(e._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",(t=>{e.emit(uW.FIRST_VIDEO_FRAME,$b(Xb({},t),{streamType:FH(t.streamType)}))})),c.on("5",(t=>{e.emit(uW.ERROR,new VH({code:MH.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),c.on("2",(t=>{e.emit(uW.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),c.on("4",(t=>{let r;t.error&&(r=VH.convertFrom(t.error)),e.emit(uW.PUBLISH_STATE_CHANGED,$b(Xb({},t),{error:r}))})),c.on("6",(()=>{e.emit(uW.ERROR,new VH({code:MH.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))})),e._listenOutputTrackChanged(c),n?yield c.capture(l):null==(r=c.manager)||r.changeInput(c),FD(a)||(yield c.setMute(a)),zP(c,c).add("player-state-changed",(t=>{e.emit(uW.VIDEO_PLAY_STATE_CHANGED,$b(Xb({},t),{userId:"",streamType:"main"}))})).add("video-size-changed",(t=>{e.emit(uW.VIDEO_SIZE_CHANGED,$b(Xb({},t),{streamType:FH(t.streamType)}))})),o&&e._room.isJoined&&e._room.publish(c).catch((()=>{})),e._localVideoTrack=c,e._localVideoConfig=$b(Xb({},t),{view:i,publish:o,capture:n}),yield e._updateVideoPlayOption({view:i,playOption:d,track:c})}()}))}updateLocalVideo(e){return ow(this,null,(function*(){var t,r,i;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:o,publish:n,mute:a,capture:s,option:c}=e,l={};if(this._localVideoConfig.capture)!1!==s?null!=c&&c.cameraId?yield this._localVideoTrack.switchDevice(null==c?void 0:c.cameraId):FD(null==c?void 0:c.useFrontCamera)?FD(null==c?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==c?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(null!=c&&c.useFrontCamera?$w.FACING_MODE_USER:$w.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(s){let e={};e.deviceId=(null==c?void 0:c.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=c&&c.useFrontCamera||null!=(r=this._localVideoConfig.option)&&r.useFrontCamera?$w.FACING_MODE_USER:$w.FACING_MODE_ENVIRONMENT,e.customSource=(null==c?void 0:c.videoTrack)||(null==(i=this._localVideoConfig.option)?void 0:i.videoTrack),yield this._localVideoTrack.capture(e)}c&&(FD(c.profile)||(BD(c.profile)?qw[c.profile]&&this._localVideoTrack.setProfile(qw[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&FD(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),FD(c.fillMode)||(l.objectFit=c.fillMode),FD(c.mirror)||(l.mirror=c.mirror),FD(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(BH(c.qosPreference)),FD(c.small)||(WD(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(HH(c.small,!0)))),this._room.isJoined&&FD(n)&&this._localVideoConfig.publish&&s&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._room.isJoined&&((null!=n?n:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch((()=>{})):this._room.unpublish(this._localVideoTrack).catch((()=>{}))),FD(a)||(yield this._localVideoTrack.setMute(a)),yield this._updateVideoPlayOption({view:o,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),sN(this._localVideoConfig,e)}))}stopLocalVideo(){return ow(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),KP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return ow(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){var r,i;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:o=null,publish:n=!0,muteSystemAudio:a,option:s}=t,c=new NB(e._room.videoManager);c.on("4",(t=>{let r;t.error&&(r=VH.convertFrom(t.error)),e.emit(uW.PUBLISH_STATE_CHANGED,$b(Xb({},t),{error:r}))})),c.once("first-video-frame",(t=>{e.emit(uW.FIRST_VIDEO_FRAME,$b(Xb({},t),{streamType:FH(t.streamType)}))})),e._listenOutputTrackChanged(c),"main"===t.streamType&&(c.mediaType=4);let l=null,d={},u={};s&&(FD(s.profile)||(BD(s.profile)?Xw[s.profile]&&c.setProfile(Xw[s.profile]):c.setProfile(s.profile)),s.systemAudio&&(d.systemAudio=!0,d.echoCancellation=s.echoCancellation,d.noiseSuppression=s.noiseSuppression,d.autoGainControl=s.autoGainControl),FD(s.fillMode)||(u.objectFit=s.fillMode),s.videoTrack&&(d.videoTrack=s.videoTrack),s.audioTrack&&(d.audioTrack=s.audioTrack),s.captureElement&&(d.captureElement=s.captureElement),s.preferDisplaySurface&&(d.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(d.contentHint=BH(s.qosPreference)));let h=yield c.capture(d);if(c.mediaTrack.addEventListener($w.ENDED,(()=>{e._stopScreenShare(),e.emit(uW.SCREEN_SHARE_STOPPED)})),h.getAudioTracks()[0]){l=new OB(e._room.audioManager);let o=h.getAudioTracks()[0];null!=(r=t.option)&&r.systemAudio&&!(null!=(i=t.option)&&i.audioTrack)&&(l.sourceTrack=o),yield l.setInputMediaStreamTrack(o),WD(a)&&l.mediaTrack&&(l.mediaTrack.enabled=!a),e._speakerId&&l.setAudioOutput(e._speakerId)}if(zP(c,c).add("player-state-changed",(t=>{e.emit(uW.VIDEO_PLAY_STATE_CHANGED,$b(Xb({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[c];l&&(t.push(l),e._checkScreenAudioEchoCancellation(c,l)),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=c,e._localScreenAudioTrack=l,e._localScreenConfig=$b(Xb({},t),{view:o,publish:n}),yield e._updateVideoPlayOption({view:o,playOption:u,track:c})}()}))}updateScreenShare(e){return ow(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:i,muteSystemAudio:o,option:n}=e,a={};if(n&&(FD(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let e=BH(n.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!FD(i)){if(i&&!this._localScreenConfig.publish){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.publish(...e).catch((()=>{}))}if(this._localScreenConfig.publish&&!i){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._room.unpublish(...e).catch((()=>{}))}}null!=(t=this._localScreenAudioTrack)&&t.mediaTrack&&WD(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),sN(this._localScreenConfig,e)}))}stopScreenShare(){return ow(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return ow(this,null,(function*(){let{view:t,userId:r,streamType:i,option:o}=e,n="".concat(r,"_").concat(i);if(this._remoteVideoConfigMap.has(n))return void this._log.warn("remote video has already started. userId:".concat(r,", streamType:").concat(i));let a=this._room.remotePublishedUserMap.get(r);if(!a)return;let s={},c="main"===i?a.remoteVideoTrack:a.remoteAuxiliaryTrack;c.on("decode-failed",(e=>{this.emit(uW.ERROR,new VH({code:MH.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),c.on("video-size-changed",(e=>{this.emit(uW.VIDEO_SIZE_CHANGED,$b(Xb({},e),{streamType:FH(e.streamType)}))})),this._listenOutputTrackChanged(c),o&&(FD(o.fillMode)||(s.objectFit=o.fillMode),FD(o.mirror)||(s.mirror=o.mirror),FD(o.poster)||(s.poster=o.poster),s.canvasRender=o.canvasRender,"main"===i&&!FD(o.small)&&(!a.remoteVideoTrack.isSubscribing&&!a.remoteVideoTrack.isSubscribed&&a.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,i),yield this._updateVideoPlayOption({view:t,playOption:s,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(n,{config:e}),o&&!FD(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:null==o?void 0:o.viewRoot})}))}updateRemoteVideo(e){return ow(this,null,(function*(){var t,r;let{view:i,userId:o,streamType:n,option:a}=e,s="".concat(o,"_").concat(n),c=this._remoteVideoConfigMap.get(s);if(!c||!this._room.remotePublishedUserMap.has(o))return;let l={};a&&(FD(a.fillMode)||(l.objectFit=a.fillMode),FD(a.mirror)||(l.mirror=a.mirror));let d=null,u=this._room.remotePublishedUserMap.get(o);if("main"===n&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===n&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===n&&a&&!FD(a.small)&&this._room.changeType(a.small,d.user),yield this._updateVideoPlayOption({view:i,playOption:l,track:d,prevConfig:h}),sN(h,e);let p=FD(null==a?void 0:a.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:a.receiveWhenViewVisible,m=FD(i)?h.view:i,f=FD(null==a?void 0:a.viewRoot)?null==(r=h.option)?void 0:r.viewRoot:a.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:f})}))}stopRemoteVideo(e){return ow(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ow(this,null,(function*(){let r=[],i=this._room.remotePublishedUserMap.get(e.userId);if(i){let{muteState:t,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=i;"main"===e.streamType&&(o.stop(),t.hasVideo&&r.push(o)),"sub"===e.streamType&&(n.stop(),t.hasAuxiliary&&r.push(n))}for(let e of r)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let r="".concat(e,"_").concat(t),i=this._remoteVideoConfigMap.get(r);i&&i.observer&&i.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return ow(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(iM){throw iM.code!==MH.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),iM}}))}setRemoteAudioVolume(e,t){if("*"===e){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach(((e,r)=>this._remoteAudioVolumeMap.set(r,t)));let e=[...this._room.remotePublishedUserMap.values()];for(let r of e)this._remoteAudioVolumeMap.set(r.userId,t),r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return ow(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return ow(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return ow(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,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(uW.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:e}=this.room.audioManager;e.get("")||e.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];try{hW.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(r)))}catch(iM){}return super.emit(e,...r)}off(t,r,i){if(this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,r,i),(t===e.EVENT.AUDIO_FRAME||"*"===t)&&0===this.listeners(e.EVENT.AUDIO_FRAME).length){let{getPCMAbortCtrlMap:e}=this.room.audioManager;e.forEach((e=>{null==e||e.abort("off")})),e.clear()}return this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},r=null,i="main",o=!1;if(BD(t)?e=t:(e=t.userId,o=!0===t.processed,t.streamType&&(i=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(r=t.remoteAudioTrack)}else r="sub"===i?this._localScreenAudioTrack:this._localAudioTrack;return r?o&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:r="main",processed:i=!1}=e,o=null;if(""===t)"main"===r&&this._localVideoTrack&&(o=this._localVideoTrack),"sub"===r&&this._localScreenTrack&&(o=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(o="main"===r?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return o?i&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:r="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===r&&null!=e&&e.muteState.hasVideo)return e.remoteVideoTrack.getVideoFrame();if("sub"===r&&null!=e&&e.muteState.hasAuxiliary)return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===r&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===r&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(r=this._localScreenAudioTrack)||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}setCurrentSpeaker(e){return ow(this,null,(function*(){(yield iU()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),Sj=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return ow(this,null,(function*(){var t;let{userId:r}=e;if(this._remoteAudioConfigMap.has(r))return void this._log.warn("remote audio has already started. userId:".concat(r));let i=this._room.remotePublishedUserMap.get(r);if(!i)return;let o={},n=i.remoteAudioTrack;n.on("decode-failed",(e=>{this.emit(uW.ERROR,new VH({code:MH.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))})),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=null!=(t=this._remoteAudioVolumeMap.get(r))?t:this._remoteAudioVolumeMap.get("*"),a=HD(i)?i:100;o.volume=a,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),FU(vV(n,"decode-failed"),HV(vV(n,PP.INIT)),WF((()=>{this.startPlugin(_j.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:o,track:n}),WO.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:"ra-".concat(r)})}catch(nM){throw this._remoteAudioConfigMap.delete(r),nM}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ow(this,null,(function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),WO.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})}))}_enableVideoDecodeFallback(e,t){let r,i=this._room.videoDecodeFallbackType;i&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),FU(vV(e,"decode-failed"),HV(vV(e,PP.INIT)),jF((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:i})})),yF(vV(e,"decode-downgrade-state-changed")),WF((i=>{r=i.state,this.emit(uW.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,$b(Xb({},i),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===r&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return ow(this,arguments,(function(e){let{view:t,playOption:r,track:i,prevConfig:o}=e;return function*(){if(i.setMirror(r.mirror),FD(t)&&o&&o.view&&!iN(r)){let e=lN(o.view);e.length>0&&(yield i.play(e,r))}if(!FD(t)){let e=lN(t);e.length>0?yield i.play(e,r):i.stop()}}()}))}_updateAudioPlayOption(e){return ow(this,arguments,(function(e){var t=this;let{playOption:r={},track:i,prevConfig:o}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,r)}catch(Sw){}if(FD(r.muted)||i.setPlayerMute(r.muted),FD(r.volume)||i.setAudioVolume(r.volume/100),i instanceof XF&&i.mediaTrack){let e=!1===r.muted&&!FD(r.volume)&&r.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:i.mediaTrack,refId:"em"})}else if(i instanceof UB){let e=r.muted?0:r.volume;if(FD(e))return;t.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(i.userId),volume:r.volume})}}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(uW.TRACK,{userId:r,streamType:FH(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,r;let i=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&i.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&t.publish&&this._localVideoTrack&&i.push(this._localVideoTrack),null!=(r=this._localScreenConfig)&&r.publish&&(this._localScreenTrack&&i.push(this._localScreenTrack),this._localScreenAudioTrack&&i.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),0!==i.length)return this._room.publish(...i).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:r,receiveWhenViewVisible:i=!1,viewRoot:o}=e;if(FD(r))return;let n=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(FH(t.streamType)));if(!n)return;let a=n.observer||void 0;if(null===r||GD(r)&&0===r.length||!i)return null==a||a.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let s=n.visibleViewMap||new Map,c=-1;(!a||a.root!==o)&&(null==a||a.disconnect(),s.clear(),a=new IntersectionObserver((e=>{e.forEach((e=>{s.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),clearTimeout(c),c=window.setTimeout((()=>{[...s.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:o}));let l=new Set(lN(r));s.forEach(((e,t)=>{l.has(t)||(a.unobserve(t),s.delete(t))})),l.forEach((e=>{s.set(e,!0),a.observe(e)})),a.takeRecords().forEach((e=>{s.set(e.target,e.isIntersecting)})),n.visibleViewMap=s,n.observer=a}_exitRoom(){return ow(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()}))}_stopScreenShare(){return ow(this,null,(function*(){var e,t;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&&(!1===(null==(t=this._localScreenAudioTrack.trackSettings)?void 0:t.echoCancellation)&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),KP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return ow(this,null,(function*(){var r,i;if(!e||!t)return;let o=null==(r=e.trackSettings)?void 0:r.displaySurface;if(!1===(null==(i=t.trackSettings)?void 0:i.echoCancellation)&&("monitor"===o||"browser"===o&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(rM){this._log.warn("start audioProcessor plugin failed: ",rM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!Sj||Qx(Sj))&&(this._initActiveSpeaker(),WO.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return ow(this,null,(function*(){if(Sj&&!Qx(Sj))this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:Sj});else{let e=yield iU();e[0]&&!Qx(e[0])?(Sj=e[0],this.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):WO.on("102",this._onLocalTrackCaptured,this)}}))}_onAudioAvailable(e){let{userId:t}=e,r=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===r||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:r}=e;if(!this._room.autoReceiveVideo)return;let i=this._room.remotePublishedUserMap.get(t);if(i){let e="main"===r?i.remoteVideoTrack:i.remoteAuxiliaryTrack,t=[e];this._room.autoReceiveAudio&&i.remoteAudioTrack.isAvailable&&t.push(i.remoteAudioTrack),this._room.subscribe(...t).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:r}=e;r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:r}=e;this._stopRemoteVideo({userId:t,streamType:r},!1).catch((()=>{}))}sendSEIMessage(e,t){var r;let i=this._plugins.get("SEI");i&&(i.update({buffer:e,options:$b(Xb({seiPayloadType:243},t),{small:!(null==(r=this._localVideoTrack)||!r.small)})}),EL.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;null==(r=(t=this._room).sendCustomMessage)||r.call(t,e),EL.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return ow(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),Ej.call(e,Xb({trtcInstance:this},t))}))}static setLogLevel(e,t){qO.setLogLevel(e),FD(t)||(t?qO.enableUploadLog():qO.disableUploadLog())}static isSupported(){return kL(e.frameWorkType)}static getPermissions(e){return ow(this,arguments,(function(e){let{request:t=!0,types:r=["camera","microphone"]}=e;return function*(){t&&(yield Tj.request(r).catch((e=>{var t;return qO.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,i]=yield Promise.all([Tj.get("camera"),Tj.get("microphone")]);return{camera:e,microphone:i}}()}))}static getCameraList(){return tU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return eU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return iU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return ow(this,null,(function*(){if(!rk||t!==OH.SPEAKER&&t!==OH.HEADSET)(yield iU()).forEach((e=>{e.deviceId===t&&(Aj.forEach((r=>{r._setCurrentSpeaker(t),r.emit(uW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),Sj=e)}));else{let r=yield e.getMicrophoneList(),i="";if(r.forEach((e=>{e.label===t&&(i=e.deviceId)})),!i)return;Aj.forEach((e=>ow(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:i}}))}))))}}))}static _addKVStat(e){let{type:t,key:r,value:i,base:o,useUV:n,version:a,max:s}=e;switch(a&&(gL.version=a),t){case"count":gL.addCount({key:r,useUV:n});break;case"enum":gL.addEnum({key:r,value:i,useUV:n});break;case"number":gL.addNumber({key:r,value:i,split:o,max:s})}}};rw(Rj,"VERSION",NW),rw(Rj,"_loggerManager",qO),rw(Rj,"EVENT",uW),rw(Rj,"ERROR_CODE",MH),rw(Rj,"TYPE",OH),rw(Rj,"frameWorkType",30),tw([PW({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?null==e?void 0:e.assetsPath:"default"}})})],Rj.prototype,"use",1),tw([kW(ZH.TRTC.enterRoom),cW("room",((e,t)=>{let[r]=e,[i]=t;return(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId})),yU((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),PW()],Rj.prototype,"enterRoom",1),tw([PW()],Rj.prototype,"exitRoom",1),tw([kW(ZH.TRTC.switchRoom),PW(),bU()],Rj.prototype,"switchRoom",1),tw([kW(ZH.TRTC.switchRole),lW("room",{merge:(e,t)=>t}),PW()],Rj.prototype,"switchRole",1),tw([PW()],Rj.prototype,"destroy",1),tw([kW(ZH.TRTC.startLocalAudio),cW("audio",((e,t)=>{let[r]=e,[i]=t;var o,n;return(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)===(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)})),PW()],Rj.prototype,"startLocalAudio",1),tw([kW(ZH.TRTC.updateLocalAudio),lW("audio",{debounce:{delay:200,getKey:()=>"".concat(Ij,"-localAudio"),isNeedToDebounce:e=>{var t;return!FD(null==(t=e.option)?void 0:t.captureVolume)}}}),PW()],Rj.prototype,"updateLocalAudio",1),tw([dW("audio"),PW()],Rj.prototype,"stopLocalAudio",1),tw([kW(ZH.TRTC.startLocalVideo),cW("video",((e,t)=>{let[r]=e,[i]=t;var o,n;return(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)===(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)})),PW()],Rj.prototype,"startLocalVideo",1),tw([kW(ZH.TRTC.updateLocalVideo),lW("video"),PW()],Rj.prototype,"updateLocalVideo",1),tw([dW("video"),PW()],Rj.prototype,"stopLocalVideo",1),tw([kW(ZH.TRTC.startScreenShare),cW("screen",(()=>!0)),PW()],Rj.prototype,"startScreenShare",1),tw([kW(ZH.TRTC.updateScreenShare),lW("screen"),PW()],Rj.prototype,"updateScreenShare",1),tw([PW()],Rj.prototype,"stopScreenShare",1),tw([kW(ZH.TRTC.startRemoteVideo),cW((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),PW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Rj.prototype,"startRemoteVideo",1),tw([kW(ZH.TRTC.updateRemoteVideo),lW((e=>"v".concat(e.userId).concat(e.streamType))),PW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Rj.prototype,"updateRemoteVideo",1),tw([kW(ZH.TRTC.stopRemoteVideo),yU((e=>function(t){return ow(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)}))})),PW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Rj.prototype,"stopRemoteVideo",1),tw([dW((e=>"v".concat(e.userId).concat(e.streamType)))],Rj.prototype,"_stopRemoteVideo",1),tw([kW(...ZH.TRTC.muteRemoteAudio),PW({getRemoteId:e=>e})],Rj.prototype,"muteRemoteAudio",1),tw([OW(...ZH.TRTC.setRemoteAudioVolume),function(e,t){return yU(((r,i)=>function(){for(var i=arguments.length,o=new Array(i),n=0;n<i;n++)o[n]=arguments[n];let a=DW.get(this);a||(a=new Map,DW.set(this,a));let s=t(...o),c=a.get(s);if(!c||c<=0){r.apply(this,o);let t=setTimeout((()=>{var e;null==(e=DW.get(this))||e.delete(s)}),e);a.set(s,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;r.apply(this,o),null==(e=DW.get(this))||e.delete(s)}),e);a.set(s,t)}}))}(200,(e=>e)),PW({getRemoteId:e=>e})],Rj.prototype,"setRemoteAudioVolume",1),tw([UW("start"),vU((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),cW(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),PW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>hL[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],Rj.prototype,"startPlugin",1),tw([UW("update"),lW(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(sN(e[1],t[1]),e)}),PW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>pL[e.getName()]})],Rj.prototype,"updatePlugin",1),tw([UW("stop"),dW(((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),i=e.getAlias();return"*"===r?new RegExp("".concat(i,".*")):i+r})),PW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>mL[e.getName()]})],Rj.prototype,"stopPlugin",1),tw([OW(...ZH.TRTC.enableAudioVolumeEvaluation)],Rj.prototype,"enableAudioVolumeEvaluation",1),tw([PW()],Rj.prototype,"getVideoSnapshot",1),tw([PW()],Rj.prototype,"_setCurrentSpeaker",1),tw([cW((e=>"a".concat(e.userId)),(()=>!0))],Rj.prototype,"_startRemoteAudio",1),tw([yU((e=>function(t){return ow(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio($b(Xb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),dW((e=>"a".concat(e.userId)))],Rj.prototype,"_stopRemoteAudio",1),tw([dW("room")],Rj.prototype,"_exitRoom",1),tw([dW("screen")],Rj.prototype,"_stopScreenShare",1),tw([kW(...ZH.TRTC.sendSEIMessage),DH({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].byteLength}})],Rj.prototype,"sendSEIMessage",1),tw([kW(ZH.TRTC.sendCustomMessage),DH({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Rj.prototype,"sendCustomMessage",1),tw([kW(ZH.TRTC.create)],Rj,"_create",1);var bj=Rj,wj=class{constructor(e,t){rw(this,"_flag"),rw(this,"terminalType"),rw(this,"userId"),rw(this,"tinyId"),rw(this,"role"),rw(this,"remoteAudioTrack"),rw(this,"remoteVideoTrack"),rw(this,"remoteAuxiliaryTrack"),this.userId=t.userId||"",this.tinyId=t.tinyId||"",this.role=t.role||"audience",this.terminalType=t.terminalType,this.remoteAudioTrack=new UB(e,this),this.remoteVideoTrack=new VB(e,this),this.remoteAuxiliaryTrack=new FB(e,this),this.flag=t.flag||0}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 oN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){if(e===this._flag)return;let t,r=this.muteState;this._flag=e;let i=this.muteState;for(t in i)r[t]!=i[t]&&console.log(this.userId,t,r[t],"->",i[t]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}},Cj=class{constructor(){rw(this,"_set",new Set),WO.on(GO.LEAVE_SUCCESS,this.delete,this),WO.on(GO.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(e){let{room:t,roomId:r}=e;if("rtc"===t.scene)return;let i=this.getKey(t.userId,r||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(i)}delete(e){let{room:t,roomId:r}=e;if("rtc"===t.scene)return;let i=this.getKey(t.userId,t.roomId||r,t.sdkAppId,t.useStringRoomId);this._set.delete(i)}getKey(e,t,r,i){return"".concat(r,"_").concat(t,"_").concat(e,"_").concat(i)}isJoined(e){let{userId:t,roomId:r,sdkAppId:i,room:o}=e;return"rtc"!==o.scene&&this._set.has(this.getKey(t,r,i,o.useStringRoomId))}handleSwitchRoomSuccess(e){let{room:t,currentRoomId:r,targetRoomId:i}=e;"rtc"!==t.scene&&(this._set.delete(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,i,t.sdkAppId,t.useStringRoomId)))}};function Dj(){return ow(this,null,(function*(){let e,t;try{let t=yield eU();e=t&&t.length}catch(p){}try{let e=yield tU();t=e&&e.length}catch(p){}let r={microphone:e,camera:t},{isH264EncodeSupported:i,isVp8EncodeSupported:o,isH264DecodeSupported:n,isVp8DecodeSupported:a,isH265EncodeSupported:s,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=XO.basis(),d={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:i,h264Decode:n,vp8Encode:o,vp8Decode:a,h265Encode:s,h265Decode:c},u={browser:l.browser,os:l.os,trtc:d,devices:r},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};qP.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),qP.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),IP()}))}var Nj=class{constructor(e){rw(this,"_frameWorkType"),rw(this,"_component"),rw(this,"_language"),rw(this,"connectionType"),rw(this,"_room"),rw(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),rw(this,"_keyPrefix"),rw(this,"_log"),rw(this,"_intervalId"),rw(this,"_firstPublishedUserList"),rw(this,"_networkQuality"),rw(this,"_basicInfo"),rw(this,"_pathJoinRoom"),rw(this,"_pathLeaveRoom"),rw(this,"_pathMainVideoMap"),rw(this,"_pathMainAudioMap"),rw(this,"_pathAuxiliaryMap"),rw(this,"_remoteStreamStatMap"),rw(this,"_localStreamStat"),rw(this,"_eventMap",new Map),rw(this,"_captureCostSum",0),rw(this,"_captureCostCount",0),rw(this,"isDestroyed",!1),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")&&VD(this[e])&&(this[e]=function(e){let{fn:t,context:r}=e;return function(){try{for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];let n=t.apply(r,i);return qD(n)?n.catch((e=>qO.error("".concat(t.name,"() error observed ").concat(e)))):n}catch(RC){qO.error("".concat(t.name,"() error observed ").concat(RC))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Tw,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,NO().then((()=>{this._basicInfo.string_os_version=VO(),this._basicInfo.string_device_name=OO()||this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),WO.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(GO.JOIN_START,this.handleJoinStart).addEvent(GO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(GO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(GO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(GO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(GO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(GO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(GO.JOIN_FAILED,this.handleJoinFailed).addEvent(GO.LEAVE_START,this.handleLeaveStart).addEvent(GO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(GO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(GO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(GO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(GO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(GO.PUBLISH_START,this.handlePublishStart).addEvent(GO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(GO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(GO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(GO.PLAY_TRACK_START,this.handlePlayStart).addEvent(GO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(GO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:r,type:i}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===r&&(i===$w.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(GO.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(GO.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(GO.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(GO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(GO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(GO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(GO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;if(!this.hitTest(t))return;let o=r.hasAudio||r.hasVideo||r.hasSmall,n=r.hasAuxiliary,a=i.hasAudio||i.hasVideo||i.hasSmall,s=i.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(i.userId,"main"),!n&&s&&this.handleRemoteStreamAdded(i.userId,"auxiliary")})).addEvent(GO.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:r}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=r.ice,this._pathJoinRoom.int32_dtls_cost=r.dtls,this._pathJoinRoom.int32_peer_connection_cost=r.peerConnection)}))}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach(((e,t)=>WO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),HP.clearTask(this._intervalId),0===this._pathJoinRoom.uint64_start_time&&(this._room=null),this.isDestroyed=!0}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()),e.params&&(FD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),FD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),FD(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:r}=e;if(this.hitTest(t)&&r){let{totalCost:e,local:t,dns:i,tcp:o,tls:n,request:a,response:s}=r;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=i,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=n,this._pathJoinRoom.int32_schedule_request=a,this._pathJoinRoom.int32_schedule_response=s}}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:r}=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(),r&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=r instanceof pw?Number(r.getExtraCode()||r.getCode()):uw.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:r}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=r.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())}handleSwitchRoomStart(e){if(this.hitTest(e.room)){let e=Date.now();this.report().then((()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e}))}}handleSwitchRoomSuccess(e){let{room:t}=e;if(this.hitTest(t)&&0===this._pathJoinRoom.uint64_end_time){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(e){let{room:t,error:r}=e;if(this.hitTest(t)){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,r&&(this._pathJoinRoom.int32_end_ret=r instanceof pw?Number(r.getExtraCode()||r.getCode()):uw.UNKNOWN)}}handleRemoteStreamAdded(e,t){var r;let i="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(i)){let o={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:$b(Xb({},Oj),{msg_user_info:new Mj({userId:e,tinyId:null==(r=this._room.remotePublishedUserMap.get(e))?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(i,o)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:r,streamType:i,subscribeState:o}=e;if(!this.hitTest(t))return;let{userId:n,tinyId:a,role:s}=r,c=new Mj({userId:n,tinyId:a,role:"anchor"===s?20:21}),l=Date.now(),d="".concat(n,"_").concat(i),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===i?(r.muteState.hasVideo&&(o.video||o.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:n,sendSubscribeCMDTime:l}),r.muteState.hasAudio&&o.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:n,sendSubscribeCMDTime:l})):r.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:r,streamType:i}=e;if(this.hitTest(t)){let e="".concat(r.userId,"_").concat(i),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let r="".concat(t.userId,"_").concat(t.streamType),i=this._remoteStreamStatMap.get(r);0===(null==i?void 0:i.playStreamTime)&&(i.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let r="".concat(t.userId,"_").concat(t.streamType),i=this._pathMainVideoMap.get(r);i&&0===i.statsToReport.uint64_combine_first_frame_time&&(i.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),r=Date.now(),i=this._pathMainVideoMap.get(t),o=this._remoteStreamStatMap.get(t);if(o){let{statsToReport:t}=o;if(t.uint32_video_render_first||"main"!==e.streamType?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){let e=r-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,EL.addNumber({key:516820,value:e})}}0===(null==i?void 0:i.statsToReport.uint64_render_first_frame_time)&&(i.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),r=this._pathMainAudioMap.get(t);r&&0===r.statsToReport.uint64_play_first_frame_time&&(r.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:r,userId:i,videoDelay:o,audioDelay:n}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(a)a.totalRTT+=t,a.totalLoss+=r,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let e,a,s,c;o&&(a=o,s=1),n&&(e=n,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(i,{totalRTT:t,totalLoss:r,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:c,videoDelayCount:s})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:i}=e.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:i,uint32_video_height:o}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=i,this._localStreamStat.totalVideoHeight+=o,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:e}=r.msg_audio_status;Math.floor(e/jM*100)>0&&(this._localStreamStat.totalAudioLevel+=e/jM,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:r,msg_video_status:i}=e,o=t.str_identifier,n=this._room.remotePublishedUserMap.get(o);if(i.forEach((e=>{let t=2===e.uint32_video_stream_type,r=7===e.uint32_video_stream_type,i="".concat(o,"_").concat(t?"main":"auxiliary"),a=this._remoteStreamStatMap.get(i);if(a&&(t&&null!=n&&n.remoteVideoTrack.isSubscribed||r&&null!=n&&n.remoteAuxiliaryTrack)){a.totalVideoFPS+=e.uint32_video_receive_fps,a.totalVideoBitrate+=e.uint32_video_codec_bitrate,a.videoCount++,0===a.statsToReport.uint32_video_width&&(a.statsToReport.uint32_video_width=e.uint32_video_width),0===a.statsToReport.uint32_video_height&&(a.statsToReport.uint32_video_height=e.uint32_video_height);let r=t?n.remoteVideoTrack:n.remoteAuxiliaryTrack;r.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=r.stat.jitterBufferDelay),r.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(r.stat.framesDecoded/r.stat.framesReceived*Yb(10,6)))}})),!iN(r)){let e="".concat(o,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=n&&n.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=r.uint32_audio_codec_bitrate,t.audioCount++,n.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=n.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(r.uint32_audio_level/jM*100)>0&&(t.totalAudioLevel+=r.uint32_audio_level/jM,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}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:r}=e,i={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[r.name]||(r instanceof pw?r.getExtraCode()||r.getCode():uw.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=i,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=i,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&tC))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&oC))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&iC))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),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:r}=e,i=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(i){let{totalLoss:t,count:r,audioDelayCount:o,videoDelayCount:n,totalAudioDelay:a,totalVideoDelay:s}=i;e.statsToReport.uint32_avg_down_loss=Math.floor(t/r),o&&a&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(a/o),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),n&&s&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(s/n))}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:o}=this._room;o&&(e.statsToReport.uint32_audio_play_time=o.getDuration(t,$w.AUDIO),e.statsToReport.uint32_video_play_time=o.getDuration(t,$w.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,kj));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:s}=n.getDataFreezeDuration(t),{renderFreeze:c}=n.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=s,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),n.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})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>kj&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+kj):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>kj&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+kj):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>kj&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+kj)}getReportData(){this._basicInfo.uint32_networkType=bD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Mj({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:aN(this._signalInfo.relayIp),uint32_client_ip:aN(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Yb(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:aN(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return EN(e),e}report(){return ow(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(tM){this._log.warn(tM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return ow(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),r=zO.enable?CN(e,2001,t):yield UN(e),i=r instanceof ArrayBuffer,o="".concat(TD(t,Fw.KEY_POINT),"&gzip=").concat(+i),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,r));let a=[this.uploadKVStat(EL),this.uploadKVStat(gL)];n||a.push(xN({url:o,body:r,priority:"low"})),yield Promise.all(a)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return ow(this,null,(function*(){let t=e.getReportData(this._room.userSig,this._signalInfo.reportToken);if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=$b(Xb({},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 r=zO.enable?CN(t,2003,this._room.sdkAppId):yield UN(t),i=r instanceof ArrayBuffer,o="".concat(TD(+this._room.sdkAppId,Fw.KV_STAT),"&gzip=").concat(+i),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,r)),n||xN({url:o,body:r})}))}};tw([JP({settings:{timeout:500,retries:3}})],Nj.prototype,"upload",1);var kj=5e3,Oj={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_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},Mj=class{constructor(e){rw(this,"str_identifier"),rw(this,"str_tinyid"),rw(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},Lj=Nj,Pj=class{constructor(){rw(this,"_startTime"),rw(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=ZD())}stop(){0===this._endTime&&(this._endTime=ZD())}getDuration(){return 0===this._endTime?ZD()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},xj=class{constructor(e){rw(this,"_room",null),rw(this,"_durationMap"),rw(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(GO.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(GO.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(GO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;var o;let{userId:n}=i;if(!this.hitTest(t))return;r.hasAudio&&!i.hasAudio&&this.stopDurationItem("".concat(n,"_main"),$w.AUDIO),r.hasVideo&&!i.hasVideo&&this.stopDurationItem("".concat(n,"_main"),$w.VIDEO),r.hasAuxiliary&&!i.hasAuxiliary&&this.stopDurationItem("".concat(n,"_auxiliary"),$w.VIDEO);let a=null==(o=this._room)?void 0:o.remotePublishedUserMap.get(n);a&&(!r.hasAudio&&i.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,$w.AUDIO,"main"),!r.hasVideo&&i.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,$w.VIDEO,"main"),!r.hasAuxiliary&&i.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,$w.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>WO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>WO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{track:t}=e;if(!this.hitTest(t.room))return;let{userId:r,streamType:i,kind:o}=t;t.isSubscribed?this.addDuractionItem(r,o,i):this.stopDurationItem("".concat(r,"_").concat(i),o)}handleUnsubscribed(e){let{track:t}=e;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,r){let i="".concat(e,"_").concat(r),o=new Pj,n=this._durationMap.get(i);n?this.isRecording(n[t])||n[t].push(o):this._durationMap.set(i,{userId:e,type:r,audio:t===$w.AUDIO?[o]:[],video:t===$w.AUDIO?[]:[o]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let r=this._durationMap.get(e)[t].find((e=>0===e.endTime));r&&r.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()}},Uj=class{constructor(e){rw(this,"_room"),rw(this,"_renderFreezeMap",new Map),rw(this,"_isVideoPlayingEventFiredMap",new Map),rw(this,"_dataFreezeMap",new Map),rw(this,"_monitorFreezeData",new Map),rw(this,"_eventMap",new Map),rw(this,"_videoEncodeFailedCount",0),rw(this,"_audioEncodeFailedCount",0),rw(this,"_encodeFailedThreshold",3),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(GO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(GO.PLAY_TRACK_START,this.onPlayTrackStart).set(GO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:r,remotePublishedUser:i}=e;if(!this.hitTest(t))return;let{userId:o}=i,n="".concat(o,"_").concat(r);this.stopDataFreeze({key:n,userId:o,type:r})})).set(GO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;if(!this.hitTest(t))return;let{userId:o}=i;if(r.hasVideo&&!i.hasVideo){let e="main",t="".concat(i.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}if(r.hasAuxiliary&&!i.hasAuxiliary){let e="auxiliary",t="".concat(i.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}})).set(GO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:r,reason:i,type:o}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&o===$w.VIDEO){if("PLAYING"===r){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}i===$w.MUTE?this.onVideoTrackMuted(t):i===$w.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(GO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>WO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>WO.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:r}=e,i="".concat(t,"_").concat(r),o=this._dataFreezeMap.get(i),n=new Pj;o?o.durationItemList.push(n):this._dataFreezeMap.set(i,{userId:t,type:r,durationItemList:[n],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:r}=e,i="".concat(t,"_").concat(r);this.stopDataFreeze({key:i,userId:t,type:r})}onHearBeatReport(e){let{room:t,report:r}=e;if(this.hitTest(t)){if(r.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:r,muteState:i}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&i.hasVideo&&!i.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&i.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))})),r.msg_up_stream_info.msg_video_status){let e=r.msg_up_stream_info.msg_video_status,t=Array.from(this._room.localTracks).find((e=>"video"===e.kind&&!e.isScreen)),i=(null==t?void 0:t.stat.bytesSent)||0;if(!1===(null==t?void 0:t.isMediaTrackActive)||i<=0)return;e.forEach((e=>{2===e.uint32_video_stream_type&&(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=t&&t.isPublished?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&(qP.uploadEvent({userId:this._room.userId,log:"stat-".concat(wC.VIDEO_ENCODE_FAILED_DURING_CALL)}),this._videoEncodeFailedCount=0)):this._videoEncodeFailedCount=0)}))}if(r.msg_up_stream_info.msg_audio_status){let e=r.msg_up_stream_info.msg_audio_status,t=Array.from(this._room.localTracks).find((e=>"audio"===e.kind)),i=(null==t?void 0:t.stat.bytesSent)||0;if(!1===(null==t?void 0:t.isMediaTrackActive)||i<=0)return;0===e.uint32_audio_codec_bitrate&&null!=t&&t.isPublished?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&(qP.uploadEvent({userId:this._room.userId,log:"stat-".concat(wC.AUDIO_ENCODE_FAILED_DURING_CALL)}),this._audioEncodeFailedCount=0)):this._audioEncodeFailedCount=0}}}stopDataFreeze(e){let{key:t,userId:r,type:i}=e,o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let n=o.durationItemList[o.durationItemList.length-1];n.stop();let a=n.getDuration();a>PC?this._monitorFreezeData.set(t,{userId:r,type:i,duration:a}):o.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)}),0)}handleRenderFreeze(e){return ow(this,arguments,(function(e){var t=this;let{userId:r,fps:i,type:o}=e;return function*(){let e="".concat(r,"_").concat(o),n=t._renderFreezeMap.get(e);if(i<=2){let i=ZD();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:i,endTime:0}),n.isFreeze=!0),n||t._renderFreezeMap.set(e,{userId:r,type:o,isFreeze:!0,freezeTimeline:[{startTime:i,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let e=n.freezeTimeline.pop();if(e){e.endTime=ZD();let t=e.endTime-e.startTime;n.freezeTimeline.push(e),n.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==$w.VIDEO||!t.isRemotePublished)return;let r="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(r)||this._isVideoPlayingEventFiredMap.set(r,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},r=this._dataFreezeMap.get(e);if(r){if(r.isFreezing()){let e=r.durationItemList[r.durationItemList.length-1];e.stop(),e.getDuration()<PC&&r.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(r.durationItemList),t.count=r.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),r=0,i=0;if(t)if(t.isFreeze){let e=ZD()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;r=t.renderFreezeTotal+Math.min(e,5e3),i=t.freezeTimeline.length}else r=t.renderFreezeTotal;return{renderFreeze:r,count:i}}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()}},Vj=ew(nw(),1),Fj=class{constructor(e,t,r,i,o){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=r,this.visionTaskRegistry=i,this.logger=o,rw(this,"animationState"),rw(this,"originalAspect"),rw(this,"totalOffsetX",0),rw(this,"totalOffsetY",0),rw(this,"defaultScaleRatio",.1),rw(this,"isRecovering",!1),rw(this,"boundaryY",280),rw(this,"lastActionTime",0),rw(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}addEvent(e,t,r){let i=[{key:570704,error:null!=r?r:t?void 0:11},{key:570705,error:null!=r?r:t?void 0:22}][e-1];i&&(t?EL.addSuccessEvent({key:i.key}):EL.addFailedEvent({key:i.key,error:i.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:r,videoHeight:i}=e;this.animationState.debounceThreshold=r/30,this.animationState.movementThreshold=r/20,this.boundaryY=.6*i;try{let e=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(e.detections.length<=0)return void(1===this.vbMode&&this.recoverOriginal(r,i));let t=e.detections[0].boundingBox,o=t.originX,n=t.originY,a=t.width,s=t.height;1===this.vbMode?this.dualStageCropping(r,i,o,n,a,s):2===this.vbMode&&this.movingPortrait(r,i,o,n,a,s)}catch(aM){this.logger.error(aM)}this.lastActionTime=t}calculateBoundary(e,t,r,i){let o,n;return e>t/2?(o=t-r-i,n=r-o):(o=r,n=0),{min:o,offset:n}}calculateTargetPosition(e,t,r,i,o,n){let a,s,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,l=e+r/2,d=t+i/2,{min:u,offset:h}=this.calculateBoundary(l,o,e,r),{min:p,offset:m}=this.calculateBoundary(d,n,t,i);return a=2*u+r,s=2*p+i,a/s>this.originalAspect?(a=s*this.originalAspect,h=l-a/2):(s=a/this.originalAspect,m=d-s/2),r/o>c&&(h=0,m=0,a=o,s=n),h=Math.max(0,Math.min(h,o-a)),m=Math.max(0,Math.min(m,n-s)),{sx:h,sy:m,cropWidth:a,cropHeight:s,timestamp:Date.now()}}processFacePositionCrop(e,t,r){if(!this.animationState.current||!this.animationState.target){let e={sx:0,sy:0,cropWidth:t,cropHeight:r,timestamp:Date.now()};return this.animationState.current=e,void(this.animationState.target=e)}let i=this.positionDistance(this.animationState.target,e),o=this.positionDistance(this.animationState.current,e),n=this.animationState.current.cropWidth/t;i>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold*n&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}processFacePositionPortrait(e){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=Xb({},e),void(this.animationState.target=Xb({},e));let t=this.positionDistance(this.animationState.current,e),r=this.positionDistance(this.animationState.target,e);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),r=e=>e<.5?2*e*e:(4-2*e)*e-1;if(this.animationState.current&&this.animationState.target){let e=(this.animationState.target.sx-this.animationState.current.sx)*r(t);this.animationState.current.sx+=e,this.totalOffsetX+=e;let i=(this.animationState.target.sy-this.animationState.current.sy)*r(t);if(this.animationState.current.sy+=i,this.totalOffsetY+=i,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*r(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*r(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*r(t)),HD(this.animationState.current.scaleOffsetX)&&HD(this.animationState.target.scaleOffsetX)&&HD(this.animationState.current.scaleOffsetY)&&HD(this.animationState.target.scaleOffsetY)){let e=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(t);this.animationState.current.scaleOffsetX+=e;let i=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(t);this.animationState.current.scaleOffsetY+=i}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(Yb(e.sx-t.sx,2)+Yb(e.sy-t.sy,2))}recoverOriginal(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(e,t,r,i,o,n){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let s=this.calculateTargetPosition(r,i,o,n,e,t);this.processFacePositionCrop(s,e,t),o*n/s.cropWidth/s.cropHeight>a&&this.recoverOriginal(e,t)}movingPortrait(e,t,r,i,o,n){var a,s,c,l,d,u,h,p,m,f,_,g;let E={sx:r+o/2+this.totalOffsetX,sy:i+n/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(s=null==(a=this.animationState.current)?void 0:a.scaleRatio)?s:1,scaleOffsetX:null!=(l=null==(c=this.animationState.current)?void 0:c.scaleOffsetX)?l:0,scaleOffsetY:null!=(u=null==(d=this.animationState.current)?void 0:d.scaleOffsetY)?u:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:i+n/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(p=null==(h=this.animationState.target)?void 0:h.scaleRatio)?p:1,scaleOffsetX:null!=(f=null==(m=this.animationState.target)?void 0:m.scaleOffsetX)?f:0,scaleOffsetY:null!=(g=null==(_=this.animationState.target)?void 0:_.scaleOffsetY)?g:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(o*n/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(E)}set aspectRatio(e){this.originalAspect=e}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}},Bj=class extends fB{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log}),rw(this,"_bgTexture"),rw(this,"_waterMarkTexture"),rw(this,"_lastMaskTexture"),rw(this,"_lastMaskFbo"),rw(this,"_textureValid",!1),rw(this,"_selfieTextureValid",!1),rw(this,"_selfieSegmentationHash"),rw(this,"wasm"),rw(this,"predictReady"),rw(this,"_color"),rw(this,"_prePrograme"),rw(this,"_segmentationMask"),rw(this,"_weixin",!1),rw(this,"_centerFace"),rw(this,"_textureMatrixLocation"),rw(this,"_offsetMatrixLocation"),rw(this,"_colorLocation"),rw(this,"_enableFaceCentering",!1),rw(this,"_enableEffectOptimization",!1),rw(this,"_mat4"),rw(this,"_postProcessing"),rw(this,"_onAbort"),rw(this,"_visionTaskRegistry"),rw(this,"resolvePreditReady"),this.init(t).catch((t=>{e.log.error(t),e.destroy(new pw({code:uw.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return ow(this,null,(function*(){var t,r,i;this.predictReady=new Promise((e=>{this.resolvePreditReady=e}));let o=e.Wasm,n=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,this._enableEffectOptimization=null!=(r=e.enableEffectOptimization)&&r,this.wasm=new o.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"color"===e.bg?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:t,y:r,width:i,height:o}=e.waterMark;this.wasm.setWaterMark(t,r,i,o)}if(e.beautyParams){let{beauty:t,brightness:r,ruddy:i}=e.beautyParams;this.wasm.setBeauty(t,r,i,null==e?void 0:e.width,null==e?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(n.uniform1i(n.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(n.uniform1i(n.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let a=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=n.getUniformLocation(this.program,"u_textureMatrix"),n.uniformMatrix4fv(this._textureMatrixLocation,!1,a),this._offsetMatrixLocation=n.getUniformLocation(this.program,"u_offsetMatrix"),n.uniformMatrix4fv(this._offsetMatrixLocation,!1,a),this._colorLocation=n.getUniformLocation(this.program,"u_color"),n.uniform1i(n.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(n.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(n.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),n.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.uniform1i(n.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||2!==this.wasm.vbMode&&3!==this.wasm.vbMode?this._postProcessing=void 0:CO()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(i=this._postProcessing)||i.init(n,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)}))}initVisionTasks(e){return ow(this,null,(function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new Fj(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(RC){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}}))}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let r=this.getMaskTexture(e);if(!r)return;let i=r;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,i=this._postProcessing.postProcessing(r)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,i||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),3===this.wasm.vbMode&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),SN(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:i,videoHeight:o}=r;if(SN(this.wasm.rotation)&&!this._visionTaskRegistry&&([i,o]=[o,i]),0===i||0===o||!this.available)return!1;r.width=i,r.height=o;let n=!1;if(this.totalFrames)this.useTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),n=this._textureValid,this._textureValid=!0}if(this.width===i&&this.height===o&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r):(this.resize(i,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let e=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,i,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,i,o,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let e=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);1===this.totalFrames&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(e)}}catch(nM){this._onAbort&&this._onAbort(nM)}return 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)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(1===this.wasm.vbMode&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&2===this.wasm.vbMode)){if(!this._mat4)return;let i=this._mat4.create(),{scaleRatio:o=1,scaleOffsetX:n=0,scaleOffsetY:a=0}=t;this._mat4.fromTranslation(i,[-r.offsetX/e.canvas.width+n,a,0]),this._mat4.scale(i,i,[o,o,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,i)}}drawImage(e,t,r,i){let o=this.context.ctx;if(!this._mat4)return;let{width:n,height:a}=o.canvas,s=this._mat4.create();this._mat4.fromTranslation(s,[e/n,1-(t+i)/a,0]),this._mat4.scale(s,s,[r/n,i/a,1]),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s)}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),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),null==(e=this.wasm)||e.close()}},Hj=class extends nB{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:"\n precision highp float;\n uniform sampler2D ySampler;\n uniform sampler2D uSampler;\n uniform sampler2D vSampler;\n varying highp vec2 textureCoord;\n const mat4 YUV2RGB = mat4(\n 1.1643828125, 0, 1.59602734375, -.87078515625,\n 1.1643828125, -.39176171875, -.81296875, .52959375,\n 1.1643828125, 2.017234375, 0, -1.081390625,\n 0, 0, 0, 1);\n void main() {\n vec3 yuv;\n yuv.r = texture2D(ySampler, textureCoord).r;\n yuv.g = texture2D(uSampler, textureCoord).r;\n yuv.b = texture2D(vSampler, textureCoord).r;\n gl_FragColor = vec4(yuv,1) * YUV2RGB;\n }\n ",vertexShaderSource:"\n attribute vec4 vertexPos;\n attribute vec2 texturePos;\n varying vec2 textureCoord;\n void main() {\n gl_Position = vertexPos;\n textureCoord = texturePos;\n }"}),rw(this,"yTextureRef"),rw(this,"uTextureRef"),rw(this,"vTextureRef"),rw(this,"Y"),rw(this,"U"),rw(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,i=r.createTexture();return r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),i}render(e){let t=this.context.ctx,r=this.width,i=this.height;return this.useProgram(),t.viewport(0,0,r,i),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,i,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,i/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,i/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}},Wj=(e,t)=>{switch(e){case"webCodecs":return"videoFrame"===t?514705:514706;case"wasm":return"webgl"===t?514707:"videoFrame"===t?514708:514709}throw new Error("decoder type not supported")};var jj=0,Gj=class{constructor(e){rw(this,"id",jj++),rw(this,"trackDoneOB"),rw(this,"startOB"),rw(this,"stopOB"),rw(this,"decoder"),rw(this,"videoContext"),rw(this,"gop",0),rw(this,"gop_helper",0),rw(this,"waitFirstKeyFrame",!0),rw(this,"startTimestamp",0),rw(this,"startTime",0),rw(this,"startPerformanceTime",0),rw(this,"inputFrameCount",0),rw(this,"decodedFrameCount",0),rw(this,"decodeFrameCount",0),rw(this,"downgradeLevel",0),rw(this,"lastDowngradeTime",0),rw(this,"lastFrameDiff",0),rw(this,"lastDecodeFrameTimestamp",0),rw(this,"config"),rw(this,"gop_before_configure",[]),rw(this,"videoElement"),rw(this,"type","wasm"),rw(this,"goodType"),rw(this,"renderer","2d"),rw(this,"wasmOption"),rw(this,"createDecoder"),rw(this,"_decodeSink"),rw(this,"isReported",!1),rw(this,"track"),rw(this,"stateChangeOB"),rw(this,"failedReason");let{track:t,createDecoder:r}=e;if(this.stateChangeOB=aV(),this.track=t,this.createDecoder=r,this.wasmOption={yuvMode:"webgl"===e.renderer,wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=vV(t.availableState,PP.OFF),this.stopOB=aV(),"auto"===e.type){switch(e.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode="webgl"===this.renderer}else this.type=e.type;this.changeRenderer(this.renderer),FU(this.stateChangeOB,lF(((e,r)=>(e!==r&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:r}),r)),"INITIALIZED"),HV(this.stopOB),WF()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=FU(this.pipe(this.track),HV(this.stopOB),qU());FU(t,WF((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),EL.addFailedEvent({key:Wj(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),EL.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),EL.addSuccessEvent({key:Wj(this.type,this.renderer)}),EL.addSuccessEvent({key:514704})}))),FU(t,BV(1),WF((()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.start()}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,"videoFrame"===this.renderer&&!wL()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var r,i;if(this.failedReason)return;this.inputFrameCount++;let o=new Uint8Array(e.data);if(!function(e){return 0===e[0]&&0===e[1]&&0===e[2]&&1===e[3]}(o)||o.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(o.subarray(0,5))),e;let n=!1;switch(31&o[4]){case 5:case 7:n=!0}if("configured"!==(null==(r=this.decoder)?void 0:r.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),n&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>this.decode(e,!0))),this.gop_before_configure=[]);let{timestamp:a}=e;if(n?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!n)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(o.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=a,this.startTime=Date.now(),this.startPerformanceTime=ZD()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(a," ").concat(null==(i=e.getMetadata)?void 0:i.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=a,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}checkDowngradeByFrameDiff(){let e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(e){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(e){return t=>ow(this,null,(function*(){this._decodeSink=t;let r,i=e.mediaTrack;t.defer((()=>{var t;i&&(e.player.setCanvas(),e.setInputMediaStreamTrack(i)),null==r||r.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:o,type:n}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let i=0;if(r.on("videoFrame",(r=>{this.decodedFrameCount++,i++,(i<=10||i%500==0)&&e.log.debug("frame ".concat(i," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(r.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(r.timestamp)),t.next(r)})),r.on("error",(r=>{e.log.error(r),t.error("webCodecs"===n?4:8)})),yield r.initialize(this.videoElement),!this._decodeSink)return;if(r.configure(this.config),"wasm"===n&&"webgl"===o){this.videoContext=new yB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(yB.UNAVAILABLE,(r=>{e.log.error(r),t.error(7)}));let i=new Hj(this.videoContext);r.on("videoCodecInfo",(e=>i.resize(e.width,e.height))),r.on("videoFrame",(e=>{({y:i.Y,u:i.U,v:i.V}=e),1===this.downgradeLevel?this.decodedFrameCount%2==0&&i.render(this.decodedFrameCount):i.render(this.decodedFrameCount)})),e.source=i,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===o){e.player.setCanvas();let t=new MediaStreamTrackGenerator({kind:"video"}),i=t.writable.getWriter();e.setInputMediaStreamTrack(t),r.on("videoFrame",(e=>i.write(e)))}else{this.videoContext=new TB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let i=this.videoContext.createVideoImageSource();r.on("videoFrame",(r=>{try{i.image=r,i.update()}catch(o){delete this.goodType,e.log.error(o),t.error(11)}}));let o=new lB(this.videoContext,{name:"remotePlayer",logger:e.log});i.connect(o),e.source=i,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(rM){e.log.error(rM),t.error("webCodecs"===n?2:6)}}))}},zj=Promise.resolve(),Kj=class extends Vj.EventEmitter{constructor(e){super(),this.room=e,rw(this,"videoContext"),rw(this,"_glVideoContext"),rw(this,"_2dVideoContext"),rw(this,"destination"),rw(this,"smallVideoContext"),rw(this,"smallDestination"),rw(this,"smallTrackSource"),rw(this,"smallImageSource"),rw(this,"_isMirror",!1),rw(this,"_rotation",0),rw(this,"cameraTrack"),rw(this,"cameraNode"),rw(this,"transformNode"),rw(this,"mixNode"),rw(this,"screenTrack"),rw(this,"screenNode"),rw(this,"selfModel",!1),rw(this,"blurRadius",3),rw(this,"arTrack"),rw(this,"_enableFaceCentering",!1),rw(this,"_enableEffectOptimization",!1),rw(this,"onAbort"),rw(this,"_color"),rw(this,"Wasm"),rw(this,"waterMarkNode"),rw(this,"_waterMarkOption"),rw(this,"watermarkImageList",[]),rw(this,"_beautyParams"),rw(this,"isUsingArTrack",!1),rw(this,"mixTrack"),rw(this,"_isMixScreen",!1),rw(this,"_virtualBackground"),rw(this,"_virtualBackgroundAbortCallback"),rw(this,"virtualBackgroundInstance"),rw(this,"_bgAssetPath"),rw(this,"log",qO.createLogger({id:"vm"})),rw(this,"_mat4"),rw(this,"_postProcessing"),rw(this,"_checkId",0),rw(this,"_use2d",!1),rw(this,"_autoSwitchRenderMode",!0),rw(this,"encodePipeline",[]),rw(this,"decodePipeline",[]),rw(this,"updated",zj),rw(this,"_updateFlag",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new TB({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return(null==(e=this.room)?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return 0!==this._rotation}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var e;let{width:t,height:r}=(null==(e=this.cameraTrack)?void 0:e.settings)||{};return SN(this._rotation)?{width:r,height:t}:{width:t,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new TB({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new yB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(dO<=22),this._glVideoContext.on(yB.UNAVAILABLE,(e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),null==(t=this._virtualBackgroundAbortCallback)||t.call(this,e),this.update().catch((e=>{this.log.error(e)}))}))}catch(Aw){this.emit("error",Aw)}}initVirtualBackground(e,t,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=HP.run("interval",(()=>{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(),HP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(hO||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&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?EL.addFailedEvent({key:t,error:e}):EL.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new yB({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),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}setSmallVideo(e,t){if("api"!==this.smallMode)if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new hB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(yB.UNAVAILABLE,(e=>{this.log.warn("small video context lost",e)}))}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:e,height:t}=this.cameraTrack.settings;this.smallTrackSource.resize(e,t),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:i,player:o}=r;hO&&o.setCanvas(e);let n=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),n=this.arTrack),this.log.info("set main output ".concat(n?n.label:"no output track")),this.setSmallVideo(i,e),r.setOutputMediaStreamTrack(n)}catch(iM){this.log.error("set main output failed",iM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return ow(this,null,(function*(){var t;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:i}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(nB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===EO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof fB?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof fB?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new uB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(nB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})));let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.cameraNode=new Bj(this.videoContext,{input:this.initialTrack,width:e,height:t,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=i.frameRate,this._use2d){let e=this.cameraNode;if(e.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new bB(this.videoContext,this.log,this._isMirror,this._rotation),e=e.connect(this.transformNode),e.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new SB(this.videoContext,this.log),e.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:e,height:t}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(e,t),e&&t&&this.waterMarkNode.resize(e,t)}null==(t=this.waterMarkNode)||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),e=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}e.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)}))}clearLastFrame(){var e;this.destination&&(null==(e=this.destination.ctx2d)||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,i,o,n;if(e instanceof NB)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof eB)return this.log.info("change video input",null==(r=e.mediaTrack)?void 0:r.label),this.setCameraTrack(e);if(e instanceof VB){this.log.info("change remote input",null==(i=e.mediaTrack)?void 0:i.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}if(e instanceof wB)return this.log.info("change mix input",null==(o=e.outMediaTrack)?void 0:o.label),this.setMixTrack(e);this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof NB?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof eB?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof VB?e.source&&e.source.context.destroy():e instanceof wB&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return ow(this,null,(function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}))}getWatermarkImage(e,t){return ow(this,null,(function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let i=r.getContext("2d");if(!i)throw new pw({code:uw.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:r,y:o,width:n,height:a}=e;i.drawImage(t,r,o,n,a)})),_N(r.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))}setBeautyParams(e){return ow(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return ow(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return ow(this,null,(function*(){let t;try{t=yield _N((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new pw({code:uw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:r=0,y:i=0,width:o=t.width,height:n=t.height,type:a="watermark",zIndex:s=2}=e;this.watermarkImageList.some((e=>e.type===a))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==a)),this.pushWaterMarkImageList({x:r,y:i,width:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:i,width:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return ow(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t))),yield this.freshWatermark()}))}freshWatermark(){return ow(this,null,(function*(){var e;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:r}=this.cameraResolution,i=yield this.getWatermarkImage(t,r);this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.update()}))}setVirtualBackground(e){return ow(this,null,(function*(){var t,r,i;if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield _N(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=null!=(t=e.enableFaceCentering)?t:this._enableFaceCentering,this._enableEffectOptimization=null!=(r=e.enableEffectOptimization)?r:this._enableEffectOptimization,this._color=null!=(i=e.color)?i:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new pw({code:uw.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}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._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return ow(this,null,(function*(){var e;null!=(e=this.cameraTrack)&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new Gj(e)}clear(){var e,t;null==(e=this.videoContext)||e.disconnect(),null==(t=this.destination)||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:r}=e;var i;this.encodePipeline.includes(t)||(this.encodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:r}=e;var i;this.decodePipeline.includes(t)||(this.decodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};tw([function(e){return yU(((t,r)=>function(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return ow(this,null,(function*(){try{return yield t.apply(this,i)}catch(iM){e.call(this,iM)}}))}))}((function(e){this.log.error("update failed",e)})),yU((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return ow(this,null,(function*(){this._updateFlag||(this._updateFlag=!0,yield zj,this.updated=new Promise(((t,i)=>{e.apply(this,r).then(t,i),setTimeout(i,5e3,new pw({code:uw.API_CALL_TIMEOUT,message:"update timeout"}))})),this._updateFlag=!1,yield this.updated)}))}))],Kj.prototype,"update",1);var qj=0,Yj=class extends PP{constructor(e){super("room"),rw(this,"seq",++qj),rw(this,"sdkAppId"),rw(this,"userId"),rw(this,"userSig"),rw(this,"privateMapKey"),rw(this,"latencyLevel"),rw(this,"tinyId"),rw(this,"scene"),rw(this,"roomId"),rw(this,"useStringRoomId"),rw(this,"role","anchor"),rw(this,"joinParams",null),rw(this,"localPublishFlag",0),rw(this,"localTracks",new Set),rw(this,"enableAutoPlayDialog",!0),rw(this,"autoReceiveAudio",!0),rw(this,"autoReceiveVideo",!0),rw(this,"proxy_ws"),rw(this,"proxy_wt"),rw(this,"proxy_unified"),rw(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),rw(this,"keyPointManager"),rw(this,"audioManager"),rw(this,"videoManager"),rw(this,"callDurationCalculator"),rw(this,"badCaseDetector"),rw(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),rw(this,"videoDecodeFallbackType"),rw(this,"smallMode","canvas"),rw(this,"enableChorus",!1),rw(this,"_isUsingCachedSchedule",!1),rw(this,"_log",qO.createLogger({id:"r".concat(this.seq)})),rw(this,"_joinedTimestamp",0),rw(this,"_sdkType"),rw(this,"heartbeatReport"),rw(this,"quality"),rw(this,"enableSEI"),rw(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,WD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),WD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),WD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Lj({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new xj({room:this}),this.badCaseDetector=new Uj({room:this}),this.audioManager=new LB(this),this.videoManager=new Kj(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}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}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}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 ow(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return ow(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return ow(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(BD(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(LD(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:i,scheduleProxy:o,unifiedProxy:n}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=n,n?(vW([n,n]),Dw("https://".concat(n))):(i&&Dw(i),o&&vW(o))}WO.once(GO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:EW.main,sched_back_domain:EW.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return ow(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return ow(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)t.downlinksRTT[r.userId]=r.rtt;return t}))}getRemoteVideoStats(){return ow(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let r={};return e.remotePublishedUserMap.forEach((e=>{let i="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;r[e.userId]=i.stat})),r}()}))}checkDestroy(){if(this.isDestroyed)throw new pw({code:uw.INVALID_OPERATION,message:sL({key:iL.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(oL.INVALID_DESTROY),new pw({code:uw.INVALID_OPERATION,message:sL({key:iL.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,WO.emit(GO.ROOM_DESTROY,{room:this})}schedule(e,t){return ow(this,null,(function*(){var r,i,o,n;let a=ZD();try{let{isCached:s,result:c,detailCost:l}=yield gW({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Tw,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=s,this._log.info("schedule cache:".concat(+s," ").concat(hN(c,{keysToExclude:["username","credential"]}))),s&&WO.once(GO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=Xb(Xb({},this.scheduleResult),c),HD(null==(r=c.config)?void 0:r.retryCount)&&AC(c.config.retryCount),BD(null==(i=c.config)?void 0:i.loggerDomain)&&Dw(c.config.loggerDomain),this.videoDecodeFallbackType=(null==(o=c.config)?void 0:o.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(n=c.config)?void 0:n.smallMode)||this.smallMode,WO.emit(GO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),EL.addSuccessEvent({key:521700,cost:ZD()-a})}catch(ZO){throw EL.addFailedEvent({key:521700,error:ZO}),ZO}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var Jj={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Xj="__INLINE__WORKER__",$j="__INLINE__WASM__",{debug:Qj}=console;Jj.debug||(console.debug=()=>{});var Zj,eG=!Xj.startsWith("__"),tG=!$j.startsWith("__");function rG(){let e=TN("".concat(Jj.assetsPath?"".concat(Jj.assetsPath,"/"):"","worker.js"));return eG?URL.createObjectURL(new Blob([atob(Xj)],{type:"application/javascript"})):e.startsWith("http")?fetch(e).then((e=>e.blob().then((e=>URL.createObjectURL(e))))):e}function iG(){return ow(this,null,(function*(){let e=Jj.assetsPath?"".concat(Jj.assetsPath,"/"):"";return Zj||(Zj=tG?(new TextEncoder).encode(atob($j)).buffer:yield fetch(TN("".concat(e,"av_processing.wasm"))).then((e=>e.arrayBuffer())),Zj)}))}var oG=new class{constructor(){rw(this,"playPort"),rw(this,"playPortSent",!1),rw(this,"worklet"),rw(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return ow(this,null,(function*(){let e=Px(),t=rG();try{yield e.audioWorklet.addModule("string"==typeof t?t:yield t),qO.info("global audio player worklet addModule success",t)}catch(RC){throw qO.error("global audio player worklet addModule failed:",RC),RC}return this.worklet=new AudioWorkletNode(e,"global-audio-player",{processorOptions:{wasm:yield iG(),flag:Jj},numberOfInputs:2}),qO.info("global audio player worklet created",e.state),this.playPort=this.worklet.port,this.playPort}))}playAudio(e){return ow(this,null,(function*(){var t;yield this.init();let r=new MessageChannel;null==(t=this.playPort)||t.postMessage(null,[r.port1]),e(r.port2)}))}},nG="undefined"!=typeof self&&(!("top"in self)||self===top)&&"showOpenFilePicker"in self&&"showOpenFilePicker";nG?Promise.resolve().then((function(){return lG})):Promise.resolve().then((function(){return fG})),nG?Promise.resolve().then((function(){return pG})):Promise.resolve().then((function(){return _G}));var aG=nG?Promise.resolve().then((function(){return mG})):Promise.resolve().then((function(){return gG}));function sG(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(this,null,(function*(){return(yield aG).default(...t)}))}var cG=e=>ow(void 0,null,(function*(){let t=yield e.getFile();return t.handle=e,t})),lG={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(void 0,[...t],(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){Array.isArray(e)||(e=[e]);let t=[];e.forEach(((e,r)=>{t[r]={description:e.description||"Files",accept:{}},e.mimeTypes?e.mimeTypes.map((i=>{t[r].accept[i]=e.extensions||[]})):t[r].accept["*/*"]=e.extensions||[]}));let r=yield window.showOpenFilePicker({id:e[0].id,startIn:e[0].startIn,types:t,multiple:e[0].multiple||!1,excludeAcceptAllOption:e[0].excludeAcceptAllOption||!1}),i=yield Promise.all(r.map(cG));return e[0].multiple?i:i[0]}()}))}};function dG(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then((function(e){return{value:e,done:t}}))}return dG=function(e){this.s=e,this.n=e.next},dG.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new dG(e)}var uG,hG=function(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return ow(void 0,[e,t,...i],(function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.name,i=arguments.length>3?arguments[3]:void 0;return function*(){let o=[],n=[];var a,s=!1,c=!1;try{for(var l,d=function(e){var t,r,i,o=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,i=Symbol.iterator);o--;){if(r&&null!=(t=e[r]))return t.call(e);if(i&&null!=(t=e[i]))return new dG(t.call(e));r="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}(e.values());s=!(l=yield d.next()).done;s=!1){let a=l.value,s="".concat(r,"/").concat(a.name);"file"===a.kind?n.push(a.getFile().then((t=>(t.directoryHandle=e,t.handle=a,Object.defineProperty(t,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>s}))))):"directory"!==a.kind||!t||i&&i(a)||o.push(hG(a,t,s,i))}}catch(u){c=!0,a=u}finally{try{s&&null!=d.return&&(yield d.return())}finally{if(c)throw a}}return[...(yield Promise.all(o)).flat(),...yield Promise.all(n)]}()}))},pG={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(void 0,[...t],(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){e.recursive=e.recursive||!1,e.mode=e.mode||"read";let t=yield window.showDirectoryPicker({id:e.id,startIn:e.startIn,mode:e.mode});return hG(t,e.recursive,void 0,e.skipDirectory)}()}))}},mG={__proto__:null,default:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return ow(void 0,[e,...r],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[{}],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;return function*(){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let n=[],a=null;if(e instanceof Blob&&e.type?a=e.type:e.headers&&e.headers.get("content-type")&&(a=e.headers.get("content-type")),t.forEach(((e,t)=>{n[t]={description:e.description||"Files",accept:{}},e.mimeTypes?(0===t&&a&&e.mimeTypes.push(a),e.mimeTypes.map((r=>{n[t].accept[r]=e.extensions||[]}))):a?n[t].accept[a]=e.extensions||[]:n[t].accept["*/*"]=e.extensions||[]})),r)try{yield r.getFile()}catch(l){if(r=null,i)throw l}let s=r||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:n,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!r&&o&&o(s);let c=yield s.createWritable();return"stream"in e?(yield e.stream().pipeTo(c),s):"body"in e?(yield e.body.pipeTo(c),s):(yield c.write(yield e),yield c.close(),s)}()}))}},fG={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(void 0,[...t],(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){return Array.isArray(e)||(e=[e]),new Promise(((t,r)=>{let i=document.createElement("input");i.type="file";let o=[...e.map((e=>e.mimeTypes||[])),...e.map((e=>e.extensions||[]))].join();i.multiple=e[0].multiple||!1,i.accept=o||"",i.style.display="none",document.body.append(i);let n=e=>{"function"==typeof a&&a(),t(e)},a=e[0].legacySetup&&e[0].legacySetup(n,(()=>a(r)),i),s=()=>{window.removeEventListener("focus",s),i.remove()};i.addEventListener("click",(()=>{window.addEventListener("focus",s)})),i.addEventListener("change",(()=>{window.removeEventListener("focus",s),i.remove(),n(i.multiple?Array.from(i.files):i.files[0])})),"showPicker"in HTMLInputElement.prototype?i.showPicker():i.click()}))}()}))}},_G={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(void 0,[...t],(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{}];return function*(){return Array.isArray(e)||(e=[e]),e[0].recursive=e[0].recursive||!1,new Promise(((t,r)=>{let i=document.createElement("input");i.type="file",i.webkitdirectory=!0;let o=e=>{"function"==typeof n&&n(),t(e)},n=e[0].legacySetup&&e[0].legacySetup(o,(()=>n(r)),i);i.addEventListener("change",(()=>{let t=Array.from(i.files);e[0].recursive?e[0].recursive&&e[0].skipDirectory&&(t=t.filter((t=>t.webkitRelativePath.split("/").every((t=>!e[0].skipDirectory({name:t,kind:"directory"})))))):t=t.filter((e=>2===e.webkitRelativePath.split("/").length)),o(t)})),"showPicker"in HTMLInputElement.prototype?i.showPicker():i.click()}))}()}))}},gG={__proto__:null,default:function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return ow(void 0,[e,...r],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){Array.isArray(t)&&(t=t[0]);let r=document.createElement("a"),i=e;"body"in e&&(i=yield function(e,t){return ow(this,null,(function*(){let r=e.getReader(),i=new ReadableStream({start:e=>function t(){return ow(this,null,(function*(){return r.read().then((r=>{let{done:i,value:o}=r;if(!i)return e.enqueue(o),t();e.close()}))}))}()}),o=new Response(i),n=yield o.blob();return r.releaseLock(),new Blob([n],{type:t})}))}(e.body,e.headers.get("content-type"))),r.download=t.fileName||"Untitled",r.href=URL.createObjectURL(yield i);let o=()=>{"function"==typeof n&&n()},n=t.legacySetup&&t.legacySetup(o,(()=>n()),r);return r.addEventListener("click",(()=>{setTimeout((()=>URL.revokeObjectURL(r.href)),3e4),o()})),r.click(),null}()}))}},EG=class{constructor(e){this.name=e,rw(this,"ready"),rw(this,"worker"),rw(this,"ports"),rw(this,"ids",1),rw(this,"transactions",new Map),rw(this,"log"),rw(this,"addTransaction",(e=>(this.transactions.set(++this.ids,e),this.ids)))}postMessage(e,t){var r;null==(r=this.worker)||r.postMessage(e,t)}create(e){return ow(this,null,(function*(){if(this.ready)return this.ready;e||(e=this.name),console.time("createWorker_".concat(e));let t=rG(),r=new Worker("string"==typeof t?t:yield t,{name:e});return this.worker=r,this.ready=new Promise(((t,i)=>ow(this,null,(function*(){r.onmessage=r=>{let{data:{id:o,type:n,payload:a}}=r;var s;if(o)null==(s=this.transactions.get(o))||s(a),this.transactions.delete(o);else switch(n){case"error":console.timeEnd("createWorker_".concat(e)),console.warn("worker error:",a),i(a);break;case"ready":console.timeEnd("createWorker_".concat(e)),t(this);break;case"updateAFSM":if(a.value){let e="string"==typeof a.old?a.old:"".concat(a.old.action,"ing"),t="string"==typeof a.value?a.value:"".concat(a.value.action,"ing");console.log(uN(),a.group,a.name,e,"👉",t)}break;case"log":console.log(a);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:a}))}},r.postMessage({wasm:yield iG(),flag:Jj},this.ports)}))))}))}destroy(){var e;console.log("destroy worker",this.name),delete this.ready,null==(e=this.worker)||e.terminate()}},vG=class{constructor(e,t,r){this.worker=e,rw(this,"channel",new MessageChannel),rw(this,"ready"),this.ready=new Promise(((e,r)=>{this.worker.postMessage({id:this.worker.addTransaction(e),payload:t},[this.channel.port2])})).then((e=>(0===e.err&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),e)))}postMessage(){this.channel.port1.postMessage(...arguments)}destroy(){0==--this.worker.sessionCount&&this.worker.destroy()}},yG=new class e extends EG{constructor(){super("main"),rw(this,"switchValue",new Map),rw(this,"extendChannel"),rw(this,"sessionCount",0)}setSwitchValue(e,t){var r;this.switchValue.set(e,t),null==(r=this.extendChannel)||r.port1.postMessage([e,t])}create(){return ow(this,null,(function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield iw(e.prototype,this,"create").call(this),this.switchValue.forEach(((e,t)=>{this.extendChannel.port1.postMessage([t,e])})),this)}))}};function TG(e){return ow(this,null,(function*(){yield yG.create(),WO.emit(GO.JOIN_SEND_CMD,{room:this});let t=new vG(yG,e,(e=>{let r=e.data;if("string"==typeof r)this.onWorkerEvent(r);else if(null==r)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:e,payload:t}=r;this.onWorkerEvent(e,t)}})),{err:r,data:i}=yield t.ready;if("number"==typeof r){if(WO.emit(GO.JOIN_RECEIVED_CMD_RES,{room:this,code:r}),0===r)return Object.assign(this,i,{session:t});throw new pw({code:uw.JOIN_ROOM_FAILED,extraCode:Number(r),message:sL({key:iL.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r,errorMsg:""}})})}throw r}))}function IG(e){return ow(this,null,(function*(){yG.setSwitchValue("useAINS",e)}))}function AG(e){return ow(this,null,(function*(){yG.setSwitchValue("useV2",e)}))}function SG(e){let t=new MediaStreamTrackGenerator({kind:"audio"});e.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:e.tinyId,writable:t.writable}},[t.writable])}function RG(e){return ow(this,null,(function*(){var t;this._log.info("pull video",e);let r=Date.now(),i=0,o=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:e.mediaType,tinyId:e.tinyId}},[o.port1]),(t=e.stat).framesReceived||(t.framesReceived=0),FU(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=Object.defineProperties(aV(),{postMessage:{value:e.postMessage.bind(e)},port:{get:()=>e,set(t){e.onmessage=DU,e.onmessageerror=DU,e=t,i()}}});function i(){e.onmessage=i=>{i.data?i.ports.length||t?r.next(i):r.next(i.data):(r.complete(),e.close())},e.onmessageerror=t=>{r.error(t),e.close()}}return i(),r}(o.port2),HV(vV(e,PP.INIT)),WF((t=>{let{data:o,packetsReceived:n}=t;e.stat.packetsReceived=n,e.stat.framesReceived++,i++;let a,s=31&o[4];if(i<=10){let e=Array.from(o.slice(0,10)).map((e=>e.toString(16).padStart(2,"0"))).join(" ");this._log.info("Frame ".concat(i," - Size: ").concat(o.length," bytes, Type: ").concat(s,", Timestamp: ").concat(Date.now()-r,"ms First 10 bytes: ").concat(e))}switch(s){case 5:case 7:a="key";break;default:a="delta"}e.isAvailable?e.decodeFrame({data:o.buffer,type:a,timestamp:1e3*(Date.now()-r)}):console.warn("track is not available")}),(()=>{}),(()=>{o.port2.postMessage(null),o.port2.close()})))}))}Object.defineProperties(window,{useAINS:{set:IG},useWt:{set:function(e){return ow(this,null,(function*(){yG.setSwitchValue("useWt",e)}))}},enableDebug:{set(e){console.debug=e?Qj:()=>{},yG.setSwitchValue("enableDebug",e)}},useV2:{set:AG},dump:{value(){if(uG||(console.warn("dump audio will be activated at next time join room"),uG=[]),!uG.length)return void console.warn("no audio data to dump,try it later");let e=[];return uG.forEach((t=>{e.push(new Uint16Array([t.length])),e.push(t)})),sG(new Blob(e),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"audio",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2e3,r=[],i=new Promise((i=>{let o=new MessageChannel;yG.extendChannel.port1.postMessage(["dump",e],[o.port1]),o.port2.onmessage=n=>{let{data:a}=n;console.log(a),r.push(a),r.length>t&&(o.port2.onmessage=null,yG.extendChannel.port1.postMessage(["dump",e]),o.port2.close(),i(new Blob(r)))}}));return sG(i,{fileName:e,extensions:[".pcm"]})}},hardDec:{set(e){switch(e){case!0:Jj.useHardDecoder="prefer-hardware";break;case!1:Jj.useHardDecoder="prefer-software";break;default:Jj.useHardDecoder="no-preference"}}}});var bG=[];function wG(e){var t;let r=aV();if("joined"!==this.state)throw new Error("Room is not joined");if("publish"===e.state)return;for(let l=0;l<=bG.length;l++)if(!bG[l]){bG[l]=this,this.index=l;break}let i=e.profile;this._log.info("start push audio",this.index,i);let o=new MessageChannel,n=e.enableEncodeFrame?new MessageChannel:null;null==(t=this.session)||t.postMessage({cmd:"pushAudio",payload:Xb({index:this.index},i)},n?[o.port2,n.port2]:[o.port2]),o.port1.onmessage=t=>{null==t.data||("number"==typeof t.data?r.next(t.data):n&&n.port1.postMessage($b(Xb({},t.data),{data:new Uint8Array(e.encodeFrame({data:t.data.data.buffer,timestamp:t.data.timestamp}).data)})))};let a,s=new MediaStream,c=e=>{let t=s.getAudioTracks()[0];t&&(a.disconnect(),s.removeTrack(t)),s.addTrack(e),this._log.info("push audio track:",e.readyState,e.getSettings().deviceId),a=Px().createMediaStreamSource(s),a.connect(oG.worklet,0,this.index)};FU(vV(e,"output-media-track-changed"),HV(vV(e,"ready")),WF(c,console.error,(()=>{this._log.info("stop push audio",i),e.volume=0,a.disconnect(),bG[this.index]=null,n&&n.port1.postMessage(null),o.port1.postMessage(null)}))),FU(r,jF((t=>e.volume=t)),yF(sB(1e3)),WF((()=>{e.volume=0}))),c(e.outMediaTrack)}var CG=class{constructor(e,t,r,i){this.localTrack=e,this.type=t,this.config=r,this.port=i,rw(this,"track"),rw(this,"label"),rw(this,"insertKeyFrame",!0),rw(this,"session"),rw(this,"tsMap",new Map),e._log.info("create Video Encoder",r)}trans(e,t,r){return ow(this,null,(function*(){let i=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});t.signal.addEventListener("abort",(()=>{i.encoder.close()}));let o=0;return e.pipeThrough(new TransformStream({transform:(e,t)=>{"configured"===i.encoder.state&&(this.tsMap.set(o,Date.now()),this.encode(e),o++,t.enqueue(e))}}),t)}))}encode(e){var t,r;null==(r=null==(t=this.session)?void 0:t.encoder)||r.encode(e,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(e,t,r){return ow(this,null,(function*(){let i=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=i;let o=0;e.pipeTo(new WritableStream({write:e=>{"configured"===i.encoder.state&&(o<10&&this.localTrack.log.info("capture ".concat(this.label," track frame:"),o,Date.now(),e.timestamp,e.displayWidth,e.displayHeight),(e.displayWidth!==this.config.width||e.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",e.displayWidth,e.displayHeight,this.config.width,this.config.height),this.configure({width:e.displayWidth,height:e.displayHeight},i)),this.tsMap.set(o,Date.now()),this.encode(e),o<10&&this.localTrack.log.info("encode ".concat(this.label," track frame:"),o),o++,e.close())}}),t).catch((e=>{this.localTrack.log.warn(e),i.encoder.close()}))}))}recreate(e,t){return ow(this,null,(function*(){let r=0,i=new VideoEncoder({output:i=>{let o=this.tsMap.get(r);if(this.tsMap.delete(i.timestamp),r<10&&(0===r&&0===t.recreateCount&&WO.emit(GO.SEND_FIRST_VIDEO_FRAME,{room:e}),this.localTrack.log.info("encoded ".concat(this.label," track frame:"),r,Date.now(),i.timestamp)),r++,t.frameEncoded=r,!1===this.track.enabled)return;let n=null;if(this.localTrack.enableEncodeFrame){n=new Uint8Array(i.byteLength),i.copyTo(n);let e=this.localTrack.encodeFrame({data:n.buffer},3===this.type);n=new Uint8Array(e.data)}n?(this.localTrack.stat.bytesSent+=n.length,this.port.postMessage({chunk:{type:i.type,timestamp:i.timestamp,data:n,duration:i.duration},timestamp:o},[n.buffer])):(this.localTrack.stat.bytesSent+=i.byteLength,this.port.postMessage({chunk:i,timestamp:o}))},error:r=>{this.localTrack.log.warn(r,this.config),t.recreateCount++,setTimeout((()=>this.recreate(e,t)),100)}});return t.encoder=i,yield this.configure(null,t),t}))}configure(e,t){return ow(this,null,(function*(){var r;e&&Object.assign(this.config,e),null==(r=t.encoder)||r.configure(this.config)}))}close(){this.port.postMessage(null),this.port.close()}};function DG(e,t){return ow(this,null,(function*(){let r=2===e.mediaType,i=r?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Jj.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:1e3*t.profile.bitrate},n=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[n.port1]);let a=new CG(e,t.type,o,n.port2);return n.port2.onmessage=e=>{if(260===e.data)a.insertKeyFrame=!0;else if(!r){let{bitrate:t}=e.data;OD({configureBr:[e.data.bitrate,t]}),a.session&&a.configure({bitrate:t},a.session)}},this._log.info("start push",i,t),a}))}function NG(e){return ow(this,null,(function*(){var t;let r=2===e.mediaType,i=r?"screen":"video",o={type:r?7:2,profile:e.profile,trackType:r?"screen":"camera",crypto:!(null==(t=e.manager)||!t.encodePipeline[0])};!r&&e.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(o.trackType="canvas");let{trackType:n}=o,{width:a,height:s}=e.outMediaTrack.getSettings();o.profile.width=a,o.profile.height=s;let c=yield DG.call(this,e,o);this._log.info("VideoEncoder created",o);let l,d=t=>ow(this,null,(function*(){if(null==l||l.abort("track changed"),!t)return;l=new AbortController;let{width:r,height:o,displaySurface:a}=t.getSettings();r&&(c.config.width=r),o&&(c.config.height=o);let s,d=zN.match(/Chrome\/(\d+)/);"114"===(null==d?void 0:d[1])&&"browser"===a&&delete c.config.hardwareAcceleration,this._log.info("push",i,"track:",t.readyState,t.getSettings()),s="undefined"==typeof MediaStreamTrackProcessor||t instanceof CanvasCaptureMediaStreamTrack?new ReadableStream({start(t){e.on("render",(r=>{if(0!==e.player.mode)try{t.enqueue(new VideoFrame(r,{timestamp:1e3*performance.now()}))}catch(i){console.warn(i)}}))},pull(t){return ow(this,null,(function*(){if(0===e.player.mode&&EP()&&e.player.element)return new Promise((r=>{e.player.element.requestVideoFrameCallback(((i,o)=>{try{let r=new VideoFrame(e.player.element);t.enqueue(r)}catch(n){console.warn(n)}r()}))}))}))}}):new MediaStreamTrackProcessor({track:t}).readable;let u="small"in e&&e.small;return u?(this.smallEncoder||(this.smallEncoder=yield DG.call(this,e,{profile:u,type:3,trackType:n})),this.smallEncoder.track=t,this.smallEncoder.label="small",s=yield this.smallEncoder.trans(s,l,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),c.track=t,c.label=i,c.start(s,l,this)}));return FU(vV(e,"output-media-track-changed"),HV(vV(e,"ready")),WF(d,console.error,(()=>{var e;this._log.info("stop push",i,o),l.abort("unpublish"),c.close(),null==(e=this.smallEncoder)||e.close()}))),d(e.outMediaTrack)}))}var kG=class e extends PP{constructor(t){var r,i;super(null!=(i=null==(r=t.roomid)?void 0:r.toString())?i:t.name,"volumeEvaluation"),this.room=t,rw(this,"enableInBackground",!1),rw(this,"interval",400),t.on("joined",(()=>{this.emit(e.INTERVALCHANGED,this.interval)})),FU(vV(this,e.INTERVALCHANGED),EF((e=>"joined"===this.room.state?this.room.fromWorker("getAudioEnergy",e):FU((e=>t=>{let r=0,i=performance.now();FU(aB,hF((t=>(t-i)/e|0)),VV((e=>e!=r&&(r=e,!0))))(t)})(e),hF((()=>[]))))),WF((e=>{e.forEach((e=>{this.room.remotePublishedUserMap.has(e.userId)&&(this.room.remotePublishedUserMap.get(e.userId).remoteAudioTrack.volume=e.volume)})),(!document.hidden||this.enableInBackground)&&this.state==PP.ON&&this.room.emit("audio-volume",e)})))}start(t,r){this.interval=t,this.enableInBackground=r,this.emit(e.INTERVALCHANGED,this.interval)}stop(){}};rw(kG,"INTERVALCHANGED","intervalChanged"),tw([OP([PP.INIT,PP.OFF],PP.ON)],kG.prototype,"start",1),tw([OP([],PP.OFF)],kG.prototype,"stop",1);var OG=kG,MG=class extends Yj{constructor(e){super(e),rw(this,"index",0),rw(this,"session"),rw(this,"tinyid"),rw(this,"roomid"),rw(this,"openid"),rw(this,"socketid"),rw(this,"relayip"),rw(this,"clientip"),rw(this,"remotePublishedUserMap",new Map),rw(this,"bussinessInfo"),rw(this,"token"),rw(this,"audioVolumeEvalution",new OG(this)),rw(this,"enableAIVoice",IG),rw(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:FO(),uint32_device_type:0,str_os_verion:BO(),uint32_link_type:1,str_client_version:Tw,uint32_net_type:Gw[Ew.getNetworkType()],ua:navigator.userAgent,version:""}}),rw(this,"joinAbortController",new AbortController),rw(this,"smallAbortCtrl"),rw(this,"smallEncoder"),e.tinyId&&(this.tinyId=e.tinyId,AG(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return ow(this,null,(function*(){}))}getLogger(){return this._log}postMessage(e,t){this.session&&(e?"string"==typeof e?this.session.postMessage({cmd:e,payload:t}):this.session.postMessage(e,t):this.session.postMessage(null))}sendMessage(e,t){return new Promise(((r,i)=>{"joined"!=this.state&&i("join room first");let o=new MessageChannel;this.postMessage({cmd:e,payload:t},[o.port1]),o.port2.onmessageerror=i,o.port2.onmessage=e=>{o.port2.close(),r(e.data)}}))}fromWorker(e,t){if("joined"!=this.state)throw"join room first";return r=>{var i;let o=new MessageChannel;o.port2.onmessage=e=>{e.data?r.next(e.data):r.complete()},o.port2.onmessageerror=e=>r.error(e),r.defer((()=>{o.port2.postMessage(null),o.port2.close()})),null==(i=this.session)||i.postMessage({cmd:e,payload:t},[o.port1])}}switchRole(e){return ow(this,null,(function*(){if(e!==this.role)return this._log.info("switchRole() => switch role to: ".concat(e)),"audience"==e&&this.unpublish(...this.localTracks),this.sendMessage("switchRole","audience"==e?21:20).then((t=>{this.role=e}))}))}join(e,t,r){return ow(this,null,(function*(){var i,o,n;let a=Ew.getEnv(),s=TL(),c={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:r,params:e,proxy_wt:null==(i=this.proxy_wt)?void 0:i.replace("https://",""),proxy_ws:null==(o=this.proxy_ws)?void 0:o.replace("wss://",""),proxy_cloud:null!=(n=this.scheduleResult.iceServers)&&n.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:a,osName:PO(),browserInfo:TL(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:Tw,browserVersion:s.browserName+s.browserVersion,closeLocalMedia:!0,trtcscene:"live"===t?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield TG.call(this,c),console.log(this),oG.playAudio((e=>this.postMessage({cmd:"setAudioWorkletPort"},[e]))),this.checkDestroy()}))}leave(){return ow(this,null,(function*(){this.remotePublishedUserMap.forEach((e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()})),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach(((e,t)=>t.unpublish())),this.localTracks.clear()}))}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,t)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return ow(this,null,(function*(){FU((e=>ow(this,null,(function*(){let t=new MessageChannel;t.port2.onmessage=r=>{r.data?e.next({data:r.data,port:t.port2}):e.complete()},t.port2.onmessageerror=t=>e.error(t),e.defer((()=>{t.port2.postMessage(null),t.port2.close()})),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[t.port1])}))),HV(vV(this,"left")),WF((e=>{let{data:t,port:r}=e,i=this.audioManager.decodePipeline[0]({frame:{data:t.data.buffer}});r.postMessage($b(Xb({},t),{data:new Uint8Array(i.data)}),[i.data])})))}))}onWorkerEvent(e,t){switch("network-quality"!==e&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(t)),e){case GO.RECEIVED_PUBLISHED_USER_LIST:return void WO.emit(e,Xb({room:this},t));case"1":if(t.userId===this.userId)return;return void this.emit("peer-join",t);case"2":return void this.emit("peer-leave",t);case"3":let r=new wj(this,t);return this.remotePublishedUserMap.set(t.userId,r),void this.emit("remote-published",r);case"5":{let e=t,r=this.remotePublishedUserMap.get(e);r&&(r.remoteVideoTrack.close(),r.remoteAuxiliaryTrack.close(),r.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(e),this.emit("remote-unpublished",r))}return;case"banned":switch(t){case 8:return void this.emit("banned",{reason:"kick",message:""});case 2:case 6:case 4:return void this.emit("banned",{reason:"banned",message:""});case 7:case 5:return void this.emit("banned",{reason:"room_disband",message:""})}break;case"6":{let{prevMuteState:e,muteState:r,flag:i}=t,o=this.remotePublishedUserMap.get(r.userId);if(!o)return void this.emit("remote-publish-state-changed",t);o.flag=i}return WO.emit(GO.REMOTE_PUBLISH_STATE_CHANGED,Xb({room:this},t)),void this.emit("remote-publish-state-changed",t);case"7":return void(this.localPublishFlag!==t.flag&&(this.localPublishFlag=t.flag,this.emit("local-publish-flag-changed",t.flag)));case"network-quality":this.quality=Xb({},t);let{uplinkLoss:i,uplinkRTT:o,uplinkInfo:n,downlinkInfo:a,msg_down_stream_info:s}=t,c={str_sdk_version:Tw,uint64_datetime:Date.now(),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:Gw[AD()]},msg_event_msg:WB(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:n,msg_down_stream_info:s};WO.emit(GO.HEARTBEAT_REPORT,{room:this,report:c}),this.emit("heartbeat-report",c),WO.emit(GO.NETWORK_QUALITY,{room:this,uplink:{rtt:o,loss:i},downlinks:a}),delete t.downlinkInfo;break;case"signal-connection-state-changed":return void WO.emit(GO.SIGNAL_CONNECTION_STATE_CHANGED,Xb({room:this},t))}this.emit(e,t)}sendStartPublishCDN(e,t){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,t&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,t){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,t&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(this,null,(function*(){t.forEach((e=>this.localTracks.add(e)));let e=t.reduce(((e,t)=>t.mediaType|e),0),r=this.sendMessage("publish",e).then((e=>0!==e.err?Promise.reject(e.err):e)),i=0;yield Promise.all(t.map((e=>ow(this,null,(function*(){if(1===(yield r,e.muted&&(i|=e.mediaType),zP(e,e).add("mute",(()=>{this.postMessage("mute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})})).add("unmute",(()=>{this.postMessage("unmute",{mediaType:e.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})})),e.mediaType))wG.call(this,e);else yield NG.call(this,e)}))))),i&&this.postMessage("mute",{mediaType:i,srctinyid:this.tinyid,userId:this.openid,remove:!0})}))}unpublish(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(this,null,(function*(){t.forEach(KP),t.forEach((e=>this.localTracks.delete(e)))}))}subscribe(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(this,null,(function*(){let e=t.reduce(((e,t)=>t.mediaType|e),0),{userId:r,tinyId:i,streamType:o}=t[0],n=this.remotePublishedUserMap.get(r),a=Xb({},n.subscribeState),s=Object.assign(new zM,a);s.mediaType|=e,WO.emit(GO.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:n,subscribeState:s});let c=yield this.sendMessage("subscribe",{mediaType:s.mediaType,userId:r,srctinyid:i,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter((e=>s.mediaType&e)).map((e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]})))}});console.dir("subscribe",c),yield Promise.all(t.filter((e=>!e.isSubscribed)).map((e=>1===e.mediaType?SG.call(this,e):RG.call(this,e)))),WO.emit(GO.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:n})}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return ow(this,null,(function*(){let e=0;for(let r of t)e|=r.mediaType;if(t.length){let{userId:r,streamType:i,tinyId:o}=t[0];yield this.sendMessage("unSubscribe",{mediaType:e,srctinyid:o,userId:r});for(let e of t)e.unsubscribe();WO.emit(GO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:i,remotePublishedUser:this.remotePublishedUserMap.get(r)})}}))}enableSmall(e){return ow(this,null,(function*(){var t;if(e){if(this.videoManager.smallTrack){let e=this.videoManager.cameraTrack;this.smallEncoder=yield DG.call(this,e,{profile:e.small,type:3,trackType:"camera"});let t=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(t,this.smallAbortCtrl,this),this._log.info("push small")}}else null==(t=this.smallAbortCtrl)||t.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)}))}changeType(e,t){let r=this.remotePublishedUserMap.get(t.userId);if(!r)return;let i=e?8:4;if(r.remoteVideoTrack.mediaType===i)return;let o={srctinyid:r.tinyId,mediaType:i,userId:t.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter((e=>i&e)).map((e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]})))}};r.remoteVideoTrack.mediaType=o.mediaType,this.postMessage("changetype",o)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};tw([vU(MG.prototype.afterJoin),OP(["left",PP.INIT],"joined"),yU((e=>{let t=new Cj;return function(r,i,o){return ow(this,null,(function*(){let n=String(r.roomId||r.strRoomId);if(this.userId=r.userId,this.sdkAppId=r.sdkAppId,this.userSig=r.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=i,r.privateMapKey=r.privateMapKey||"",this.isJoined)throw new pw({code:uw.INVALID_OPERATION,message:sL({key:iL.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new pw({code:uw.INVALID_OPERATION,message:sL({key:iL.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:n}),this.role=21===r.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(n," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),WO.emit(GO.JOIN_START,{room:this,roomId:n,params:r});let a=Ew.getEnv();a||(a=Bw.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Zw.OLD_CLOUD_LADDER)?a=Bw.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Zw.WEBRTC)&&(a=Bw.WEBRTC))),qP.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),XO.checkSystemRequirementsInternal(o).then((e=>{this.checkSystemResult=e,Dj.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ew.getEnv()&&(yield this.schedule(r,o));let t=yield e.call(this,r,i,o);return this.roomId=n,this._joinedTimestamp=Ew.performanceNow(),WO.emit(GO.JOIN_SUCCESS,{room:this}),30===o&&!r.component&&qP.uploadEvent({log:"stat-conv-".concat(Number(AO),"-").concat(location.hostname),userId:this.userId}),t}catch(rM){throw t.delete({room:this,roomId:n}),WO.emit(GO.JOIN_FAILED,{room:this,error:rM}),rM}}))}}))],MG.prototype,"join",1),tw([OP("joined","left",{ignoreError:!0}),yU((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return ow(this,null,(function*(){WO.emit(GO.LEAVE_START,{room:this}),yield e.call(this,...r),WO.emit(GO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))}))],MG.prototype,"leave",1),tw([bU(),yU((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return ow(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(r=r.filter((e=>e.outMediaTrack&&"ready"===e.state)),!r.length))return;WO.emit("61",{room:this});let t=e.apply(this,r);return Promise.all(r.map((e=>e.publish(this,t))))}))}))],MG.prototype,"publish",1),tw([bU(),yU((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];let o=e.apply(this,r);return r.forEach((e=>e.unpublish())),o}))],MG.prototype,"unpublish",1),tw([function(e){return function(t,r,i){let o=i.value,n=t=>e(...t);return i.value=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];let i=RU.get(this)||new Map,a=i.get(n(t))||new AU;return i.set(n(t),a),RU.set(this,i),a.push({fn:o,args:t,context:this})},i}}((function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].userId})),yU((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];let o=e.apply(this,r);return r.forEach((e=>!e.isSubscribed&&e.subscribe(o))),o}))],MG.prototype,"subscribe",1);var LG=MG;bj.frameWorkType=37,bj.create=function(e){let t=bj._create.call(this,LG,e);return t._use(wH,null==e?void 0:e.assetsPath),null!=e&&e.assetsPath&&(Jj.assetsPath=null==e?void 0:e.assetsPath),console.log("trtc wasm sdk:",Tw,"created",Jj),t};var PG=bj.prototype._setCurrentSpeaker;return Object.assign(bj.prototype,{_setCurrentSpeaker(e){PG.call(this,e);let t=Px();return null!=t&&t.setSinkId?t.setSinkId(e):Promise.reject("not support")},_enableVideoDecodeFallback(e,t){return ow(this,null,(function*(){return this.startPlugin(wH.Name,{type:"webCodecs",renderer:"videoFrame",track:e,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise(((t,r)=>{FU(vV(e,"decode-downgrade-state-changed"),VV((e=>"STARTED"===e.state)),BV(1),GF(1e4),HV(vV(e,PP.INIT)),WF(t,r))}))}))}}),gP(37),bj}));
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 r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var r=function(e){return e&&e.Math===Math&&e},n=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof t&&t)||r("object"==typeof t&&t)||function(){return this}()||Function("return this")(),o={},s=function(e){try{return!!e()}catch(t){return!0}},a=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),c=!s((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),l=c,d=Function.prototype.call,u=l?d.bind(d):function(){return d.apply(d,arguments)},h={},p={}.propertyIsEnumerable,m=Object.getOwnPropertyDescriptor,_=m&&!p.call({1:2},1);h.f=_?function(e){var t=m(this,e);return!!t&&t.enumerable}:p;var f,g,E=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=c,v=Function.prototype,y=v.call,S=T&&v.bind.bind(y,y),I=T?S:function(e){return function(){return y.apply(e,arguments)}},A=I,R=A({}.toString),C=A("".slice),b=function(e){return C(R(e),8,-1)},k=s,D=b,w=Object,N=I("".split),O=k((function(){return!w("z").propertyIsEnumerable(0)}))?function(e){return"String"===D(e)?N(e,""):w(e)}:w,M=function(e){return null==e},P=M,L=TypeError,x=function(e){if(P(e))throw new L("Can't call method on "+e);return e},V=O,U=x,F=function(e){return V(U(e))},B="object"==typeof document&&document.all,H=void 0===B&&void 0!==B?function(e){return"function"==typeof e||e===B}:function(e){return"function"==typeof e},W=H,G=function(e){return"object"==typeof e?null!==e:W(e)},j=n,J=H,q=function(e,t){return arguments.length<2?(i=j[e],J(i)?i:void 0):j[e]&&j[e][t];var i},K=I({}.isPrototypeOf),z=n.navigator,Y=z&&z.userAgent,X=Y?String(Y):"",Q=n,Z=X,$=Q.process,ee=Q.Deno,te=$&&$.versions||ee&&ee.version,ie=te&&te.v8;ie&&(g=(f=ie.split("."))[0]>0&&f[0]<4?1:+(f[0]+f[1])),!g&&Z&&(!(f=Z.match(/Edge\/(\d+)/))||f[1]>=74)&&(f=Z.match(/Chrome\/(\d+)/))&&(g=+f[1]);var re=g,ne=re,oe=s,se=n.String,ae=!!Object.getOwnPropertySymbols&&!oe((function(){var e=Symbol("symbol detection");return!se(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),ce=ae&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,le=q,de=H,ue=K,he=Object,pe=ce?function(e){return"symbol"==typeof e}:function(e){var t=le("Symbol");return de(t)&&ue(t.prototype,he(e))},me=String,_e=function(e){try{return me(e)}catch(t){return"Object"}},fe=H,ge=_e,Ee=TypeError,Te=function(e){if(fe(e))return e;throw new Ee(ge(e)+" is not a function")},ve=Te,ye=M,Se=function(e,t){var i=e[t];return ye(i)?void 0:ve(i)},Ie=u,Ae=H,Re=G,Ce=TypeError,be={exports:{}},ke=n,De=Object.defineProperty,we=function(e,t){try{De(ke,e,{value:t,configurable:!0,writable:!0})}catch(i){ke[e]=t}return t},Ne=n,Oe=we,Me="__core-js_shared__",Pe=be.exports=Ne[Me]||Oe(Me,{});(Pe.versions||(Pe.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Le=be.exports,xe=Le,Ve=function(e,t){return xe[e]||(xe[e]=t||{})},Ue=x,Fe=Object,Be=function(e){return Fe(Ue(e))},He=Be,We=I({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return We(He(e),t)},je=I,Je=0,qe=Math.random(),Ke=je(1..toString),ze=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Ke(++Je+qe,36)},Ye=Ve,Xe=Ge,Qe=ze,Ze=ae,$e=ce,et=n.Symbol,tt=Ye("wks"),it=$e?et.for||et:et&&et.withoutSetter||Qe,rt=function(e){return Xe(tt,e)||(tt[e]=Ze&&Xe(et,e)?et[e]:it("Symbol."+e)),tt[e]},nt=u,ot=G,st=pe,at=Se,ct=function(e,t){var i,r;if("string"===t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;if(Ae(i=e.valueOf)&&!Re(r=Ie(i,e)))return r;if("string"!==t&&Ae(i=e.toString)&&!Re(r=Ie(i,e)))return r;throw new Ce("Can't convert object to primitive value")},lt=TypeError,dt=rt("toPrimitive"),ut=function(e,t){if(!ot(e)||st(e))return e;var i,r=at(e,dt);if(r){if(void 0===t&&(t="default"),i=nt(r,e,t),!ot(i)||st(i))return i;throw new lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ct(e,t)},ht=ut,pt=pe,mt=function(e){var t=ht(e,"string");return pt(t)?t:t+""},_t=G,ft=n.document,gt=_t(ft)&&_t(ft.createElement),Et=function(e){return gt?ft.createElement(e):{}},Tt=Et,vt=!a&&!s((function(){return 7!==Object.defineProperty(Tt("div"),"a",{get:function(){return 7}}).a})),yt=a,St=u,It=h,At=E,Rt=F,Ct=mt,bt=Ge,kt=vt,Dt=Object.getOwnPropertyDescriptor;o.f=yt?Dt:function(e,t){if(e=Rt(e),t=Ct(t),kt)try{return Dt(e,t)}catch(i){}if(bt(e,t))return At(!St(It.f,e,t),e[t])};var wt={},Nt=a&&s((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ot=G,Mt=String,Pt=TypeError,Lt=function(e){if(Ot(e))return e;throw new Pt(Mt(e)+" is not an object")},xt=a,Vt=vt,Ut=Nt,Ft=Lt,Bt=mt,Ht=TypeError,Wt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt="enumerable",Jt="configurable",qt="writable";wt.f=xt?Ut?function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),"function"==typeof e&&"prototype"===t&&"value"in i&&qt in i&&!i[qt]){var r=Gt(e,t);r&&r[qt]&&(e[t]=i.value,i={configurable:Jt in i?i[Jt]:r[Jt],enumerable:jt in i?i[jt]:r[jt],writable:!1})}return Wt(e,t,i)}:Wt:function(e,t,i){if(Ft(e),t=Bt(t),Ft(i),Vt)try{return Wt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ht("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Kt=wt,zt=E,Yt=a?function(e,t,i){return Kt.f(e,t,zt(1,i))}:function(e,t,i){return e[t]=i,e},Xt={exports:{}},Qt=a,Zt=Ge,$t=Function.prototype,ei=Qt&&Object.getOwnPropertyDescriptor,ti=Zt($t,"name"),ii={EXISTS:ti,PROPER:ti&&"something"===function(){}.name,CONFIGURABLE:ti&&(!Qt||Qt&&ei($t,"name").configurable)},ri=H,ni=Le,oi=I(Function.toString);ri(ni.inspectSource)||(ni.inspectSource=function(e){return oi(e)});var si,ai,ci,li=ni.inspectSource,di=H,ui=n.WeakMap,hi=di(ui)&&/native code/.test(String(ui)),pi=ze,mi=Ve("keys"),_i=function(e){return mi[e]||(mi[e]=pi(e))},fi={},gi=hi,Ei=n,Ti=G,vi=Yt,yi=Ge,Si=Le,Ii=_i,Ai=fi,Ri="Object already initialized",Ci=Ei.TypeError,bi=Ei.WeakMap;if(gi||Si.state){var ki=Si.state||(Si.state=new bi);ki.get=ki.get,ki.has=ki.has,ki.set=ki.set,si=function(e,t){if(ki.has(e))throw new Ci(Ri);return t.facade=e,ki.set(e,t),t},ai=function(e){return ki.get(e)||{}},ci=function(e){return ki.has(e)}}else{var Di=Ii("state");Ai[Di]=!0,si=function(e,t){if(yi(e,Di))throw new Ci(Ri);return t.facade=e,vi(e,Di,t),t},ai=function(e){return yi(e,Di)?e[Di]:{}},ci=function(e){return yi(e,Di)}}var wi={set:si,get:ai,has:ci,enforce:function(e){return ci(e)?ai(e):si(e,{})},getterFor:function(e){return function(t){var i;if(!Ti(t)||(i=ai(t)).type!==e)throw new Ci("Incompatible receiver, "+e+" required");return i}}},Ni=I,Oi=s,Mi=H,Pi=Ge,Li=a,xi=ii.CONFIGURABLE,Vi=li,Ui=wi.enforce,Fi=wi.get,Bi=String,Hi=Object.defineProperty,Wi=Ni("".slice),Gi=Ni("".replace),ji=Ni([].join),Ji=Li&&!Oi((function(){return 8!==Hi((function(){}),"length",{value:8}).length})),qi=String(String).split("String"),Ki=Xt.exports=function(e,t,i){"Symbol("===Wi(Bi(t),0,7)&&(t="["+Gi(Bi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Pi(e,"name")||xi&&e.name!==t)&&(Li?Hi(e,"name",{value:t,configurable:!0}):e.name=t),Ji&&i&&Pi(i,"arity")&&e.length!==i.arity&&Hi(e,"length",{value:i.arity});try{i&&Pi(i,"constructor")&&i.constructor?Li&&Hi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Ui(e);return Pi(r,"source")||(r.source=ji(qi,"string"==typeof t?t:"")),e};Function.prototype.toString=Ki((function(){return Mi(this)&&Fi(this).source||Vi(this)}),"toString");var zi=Xt.exports,Yi=H,Xi=wt,Qi=zi,Zi=we,$i=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Yi(i)&&Qi(i,o,r),r.global)n?e[t]=i:Zi(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:Xi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},er={},tr=Math.ceil,ir=Math.floor,rr=Math.trunc||function(e){var t=+e;return(t>0?ir:tr)(t)},nr=rr,or=function(e){var t=+e;return t!=t||0===t?0:nr(t)},sr=or,ar=Math.max,cr=Math.min,lr=function(e,t){var i=sr(e);return i<0?ar(i+t,0):cr(i,t)},dr=or,ur=Math.min,hr=function(e){var t=dr(e);return t>0?ur(t,9007199254740991):0},pr=hr,mr=function(e){return pr(e.length)},_r=F,fr=lr,gr=mr,Er=function(e){return function(t,i,r){var n=_r(t),o=gr(n);if(0===o)return!e&&-1;var s,a=fr(r,o);if(e&&i!=i){for(;o>a;)if((s=n[a++])!=s)return!0}else for(;o>a;a++)if((e||a in n)&&n[a]===i)return e||a||0;return!e&&-1}},Tr={includes:Er(!0),indexOf:Er(!1)},vr=Ge,yr=F,Sr=Tr.indexOf,Ir=fi,Ar=I([].push),Rr=function(e,t){var i,r=yr(e),n=0,o=[];for(i in r)!vr(Ir,i)&&vr(r,i)&&Ar(o,i);for(;t.length>n;)vr(r,i=t[n++])&&(~Sr(o,i)||Ar(o,i));return o},Cr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],br=Rr,kr=Cr.concat("length","prototype");er.f=Object.getOwnPropertyNames||function(e){return br(e,kr)};var Dr={};Dr.f=Object.getOwnPropertySymbols;var wr=q,Nr=er,Or=Dr,Mr=Lt,Pr=I([].concat),Lr=wr("Reflect","ownKeys")||function(e){var t=Nr.f(Mr(e)),i=Or.f;return i?Pr(t,i(e)):t},xr=Ge,Vr=Lr,Ur=o,Fr=wt,Br=function(e,t,i){for(var r=Vr(t),n=Fr.f,o=Ur.f,s=0;s<r.length;s++){var a=r[s];xr(e,a)||i&&xr(i,a)||n(e,a,o(t,a))}},Hr=s,Wr=H,Gr=/#|\.prototype\./,jr=function(e,t){var i=qr[Jr(e)];return i===zr||i!==Kr&&(Wr(t)?Hr(t):!!t)},Jr=jr.normalize=function(e){return String(e).replace(Gr,".").toLowerCase()},qr=jr.data={},Kr=jr.NATIVE="N",zr=jr.POLYFILL="P",Yr=jr,Xr=n,Qr=o.f,Zr=Yt,$r=$i,en=we,tn=Br,rn=Yr,nn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Xr:l?Xr[a]||en(a,{}):Xr[a]&&Xr[a].prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=Qr(i,r))&&s.value:i[r],!rn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;tn(o,n)}(e.sham||n&&n.sham)&&Zr(o,"sham",!0),$r(i,r,o,e)}},on={};on[rt("toStringTag")]="z";var sn="[object z]"===String(on),an=H,cn=b,ln=rt("toStringTag"),dn=Object,un="Arguments"===cn(function(){return arguments}()),hn=sn?cn:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(i){}}(t=dn(e),ln))?i:un?cn(t):"Object"===(r=cn(t))&&an(t.callee)?"Arguments":r},pn=hn,mn=String,_n=function(e){if("Symbol"===pn(e))throw new TypeError("Cannot convert a Symbol value to a string");return mn(e)},fn=zi,gn=wt,En=function(e,t,i){return i.get&&fn(i.get,t,{getter:!0}),i.set&&fn(i.set,t,{setter:!0}),gn.f(e,t,i)},Tn=nn,vn=a,yn=I,Sn=Ge,In=H,An=K,Rn=_n,Cn=En,bn=Br,kn=n.Symbol,Dn=kn&&kn.prototype;if(vn&&In(kn)&&(!("description"in Dn)||void 0!==kn().description)){var wn={},Nn=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Rn(arguments[0]),t=An(Dn,this)?new kn(e):void 0===e?kn():kn(e);return""===e&&(wn[t]=!0),t};bn(Nn,kn),Nn.prototype=Dn,Dn.constructor=Nn;var On="Symbol(description detection)"===String(kn("description detection")),Mn=yn(Dn.valueOf),Pn=yn(Dn.toString),Ln=/^Symbol\((.*)\)[^)]+$/,xn=yn("".replace),Vn=yn("".slice);Cn(Dn,"description",{configurable:!0,get:function(){var e=Mn(this);if(Sn(wn,e))return"";var t=Pn(e),i=On?Vn(t,7,-1):xn(t,Ln,"$1");return""===i?void 0:i}}),Tn({global:!0,constructor:!0,forced:!0},{Symbol:Nn})}var Un={},Fn=Rr,Bn=Cr,Hn=Object.keys||function(e){return Fn(e,Bn)},Wn=a,Gn=Nt,jn=wt,Jn=Lt,qn=F,Kn=Hn;Un.f=Wn&&!Gn?Object.defineProperties:function(e,t){Jn(e);for(var i,r=qn(t),n=Kn(t),o=n.length,s=0;o>s;)jn.f(e,i=n[s++],r[i]);return e};var zn,Yn=q("document","documentElement"),Xn=Lt,Qn=Un,Zn=Cr,$n=fi,eo=Yn,to=Et,io="prototype",ro="script",no=_i("IE_PROTO"),oo=function(){},so=function(e){return"<"+ro+">"+e+"</"+ro+">"},ao=function(e){e.write(so("")),e.close();var t=e.parentWindow.Object;return e=null,t},co=function(){try{zn=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;co="undefined"!=typeof document?document.domain&&zn?ao(zn):(t=to("iframe"),i="java"+ro+":",t.style.display="none",eo.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(so("document.F=Object")),e.close(),e.F):ao(zn);for(var r=Zn.length;r--;)delete co[io][Zn[r]];return co()};$n[no]=!0;var lo=Object.create||function(e,t){var i;return null!==e?(oo[io]=Xn(e),i=new oo,oo[io]=null,i[no]=e):i=co(),void 0===t?i:Qn.f(i,t)},uo=rt,ho=lo,po=wt.f,mo=uo("unscopables"),_o=Array.prototype;void 0===_o[mo]&&po(_o,mo,{configurable:!0,value:ho(null)});var fo=function(e){_o[mo][e]=!0},go=Tr.includes,Eo=fo;nn({target:"Array",proto:!0,forced:s((function(){return!Array(1).includes()}))},{includes:function(e){return go(this,e,arguments.length>1?arguments[1]:void 0)}}),Eo("includes");var To,vo,yo,So={},Io=!s((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ao=Ge,Ro=H,Co=Be,bo=Io,ko=_i("IE_PROTO"),Do=Object,wo=Do.prototype,No=bo?Do.getPrototypeOf:function(e){var t=Co(e);if(Ao(t,ko))return t[ko];var i=t.constructor;return Ro(i)&&t instanceof i?i.prototype:t instanceof Do?wo:null},Oo=s,Mo=H,Po=G,Lo=No,xo=$i,Vo=rt("iterator"),Uo=!1;[].keys&&("next"in(yo=[].keys())?(vo=Lo(Lo(yo)))!==Object.prototype&&(To=vo):Uo=!0);var Fo=!Po(To)||Oo((function(){var e={};return To[Vo].call(e)!==e}));Fo&&(To={}),Mo(To[Vo])||xo(To,Vo,(function(){return this}));var Bo={IteratorPrototype:To,BUGGY_SAFARI_ITERATORS:Uo},Ho=wt.f,Wo=Ge,Go=rt("toStringTag"),jo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!Wo(e,Go)&&Ho(e,Go,{configurable:!0,value:t})},Jo=Bo.IteratorPrototype,qo=lo,Ko=E,zo=jo,Yo=So,Xo=function(){return this},Qo=function(e,t,i,r){var n=t+" Iterator";return e.prototype=qo(Jo,{next:Ko(+!r,i)}),zo(e,n,!1),Yo[n]=Xo,e},Zo=I,$o=Te,es=G,ts=function(e){return es(e)||null===e},is=String,rs=TypeError,ns=function(e,t,i){try{return Zo($o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},os=G,ss=x,as=function(e){if(ts(e))return e;throw new rs("Can't set "+is(e)+" as a prototype")},cs=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ns(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return ss(i),as(r),os(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),ls=nn,ds=u,us=H,hs=Qo,ps=No,ms=cs,_s=jo,fs=Yt,gs=$i,Es=So,Ts=ii.PROPER,vs=ii.CONFIGURABLE,ys=Bo.IteratorPrototype,Ss=Bo.BUGGY_SAFARI_ITERATORS,Is=rt("iterator"),As="keys",Rs="values",Cs="entries",bs=function(){return this},ks=function(e,t,i,r,n,o,s){hs(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!Ss&&e&&e in p)return p[e];switch(e){case As:case Rs:case Cs:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Is]||p["@@iterator"]||n&&p[n],_=!Ss&&m||d(n),f="Array"===t&&p.entries||m;if(f&&(a=ps(f.call(new e)))!==Object.prototype&&a.next&&(ps(a)!==ys&&(ms?ms(a,ys):us(a[Is])||gs(a,Is,bs)),_s(a,u,!0)),Ts&&n===Rs&&m&&m.name!==Rs&&(vs?fs(p,"name",Rs):(h=!0,_=function(){return ds(m,this)})),n)if(c={values:d(Rs),keys:o?_:d(As),entries:d(Cs)},s)for(l in c)(Ss||h||!(l in p))&&gs(p,l,c[l]);else ls({target:t,proto:!0,forced:Ss||h},c);return p[Is]!==_&&gs(p,Is,_,{name:n}),Es[t]=_,c},Ds=function(e,t){return{value:e,done:t}},ws=F,Ns=fo,Os=So,Ms=wi,Ps=wt.f,Ls=ks,xs=Ds,Vs=a,Us="Array Iterator",Fs=Ms.set,Bs=Ms.getterFor(Us),Hs=Ls(Array,"Array",(function(e,t){Fs(this,{type:Us,target:ws(e),index:0,kind:t})}),(function(){var e=Bs(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,xs(void 0,!0);switch(e.kind){case"keys":return xs(i,!1);case"values":return xs(t[i],!1)}return xs([i,t[i]],!1)}),"values"),Ws=Os.Arguments=Os.Array;if(Ns("keys"),Ns("values"),Ns("entries"),Vs&&"values"!==Ws.name)try{Ps(Ws,"name",{value:"values"})}catch(lq){}var Gs=Te,js=Be,Js=O,qs=mr,Ks=TypeError,zs="Reduce of empty array with no initial value",Ys=function(e){return function(t,i,r,n){var o=js(t),s=Js(o),a=qs(o);if(Gs(i),0===a&&r<2)throw new Ks(zs);var c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw new Ks(zs)}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},Xs={left:Ys(!1),right:Ys(!0)},Qs=s,Zs=function(e,t){var i=[][e];return!!i&&Qs((function(){i.call(null,t||function(){return 1},1)}))},$s=n,ea=X,ta=b,ia=function(e){return ea.slice(0,e.length)===e},ra=ia("Bun/")?"BUN":ia("Cloudflare-Workers")?"CLOUDFLARE":ia("Deno/")?"DENO":ia("Node.js/")?"NODE":$s.Bun&&"string"==typeof Bun.version?"BUN":$s.Deno&&"object"==typeof Deno.version?"DENO":"process"===ta($s.process)?"NODE":$s.window&&$s.document?"BROWSER":"REST",na="NODE"===ra,oa=Xs.left;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduce")},{reduce:function(e){var t=arguments.length;return oa(this,e,t,t>1?arguments[1]:void 0)}});var sa=Xs.right;nn({target:"Array",proto:!0,forced:!na&&re>79&&re<83||!Zs("reduceRight")},{reduceRight:function(e){return sa(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var aa=b,ca=Array.isArray||function(e){return"Array"===aa(e)},la=nn,da=ca,ua=I([].reverse),ha=[1,2];la({target:"Array",proto:!0,forced:String(ha)===String(ha.reverse())},{reverse:function(){return da(this)&&(this.length=this.length),ua(this)}});var pa=_e,ma=TypeError,_a=I([].slice),fa=_a,ga=Math.floor,Ea=function(e,t){var i=e.length;if(i<8)for(var r,n,o=1;o<i;){for(n=o,r=e[o];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==o++&&(e[n]=r)}else for(var s=ga(i/2),a=Ea(fa(e,0,s),t),c=Ea(fa(e,s),t),l=a.length,d=c.length,u=0,h=0;u<l||h<d;)e[u+h]=u<l&&h<d?t(a[u],c[h])<=0?a[u++]:c[h++]:u<l?a[u++]:c[h++];return e},Ta=Ea,va=X.match(/firefox\/(\d+)/i),ya=!!va&&+va[1],Sa=/MSIE|Trident/.test(X),Ia=X.match(/AppleWebKit\/(\d+)\./),Aa=!!Ia&&+Ia[1],Ra=nn,Ca=I,ba=Te,ka=Be,Da=mr,wa=function(e,t){if(!delete e[t])throw new ma("Cannot delete property "+pa(t)+" of "+pa(e))},Na=_n,Oa=s,Ma=Ta,Pa=Zs,La=ya,xa=Sa,Va=re,Ua=Aa,Fa=[],Ba=Ca(Fa.sort),Ha=Ca(Fa.push),Wa=Oa((function(){Fa.sort(void 0)})),Ga=Oa((function(){Fa.sort(null)})),ja=Pa("sort"),Ja=!Oa((function(){if(Va)return Va<70;if(!(La&&La>3)){if(xa)return!0;if(Ua)return Ua<603;var e,t,i,r,n="";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(r=0;r<47;r++)Fa.push({k:t+r,v:i})}for(Fa.sort((function(e,t){return t.v-e.v})),r=0;r<Fa.length;r++)t=Fa[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));Ra({target:"Array",proto:!0,forced:Wa||!Ga||!ja||!Ja},{sort:function(e){void 0!==e&&ba(e);var t=ka(this);if(Ja)return void 0===e?Ba(t):Ba(t,e);var i,r,n=[],o=Da(t);for(r=0;r<o;r++)r in t&&Ha(n,t[r]);for(Ma(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Na(t)>Na(i)?1:-1}}(e)),i=Da(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)wa(t,r++);return t}});var qa="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ka=$i,za=function(e,t,i){for(var r in t)Ka(e,r,t[r],i);return e},Ya=K,Xa=TypeError,Qa=function(e,t){if(Ya(t,e))return e;throw new Xa("Incorrect invocation")},Za=or,$a=hr,ec=RangeError,tc=function(e){if(void 0===e)return 0;var t=Za(e),i=$a(t);if(t!==i)throw new ec("Wrong length or index");return i},ic=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},rc=4503599627370496,nc=ic,oc=function(e){return e+rc-rc},sc=Math.abs,ac=function(e,t,i,r){var n=+e,o=sc(n),s=nc(n);if(o<r)return s*oc(o/r/t)*r*t;var a=(1+t/2220446049250313e-31)*o,c=a-(a-o);return c>i||c!=c?Infinity*s:s*c},cc=Math.fround||function(e){return ac(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},lc=Array,dc=Math.abs,uc=Math.pow,hc=Math.floor,pc=Math.log,mc=Math.LN2,_c={pack:function(e,t,i){var r,n,o,s=lc(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?uc(2,-24)-uc(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=dc(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=hc(pc(e)/mc),e*(o=uc(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*uc(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*uc(2,t),r+=l):(n=e*uc(2,l-1)*uc(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[h-1]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-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+=uc(2,t),d-=s}return(l?-1:1)*i*uc(2,d-t)}},fc=Be,gc=lr,Ec=mr,Tc=function(e){for(var t=fc(this),i=Ec(t),r=arguments.length,n=gc(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:gc(o,i);s>n;)t[n++]=e;return t},vc=H,yc=G,Sc=cs,Ic=function(e,t,i){var r,n;return Sc&&vc(r=t.constructor)&&r!==i&&yc(n=r.prototype)&&n!==i.prototype&&Sc(e,n),e},Ac=n,Rc=I,Cc=a,bc=qa,kc=Yt,Dc=En,wc=za,Nc=s,Oc=Qa,Mc=or,Pc=hr,Lc=tc,xc=cc,Vc=_c,Uc=No,Fc=cs,Bc=Tc,Hc=_a,Wc=Ic,Gc=Br,jc=jo,Jc=wi,qc=ii.PROPER,Kc=ii.CONFIGURABLE,zc="ArrayBuffer",Yc="DataView",Xc="prototype",Qc="Wrong index",Zc=Jc.getterFor(zc),$c=Jc.getterFor(Yc),el=Jc.set,tl=Ac[zc],il=tl,rl=il&&il[Xc],nl=Ac[Yc],ol=nl&&nl[Xc],sl=Object.prototype,al=Ac.Array,cl=Ac.RangeError,ll=Rc(Bc),dl=Rc([].reverse),ul=Vc.pack,hl=Vc.unpack,pl=function(e){return[255&e]},ml=function(e){return[255&e,e>>8&255]},_l=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},fl=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},gl=function(e){return ul(xc(e),23,4)},El=function(e){return ul(e,52,8)},Tl=function(e,t,i){Dc(e[Xc],t,{configurable:!0,get:function(){return i(this)[t]}})},vl=function(e,t,i,r){var n=$c(e),o=Lc(i),s=!!r;if(o+t>n.byteLength)throw new cl(Qc);var a=n.bytes,c=o+n.byteOffset,l=Hc(a,c,c+t);return s?l:dl(l)},yl=function(e,t,i,r,n,o){var s=$c(e),a=Lc(i),c=r(+n),l=!!o;if(a+t>s.byteLength)throw new cl(Qc);for(var d=s.bytes,u=a+s.byteOffset,h=0;h<t;h++)d[u+h]=c[l?h:t-h-1]};if(bc){var Sl=qc&&tl.name!==zc;Nc((function(){tl(1)}))&&Nc((function(){new tl(-1)}))&&!Nc((function(){return new tl,new tl(1.5),new tl(NaN),1!==tl.length||Sl&&!Kc}))?Sl&&Kc&&kc(tl,"name",zc):((il=function(e){return Oc(this,rl),Wc(new tl(Lc(e)),this,il)})[Xc]=rl,rl.constructor=il,Gc(il,tl)),Fc&&Uc(ol)!==sl&&Fc(ol,sl);var Il=new nl(new il(2)),Al=Rc(ol.setInt8);Il.setInt8(0,2147483648),Il.setInt8(1,2147483649),!Il.getInt8(0)&&Il.getInt8(1)||wc(ol,{setInt8:function(e,t){Al(this,e,t<<24>>24)},setUint8:function(e,t){Al(this,e,t<<24>>24)}},{unsafe:!0})}else rl=(il=function(e){Oc(this,rl);var t=Lc(e);el(this,{type:zc,bytes:ll(al(t),0),byteLength:t}),Cc||(this.byteLength=t,this.detached=!1)})[Xc],ol=(nl=function(e,t,i){Oc(this,ol),Oc(e,rl);var r=Zc(e),n=r.byteLength,o=Mc(t);if(o<0||o>n)throw new cl("Wrong offset");if(o+(i=void 0===i?n-o:Pc(i))>n)throw new cl("Wrong length");el(this,{type:Yc,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),Cc||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Xc],Cc&&(Tl(il,"byteLength",Zc),Tl(nl,"buffer",$c),Tl(nl,"byteLength",$c),Tl(nl,"byteOffset",$c)),wc(ol,{getInt8:function(e){return vl(this,1,e)[0]<<24>>24},getUint8:function(e){return vl(this,1,e)[0]},getInt16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=vl(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return fl(vl(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return hl(vl(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return hl(vl(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){yl(this,1,e,pl,t)},setUint8:function(e,t){yl(this,1,e,pl,t)},setInt16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){yl(this,2,e,ml,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){yl(this,4,e,_l,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){yl(this,4,e,gl,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){yl(this,8,e,El,t,arguments.length>2&&arguments[2])}});jc(il,zc),jc(nl,Yc);var Rl={ArrayBuffer:il,DataView:nl},Cl=q,bl=En,kl=a,Dl=rt("species"),wl=function(e){var t=Cl(e);kl&&t&&!t[Dl]&&bl(t,Dl,{configurable:!0,get:function(){return this}})},Nl=wl,Ol="ArrayBuffer",Ml=Rl[Ol];nn({global:!0,constructor:!0,forced:n[Ol]!==Ml},{ArrayBuffer:Ml}),Nl(Ol);var Pl=b,Ll=I,xl=function(e){if("Function"===Pl(e))return Ll(e)},Vl=nn,Ul=xl,Fl=s,Bl=Lt,Hl=lr,Wl=hr,Gl=Rl.ArrayBuffer,jl=Rl.DataView,Jl=jl.prototype,ql=Ul(Gl.prototype.slice),Kl=Ul(Jl.getUint8),zl=Ul(Jl.setUint8);Vl({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Fl((function(){return!new Gl(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(ql&&void 0===t)return ql(Bl(this),e);for(var i=Bl(this).byteLength,r=Hl(e,i),n=Hl(void 0===t?i:t,i),o=new Gl(Wl(n-r)),s=new jl(this),a=new jl(o),c=0;r<n;)zl(a,c++,Kl(s,r++));return o}});var Yl=I,Xl=s,Ql=H,Zl=hn,$l=li,ed=function(){},td=q("Reflect","construct"),id=/^\s*(?:class|function)\b/,rd=Yl(id.exec),nd=!id.test(ed),od=function(e){if(!Ql(e))return!1;try{return td(ed,[],e),!0}catch(lq){return!1}},sd=function(e){if(!Ql(e))return!1;switch(Zl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nd||!!rd(id,$l(e))}catch(lq){return!0}};sd.sham=!0;var ad,cd,ld,dd,ud=!td||Xl((function(){var e;return od(od.call)||!od(Object)||!od((function(){e=!0}))||e}))?sd:od,hd=ud,pd=_e,md=TypeError,_d=function(e){if(hd(e))return e;throw new md(pd(e)+" is not a constructor")},fd=Lt,gd=_d,Ed=M,Td=rt("species"),vd=function(e,t){var i,r=fd(e).constructor;return void 0===r||Ed(i=fd(r)[Td])?t:gd(i)},yd=c,Sd=Function.prototype,Id=Sd.apply,Ad=Sd.call,Rd="object"==typeof Reflect&&Reflect.apply||(yd?Ad.bind(Id):function(){return Ad.apply(Id,arguments)}),Cd=Te,bd=c,kd=xl(xl.bind),Dd=function(e,t){return Cd(e),void 0===t?e:bd?kd(e,t):function(){return e.apply(t,arguments)}},wd=TypeError,Nd=function(e,t){if(e<t)throw new wd("Not enough arguments");return e},Od=/(?:ipad|iphone|ipod).*applewebkit/i.test(X),Md=n,Pd=Rd,Ld=Dd,xd=H,Vd=Ge,Ud=s,Fd=Yn,Bd=_a,Hd=Et,Wd=Nd,Gd=Od,jd=na,Jd=Md.setImmediate,qd=Md.clearImmediate,Kd=Md.process,zd=Md.Dispatch,Yd=Md.Function,Xd=Md.MessageChannel,Qd=Md.String,Zd=0,$d={},eu="onreadystatechange";Ud((function(){ad=Md.location}));var tu=function(e){if(Vd($d,e)){var t=$d[e];delete $d[e],t()}},iu=function(e){return function(){tu(e)}},ru=function(e){tu(e.data)},nu=function(e){Md.postMessage(Qd(e),ad.protocol+"//"+ad.host)};Jd&&qd||(Jd=function(e){Wd(arguments.length,1);var t=xd(e)?e:Yd(e),i=Bd(arguments,1);return $d[++Zd]=function(){Pd(t,void 0,i)},cd(Zd),Zd},qd=function(e){delete $d[e]},jd?cd=function(e){Kd.nextTick(iu(e))}:zd&&zd.now?cd=function(e){zd.now(iu(e))}:Xd&&!Gd?(dd=(ld=new Xd).port2,ld.port1.onmessage=ru,cd=Ld(dd.postMessage,dd)):Md.addEventListener&&xd(Md.postMessage)&&!Md.importScripts&&ad&&"file:"!==ad.protocol&&!Ud(nu)?(cd=nu,Md.addEventListener("message",ru,!1)):cd=eu in Hd("script")?function(e){Fd.appendChild(Hd("script"))[eu]=function(){Fd.removeChild(this),tu(e)}}:function(e){setTimeout(iu(e),0)});var ou={set:Jd,clear:qd},su=n,au=a,cu=Object.getOwnPropertyDescriptor,lu=function(e){if(!au)return su[e];var t=cu(su,e);return t&&t.value},du=function(){this.head=null,this.tail=null};du.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 uu,hu,pu,mu,_u,fu=du,gu=/ipad|iphone|ipod/i.test(X)&&"undefined"!=typeof Pebble,Eu=/web0s(?!.*chrome)/i.test(X),Tu=n,vu=lu,yu=Dd,Su=ou.set,Iu=fu,Au=Od,Ru=gu,Cu=Eu,bu=na,ku=Tu.MutationObserver||Tu.WebKitMutationObserver,Du=Tu.document,wu=Tu.process,Nu=Tu.Promise,Ou=vu("queueMicrotask");if(!Ou){var Mu=new Iu,Pu=function(){var e,t;for(bu&&(e=wu.domain)&&e.exit();t=Mu.get();)try{t()}catch(lq){throw Mu.head&&uu(),lq}e&&e.enter()};Au||bu||Cu||!ku||!Du?!Ru&&Nu&&Nu.resolve?((mu=Nu.resolve(void 0)).constructor=Nu,_u=yu(mu.then,mu),uu=function(){_u(Pu)}):bu?uu=function(){wu.nextTick(Pu)}:(Su=yu(Su,Tu),uu=function(){Su(Pu)}):(hu=!0,pu=Du.createTextNode(""),new ku(Pu).observe(pu,{characterData:!0}),uu=function(){pu.data=hu=!hu}),Ou=function(e){Mu.head||uu(),Mu.add(e)}}var Lu=Ou,xu=function(e){try{return{error:!1,value:e()}}catch(lq){return{error:!0,value:lq}}},Vu=n.Promise,Uu=n,Fu=Vu,Bu=H,Hu=Yr,Wu=li,Gu=rt,ju=ra,Ju=re;Fu&&Fu.prototype;var qu=Gu("species"),Ku=!1,zu=Bu(Uu.PromiseRejectionEvent),Yu=Hu("Promise",(function(){var e=Wu(Fu),t=e!==String(Fu);if(!t&&66===Ju)return!0;if(!Ju||Ju<51||!/native code/.test(e)){var i=new Fu((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[qu]=r,!(Ku=i.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==ju&&"DENO"!==ju||zu)})),Xu={CONSTRUCTOR:Yu,REJECTION_EVENT:zu,SUBCLASSING:Ku},Qu={},Zu=Te,$u=TypeError,eh=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new $u("Bad Promise constructor");t=e,i=r})),this.resolve=Zu(t),this.reject=Zu(i)};Qu.f=function(e){return new eh(e)};var th,ih,rh,nh=nn,oh=na,sh=n,ah=u,ch=$i,lh=cs,dh=jo,uh=wl,hh=Te,ph=H,mh=G,_h=Qa,fh=vd,gh=ou.set,Eh=Lu,Th=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(lq){}},vh=xu,yh=fu,Sh=wi,Ih=Vu,Ah=Qu,Rh="Promise",Ch=Xu.CONSTRUCTOR,bh=Xu.REJECTION_EVENT,kh=Xu.SUBCLASSING,Dh=Sh.getterFor(Rh),wh=Sh.set,Nh=Ih&&Ih.prototype,Oh=Ih,Mh=Nh,Ph=sh.TypeError,Lh=sh.document,xh=sh.process,Vh=Ah.f,Uh=Vh,Fh=!!(Lh&&Lh.createEvent&&sh.dispatchEvent),Bh="unhandledrejection",Hh=function(e){var t;return!(!mh(e)||!ph(t=e.then))&&t},Wh=function(e,t){var i,r,n,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&&Kh(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(new Ph("Promise-chain cycle")):(r=Hh(i))?ah(r,i,c,l):c(i)):l(o)}catch(lq){d&&!n&&d.exit(),l(lq)}},Gh=function(e,t){e.notified||(e.notified=!0,Eh((function(){for(var i,r=e.reactions;i=r.get();)Wh(i,e);e.notified=!1,t&&!e.rejection&&Jh(e)})))},jh=function(e,t,i){var r,n;Fh?((r=Lh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),sh.dispatchEvent(r)):r={promise:t,reason:i},!bh&&(n=sh["on"+e])?n(r):e===Bh&&Th("Unhandled promise rejection",i)},Jh=function(e){ah(gh,sh,(function(){var t,i=e.facade,r=e.value;if(qh(e)&&(t=vh((function(){oh?xh.emit("unhandledRejection",r,i):jh(Bh,i,r)})),e.rejection=oh||qh(e)?2:1,t.error))throw t.value}))},qh=function(e){return 1!==e.rejection&&!e.parent},Kh=function(e){ah(gh,sh,(function(){var t=e.facade;oh?xh.emit("rejectionHandled",t):jh("rejectionhandled",t,e.value)}))},zh=function(e,t,i){return function(r){e(t,r,i)}},Yh=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Gh(e,!0))},Xh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new Ph("Promise can't be resolved itself");var r=Hh(t);r?Eh((function(){var i={done:!1};try{ah(r,t,zh(Xh,i,e),zh(Yh,i,e))}catch(lq){Yh(i,lq,e)}})):(e.value=t,e.state=1,Gh(e,!1))}catch(lq){Yh({done:!1},lq,e)}}};if(Ch&&(Mh=(Oh=function(e){_h(this,Mh),hh(e),ah(th,this);var t=Dh(this);try{e(zh(Xh,t),zh(Yh,t))}catch(lq){Yh(t,lq)}}).prototype,(th=function(e){wh(this,{type:Rh,done:!1,notified:!1,parent:!1,reactions:new yh,rejection:!1,state:0,value:null})}).prototype=ch(Mh,"then",(function(e,t){var i=Dh(this),r=Vh(fh(this,Oh));return i.parent=!0,r.ok=!ph(e)||e,r.fail=ph(t)&&t,r.domain=oh?xh.domain:void 0,0===i.state?i.reactions.add(r):Eh((function(){Wh(r,i)})),r.promise})),ih=function(){var e=new th,t=Dh(e);this.promise=e,this.resolve=zh(Xh,t),this.reject=zh(Yh,t)},Ah.f=Vh=function(e){return e===Oh||undefined===e?new ih(e):Uh(e)},ph(Ih)&&Nh!==Object.prototype)){rh=Nh.then,kh||ch(Nh,"then",(function(e,t){var i=this;return new Oh((function(e,t){ah(rh,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Nh.constructor}catch(lq){}lh&&lh(Nh,Mh)}nh({global:!0,constructor:!0,wrap:!0,forced:Ch},{Promise:Oh}),dh(Oh,Rh,!1),uh(Rh);var Qh=So,Zh=rt("iterator"),$h=Array.prototype,ep=function(e){return void 0!==e&&(Qh.Array===e||$h[Zh]===e)},tp=hn,ip=Se,rp=M,np=So,op=rt("iterator"),sp=function(e){if(!rp(e))return ip(e,op)||ip(e,"@@iterator")||np[tp(e)]},ap=u,cp=Te,lp=Lt,dp=_e,up=sp,hp=TypeError,pp=function(e,t){var i=arguments.length<2?up(e):t;if(cp(i))return lp(ap(i,e));throw new hp(dp(e)+" is not iterable")},mp=u,_p=Lt,fp=Se,gp=function(e,t,i){var r,n;_p(e);try{if(!(r=fp(e,"return"))){if("throw"===t)throw i;return i}r=mp(r,e)}catch(lq){n=!0,r=lq}if("throw"===t)throw i;if(n)throw r;return _p(r),i},Ep=Dd,Tp=u,vp=Lt,yp=_e,Sp=ep,Ip=mr,Ap=K,Rp=pp,Cp=sp,bp=gp,kp=TypeError,Dp=function(e,t){this.stopped=e,this.result=t},wp=Dp.prototype,Np=function(e,t,i){var r,n,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),_=Ep(t,d),f=function(e){return r&&bp(r,"normal",e),new Dp(!0,e)},g=function(e){return u?(vp(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=Cp(e)))throw new kp(yp(e)+" is not iterable");if(Sp(n)){for(o=0,s=Ip(e);s>o;o++)if((a=g(e[o]))&&Ap(wp,a))return a;return new Dp(!1)}r=Rp(e,n)}for(c=h?e.next:r.next;!(l=Tp(c,r)).done;){try{a=g(l.value)}catch(lq){bp(r,"throw",lq)}if("object"==typeof a&&a&&Ap(wp,a))return a}return new Dp(!1)},Op=rt("iterator"),Mp=!1;try{var Pp=0,Lp={next:function(){return{done:!!Pp++}},return:function(){Mp=!0}};Lp[Op]=function(){return this},Array.from(Lp,(function(){throw 2}))}catch(lq){}var xp=function(e,t){try{if(!t&&!Mp)return!1}catch(lq){return!1}var i=!1;try{var r={};r[Op]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(lq){}return i},Vp=Vu,Up=Xu.CONSTRUCTOR||!xp((function(e){Vp.all(e).then(void 0,(function(){}))})),Fp=u,Bp=Te,Hp=Qu,Wp=xu,Gp=Np;nn({target:"Promise",stat:!0,forced:Up},{all:function(e){var t=this,i=Hp.f(t),r=i.resolve,n=i.reject,o=Wp((function(){var i=Bp(t.resolve),o=[],s=0,a=1;Gp(e,(function(e){var c=s++,l=!1;a++,Fp(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var jp=nn,Jp=Xu.CONSTRUCTOR,qp=Vu,Kp=q,zp=H,Yp=$i,Xp=qp&&qp.prototype;if(jp({target:"Promise",proto:!0,forced:Jp,real:!0},{catch:function(e){return this.then(void 0,e)}}),zp(qp)){var Qp=Kp("Promise").prototype.catch;Xp.catch!==Qp&&Yp(Xp,"catch",Qp,{unsafe:!0})}var Zp=u,$p=Te,em=Qu,tm=xu,im=Np;nn({target:"Promise",stat:!0,forced:Up},{race:function(e){var t=this,i=em.f(t),r=i.reject,n=tm((function(){var n=$p(t.resolve);im(e,(function(e){Zp(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var rm=Qu;nn({target:"Promise",stat:!0,forced:Xu.CONSTRUCTOR},{reject:function(e){var t=rm.f(this);return(0,t.reject)(e),t.promise}});var nm=Lt,om=G,sm=Qu,am=function(e,t){if(nm(e),om(t)&&t.constructor===e)return t;var i=sm.f(e);return(0,i.resolve)(t),i.promise},cm=nn,lm=Xu.CONSTRUCTOR,dm=am;q("Promise"),cm({target:"Promise",stat:!0,forced:lm},{resolve:function(e){return dm(this,e)}});var um=nn,hm=Vu,pm=s,mm=q,_m=H,fm=vd,gm=am,Em=$i,Tm=hm&&hm.prototype;if(um({target:"Promise",proto:!0,real:!0,forced:!!hm&&pm((function(){Tm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=fm(this,mm("Promise")),i=_m(e);return this.then(i?function(i){return gm(t,e()).then((function(){return i}))}:e,i?function(i){return gm(t,e()).then((function(){throw i}))}:e)}}),_m(hm)){var vm=mm("Promise").prototype.finally;Tm.finally!==vm&&Em(Tm,"finally",vm,{unsafe:!0})}var ym=G,Sm=b,Im=rt("match"),Am=function(e){var t;return ym(e)&&(void 0!==(t=e[Im])?!!t:"RegExp"===Sm(e))},Rm=Lt,Cm=function(){var e=Rm(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},bm=u,km=Ge,Dm=K,wm=Cm,Nm=RegExp.prototype,Om=function(e){var t=e.flags;return void 0!==t||"flags"in Nm||km(e,"flags")||!Dm(Nm,e)?t:bm(wm,e)},Mm=s,Pm=n.RegExp,Lm=Mm((function(){var e=Pm("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),xm=Lm||Mm((function(){return!Pm("a","y").sticky})),Vm=Lm||Mm((function(){var e=Pm("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Um={BROKEN_CARET:Vm,MISSED_STICKY:xm,UNSUPPORTED_Y:Lm},Fm=wt.f,Bm=s,Hm=n.RegExp,Wm=Bm((function(){var e=Hm(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Gm=s,jm=n.RegExp,Jm=Gm((function(){var e=jm("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),qm=a,Km=n,zm=I,Ym=Yr,Xm=Ic,Qm=Yt,Zm=lo,$m=er.f,e_=K,t_=Am,i_=_n,r_=Om,n_=Um,o_=function(e,t,i){i in e||Fm(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},s_=$i,a_=s,c_=Ge,l_=wi.enforce,d_=wl,u_=Wm,h_=Jm,p_=rt("match"),m_=Km.RegExp,__=m_.prototype,f_=Km.SyntaxError,g_=zm(__.exec),E_=zm("".charAt),T_=zm("".replace),v_=zm("".indexOf),y_=zm("".slice),S_=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,I_=/a/g,A_=/a/g,R_=new m_(I_)!==I_,C_=n_.MISSED_STICKY,b_=n_.UNSUPPORTED_Y,k_=qm&&(!R_||C_||u_||h_||a_((function(){return A_[p_]=!1,m_(I_)!==I_||m_(A_)===A_||"/a/i"!==String(m_(I_,"i"))})));if(Ym("RegExp",k_)){for(var D_=function(e,t){var i,r,n,o,s,a,c=e_(__,this),l=t_(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===D_)return e;if((l||e_(__,e))&&(e=e.source,d&&(t=r_(h))),e=void 0===e?"":i_(e),t=void 0===t?"":i_(t),h=e,u_&&"dotAll"in I_&&(r=!!t&&v_(t,"s")>-1)&&(t=T_(t,/s/g,"")),i=t,C_&&"sticky"in I_&&(n=!!t&&v_(t,"y")>-1)&&b_&&(t=T_(t,/y/g,"")),h_&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s=Zm(null),a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=E_(e,r)))t+=E_(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:if(n+=t,"?:"===y_(e,r+1,r+3))continue;g_(S_,y_(e,r+1))&&(r+=2,c=!0),l++;continue;case">"===t&&c:if(""===d||c_(s,d))throw new f_("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Xm(m_(e,t),c?this:__,D_),(r||n||u.length)&&(a=l_(s),r&&(a.dotAll=!0,a.raw=D_(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=E_(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+E_(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Qm(s,"source",""===h?"(?:)":h)}catch(lq){}return s},w_=$m(m_),N_=0;w_.length>N_;)o_(D_,m_,w_[N_++]);__.constructor=D_,D_.prototype=__,s_(Km,"RegExp",D_,{constructor:!0})}d_("RegExp");var O_=u,M_=I,P_=_n,L_=Cm,x_=Um,V_=lo,U_=wi.get,F_=Wm,B_=Jm,H_=Ve("native-string-replace",String.prototype.replace),W_=RegExp.prototype.exec,G_=W_,j_=M_("".charAt),J_=M_("".indexOf),q_=M_("".replace),K_=M_("".slice),z_=function(){var e=/a/,t=/b*/g;return O_(W_,e,"a"),O_(W_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Y_=x_.BROKEN_CARET,X_=void 0!==/()??/.exec("")[1];(z_||X_||Y_||F_||B_)&&(G_=function(e){var t,i,r,n,o,s,a,c=this,l=U_(c),d=P_(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=O_(G_,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Y_&&c.sticky,m=O_(L_,c),_=c.source,f=0,g=d;if(p&&(m=q_(m,"y",""),-1===J_(m,"g")&&(m+="g"),g=K_(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==j_(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),X_&&(i=new RegExp("^"+_+"$(?!\\s)",m)),z_&&(r=c.lastIndex),n=O_(W_,p?i:c,g),p?n?(n.input=K_(n.input,f),n[0]=K_(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:z_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),X_&&n&&n.length>1&&O_(H_,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=V_(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Q_=G_;nn({target:"RegExp",proto:!0,forced:/./.exec!==Q_},{exec:Q_});var Z_=or,$_=_n,ef=x,tf=RangeError,rf=I,nf=hr,of=_n,sf=function(e){var t=$_(ef(this)),i="",r=Z_(e);if(r<0||Infinity===r)throw new tf("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},af=x,cf=rf(sf),lf=rf("".slice),df=Math.ceil,uf=function(e){return function(t,i,r){var n,o,s=of(af(t)),a=nf(i),c=s.length,l=void 0===r?" ":of(r);return a<=c||""===l?s:((o=cf(l,df((n=a-c)/l.length))).length>n&&(o=lf(o,0,n)),e?s+o:o+s)}},hf={start:uf(!1),end:uf(!0)},pf=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(X),mf=hf.start;nn({target:"String",proto:!0,forced:pf},{padStart:function(e){return mf(this,e,arguments.length>1?arguments[1]:void 0)}});var _f=u,ff=$i,gf=Q_,Ef=s,Tf=rt,vf=Yt,yf=Tf("species"),Sf=RegExp.prototype,If=I,Af=or,Rf=_n,Cf=x,bf=If("".charAt),kf=If("".charCodeAt),Df=If("".slice),wf=function(e){return function(t,i){var r,n,o=Rf(Cf(t)),s=Af(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=kf(o,s))<55296||r>56319||s+1===a||(n=kf(o,s+1))<56320||n>57343?e?bf(o,s):r:e?Df(o,s,s+2):n-56320+(r-55296<<10)+65536}},Nf={codeAt:wf(!1),charAt:wf(!0)},Of=Nf.charAt,Mf=I,Pf=Be,Lf=Math.floor,xf=Mf("".charAt),Vf=Mf("".replace),Uf=Mf("".slice),Ff=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Bf=/\$([$&'`]|\d{1,2})/g,Hf=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=Bf;return void 0!==n&&(n=Pf(n),c=Ff),Vf(o,c,(function(o,c){var l;switch(xf(c,0)){case"$":return"$";case"&":return e;case"`":return Uf(t,0,i);case"'":return Uf(t,s);case"<":l=n[Uf(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Lf(d/10);return 0===u?o:u<=a?void 0===r[u-1]?xf(c,1):r[u-1]+xf(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Wf=u,Gf=Lt,jf=H,Jf=b,qf=Q_,Kf=TypeError,zf=Rd,Yf=u,Xf=I,Qf=function(e,t,i,r){var n=Tf(e),o=!Ef((function(){var t={};return t[n]=function(){return 7},7!==""[e](t)})),s=o&&!Ef((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[yf]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=/./[n],c=t(n,""[e],(function(e,t,i,r,n){var s=t.exec;return s===gf||s===Sf.exec?o&&!n?{done:!0,value:_f(a,t,i,r)}:{done:!0,value:_f(e,i,t,r)}:{done:!1}}));ff(String.prototype,e,c[0]),ff(Sf,n,c[1])}r&&vf(Sf[n],"sham",!0)},Zf=s,$f=Lt,eg=H,tg=M,ig=or,rg=hr,ng=_n,og=x,sg=function(e,t,i){return t+(i?Of(e,t).length:1)},ag=Se,cg=Hf,lg=function(e,t){var i=e.exec;if(jf(i)){var r=Wf(i,e,t);return null!==r&&Gf(r),r}if("RegExp"===Jf(e))return Wf(qf,e,t);throw new Kf("RegExp#exec called on incompatible receiver")},dg=rt("replace"),ug=Math.max,hg=Math.min,pg=Xf([].concat),mg=Xf([].push),_g=Xf("".indexOf),fg=Xf("".slice),gg=function(e){return void 0===e?e:String(e)},Eg="$0"==="a".replace(/./,"$0"),Tg=!!/./[dg]&&""===/./[dg]("a","$0"),vg=!Zf((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Qf("replace",(function(e,t,i){var r=Tg?"$":"$0";return[function(e,i){var r=og(this),n=tg(e)?void 0:ag(e,dg);return n?Yf(n,e,r,i):Yf(t,ng(r),e,i)},function(e,n){var o=$f(this),s=ng(e);if("string"==typeof n&&-1===_g(n,r)&&-1===_g(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=eg(n);c||(n=ng(n));var l,d=o.global;d&&(l=o.unicode,o.lastIndex=0);for(var u,h=[];null!==(u=lg(o,s))&&(mg(h,u),d);){""===ng(u[0])&&(o.lastIndex=sg(s,rg(o.lastIndex),l))}for(var p="",m=0,_=0;_<h.length;_++){for(var f,g=ng((u=h[_])[0]),E=ug(hg(ig(u.index),s.length),0),T=[],v=1;v<u.length;v++)mg(T,gg(u[v]));var y=u.groups;if(c){var S=pg([g],T,E,s);void 0!==y&&mg(S,y),f=ng(zf(n,void 0,S))}else f=cg(g,s,E,T,y,n);E>=m&&(p+=fg(s,m,E)+f,m=E+g.length)}return p+fg(s,m)}]}),!vg||!Eg||Tg);var yg="\t\n\v\f\r                 \u2028\u2029\ufeff",Sg=x,Ig=_n,Ag=yg,Rg=I("".replace),Cg=RegExp("^["+Ag+"]+"),bg=RegExp("(^|[^"+Ag+"])["+Ag+"]+$"),kg=function(e){return function(t){var i=Ig(Sg(t));return 1&e&&(i=Rg(i,Cg,"")),2&e&&(i=Rg(i,bg,"$1")),i}},Dg={start:kg(1),end:kg(2),trim:kg(3)},wg=ii.PROPER,Ng=s,Og=yg,Mg=Dg.trim;nn({target:"String",proto:!0,forced:function(e){return Ng((function(){return!!Og[e]()||"​…᠎"!=="​…᠎"[e]()||wg&&Og[e].name!==e}))}("trim")},{trim:function(){return Mg(this)}});var Pg,Lg,xg,Vg={exports:{}},Ug=qa,Fg=a,Bg=n,Hg=H,Wg=G,Gg=Ge,jg=hn,Jg=_e,qg=Yt,Kg=$i,zg=En,Yg=K,Xg=No,Qg=cs,Zg=rt,$g=ze,eE=wi.enforce,tE=wi.get,iE=Bg.Int8Array,rE=iE&&iE.prototype,nE=Bg.Uint8ClampedArray,oE=nE&&nE.prototype,sE=iE&&Xg(iE),aE=rE&&Xg(rE),cE=Object.prototype,lE=Bg.TypeError,dE=Zg("toStringTag"),uE=$g("TYPED_ARRAY_TAG"),hE="TypedArrayConstructor",pE=Ug&&!!Qg&&"Opera"!==jg(Bg.opera),mE=!1,_E={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},fE={BigInt64Array:8,BigUint64Array:8},gE=function(e){var t=Xg(e);if(Wg(t)){var i=tE(t);return i&&Gg(i,hE)?i[hE]:gE(t)}},EE=function(e){if(!Wg(e))return!1;var t=jg(e);return Gg(_E,t)||Gg(fE,t)};for(Pg in _E)(xg=(Lg=Bg[Pg])&&Lg.prototype)?eE(xg)[hE]=Lg:pE=!1;for(Pg in fE)(xg=(Lg=Bg[Pg])&&Lg.prototype)&&(eE(xg)[hE]=Lg);if((!pE||!Hg(sE)||sE===Function.prototype)&&(sE=function(){throw new lE("Incorrect invocation")},pE))for(Pg in _E)Bg[Pg]&&Qg(Bg[Pg],sE);if((!pE||!aE||aE===cE)&&(aE=sE.prototype,pE))for(Pg in _E)Bg[Pg]&&Qg(Bg[Pg].prototype,aE);if(pE&&Xg(oE)!==aE&&Qg(oE,aE),Fg&&!Gg(aE,dE))for(Pg in mE=!0,zg(aE,dE,{configurable:!0,get:function(){return Wg(this)?this[uE]:void 0}}),_E)Bg[Pg]&&qg(Bg[Pg],uE,Pg);var TE={NATIVE_ARRAY_BUFFER_VIEWS:pE,TYPED_ARRAY_TAG:mE&&uE,aTypedArray:function(e){if(EE(e))return e;throw new lE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Hg(e)&&(!Qg||Yg(sE,e)))return e;throw new lE(Jg(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Fg){if(i)for(var n in _E){var o=Bg[n];if(o&&Gg(o.prototype,e))try{delete o.prototype[e]}catch(lq){try{o.prototype[e]=t}catch(s){}}}aE[e]&&!i||Kg(aE,e,i?t:pE&&rE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Fg){if(Qg){if(i)for(r in _E)if((n=Bg[r])&&Gg(n,e))try{delete n[e]}catch(lq){}if(sE[e]&&!i)return;try{return Kg(sE,e,i?t:pE&&sE[e]||t)}catch(lq){}}for(r in _E)!(n=Bg[r])||n[e]&&!i||Kg(n,e,t)}},getTypedArrayConstructor:gE,isView:function(e){if(!Wg(e))return!1;var t=jg(e);return"DataView"===t||Gg(_E,t)||Gg(fE,t)},isTypedArray:EE,TypedArray:sE,TypedArrayPrototype:aE},vE=n,yE=s,SE=xp,IE=TE.NATIVE_ARRAY_BUFFER_VIEWS,AE=vE.ArrayBuffer,RE=vE.Int8Array,CE=!IE||!yE((function(){RE(1)}))||!yE((function(){new RE(-1)}))||!SE((function(e){new RE,new RE(null),new RE(1.5),new RE(e)}),!0)||yE((function(){return 1!==new RE(new AE(2),1,void 0).length})),bE=G,kE=Math.floor,DE=Number.isInteger||function(e){return!bE(e)&&isFinite(e)&&kE(e)===e},wE=or,NE=RangeError,OE=function(e){var t=wE(e);if(t<0)throw new NE("The argument can't be less than 0");return t},ME=RangeError,PE=function(e,t){var i=OE(e);if(i%t)throw new ME("Wrong offset");return i},LE=Math.round,xE=hn,VE=ut,UE=TypeError,FE=function(e){var t=VE(e,"number");if("number"==typeof t)throw new UE("Can't convert number to bigint");return BigInt(t)},BE=Dd,HE=u,WE=_d,GE=Be,jE=mr,JE=pp,qE=sp,KE=ep,zE=function(e){var t=xE(e);return"BigInt64Array"===t||"BigUint64Array"===t},YE=TE.aTypedArrayConstructor,XE=FE,QE=function(e){var t,i,r,n,o,s,a,c,l=WE(this),d=GE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=qE(d);if(m&&!KE(m))for(c=(a=JE(d,m)).next,d=[];!(s=HE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=BE(h,arguments[2])),i=jE(d),r=new(YE(l))(i),n=zE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?XE(o):+o;return r},ZE=ca,$E=ud,eT=G,tT=rt("species"),iT=Array,rT=function(e){var t;return ZE(e)&&(t=e.constructor,($E(t)&&(t===iT||ZE(t.prototype))||eT(t)&&null===(t=t[tT]))&&(t=void 0)),void 0===t?iT:t},nT=Dd,oT=O,sT=Be,aT=mr,cT=function(e,t){return new(rT(e))(0===t?0:t)},lT=I([].push),dT=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,l,d,u){for(var h,p,m=sT(c),_=oT(m),f=aT(_),g=nT(l,d),E=0,T=u||cT,v=t?T(c,f):i||s?T(c,0):void 0;f>E;E++)if((a||E in _)&&(p=g(h=_[E],E,m),e))if(t)v[E]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return E;case 2:lT(v,h)}else switch(e){case 4:return!1;case 7:lT(v,h)}return o?-1:r||n?n:v}},uT={forEach:dT(0),map:dT(1),filter:dT(2),some:dT(3),every:dT(4),find:dT(5),findIndex:dT(6),filterReject:dT(7)},hT=mr,pT=nn,mT=n,_T=u,fT=a,gT=CE,ET=TE,TT=Rl,vT=Qa,yT=E,ST=Yt,IT=DE,AT=hr,RT=tc,CT=PE,bT=function(e){var t=LE(e);return t<0?0:t>255?255:255&t},kT=mt,DT=Ge,wT=hn,NT=G,OT=pe,MT=lo,PT=K,LT=cs,xT=er.f,VT=QE,UT=uT.forEach,FT=wl,BT=En,HT=wt,WT=o,GT=function(e,t,i){for(var r=0,n=arguments.length>2?i:hT(t),o=new e(n);n>r;)o[r]=t[r++];return o},jT=Ic,JT=wi.get,qT=wi.set,KT=wi.enforce,zT=HT.f,YT=WT.f,XT=mT.RangeError,QT=TT.ArrayBuffer,ZT=QT.prototype,$T=TT.DataView,ev=ET.NATIVE_ARRAY_BUFFER_VIEWS,tv=ET.TYPED_ARRAY_TAG,iv=ET.TypedArray,rv=ET.TypedArrayPrototype,nv=ET.isTypedArray,ov="BYTES_PER_ELEMENT",sv="Wrong length",av=function(e,t){BT(e,t,{configurable:!0,get:function(){return JT(this)[t]}})},cv=function(e){var t;return PT(ZT,e)||"ArrayBuffer"===(t=wT(e))||"SharedArrayBuffer"===t},lv=function(e,t){return nv(e)&&!OT(t)&&t in e&&IT(+t)&&t>=0},dv=function(e,t){return t=kT(t),lv(e,t)?yT(2,e[t]):YT(e,t)},uv=function(e,t,i){return t=kT(t),!(lv(e,t)&&NT(i)&&DT(i,"value"))||DT(i,"get")||DT(i,"set")||i.configurable||DT(i,"writable")&&!i.writable||DT(i,"enumerable")&&!i.enumerable?zT(e,t,i):(e[t]=i.value,e)};fT?(ev||(WT.f=dv,HT.f=uv,av(rv,"buffer"),av(rv,"byteOffset"),av(rv,"byteLength"),av(rv,"length")),pT({target:"Object",stat:!0,forced:!ev},{getOwnPropertyDescriptor:dv,defineProperty:uv}),Vg.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=mT[n],c=a,l=c&&c.prototype,d={},u=function(e,t){zT(e,t,{get:function(){return function(e,t){var i=JT(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=JT(e);o.view[s](t*r+o.byteOffset,i?bT(n):n,!0)}(this,t,e)},enumerable:!0})};ev?gT&&(c=t((function(e,t,i,n){return vT(e,l),jT(NT(t)?cv(t)?void 0!==n?new a(t,CT(i,r),n):void 0!==i?new a(t,CT(i,r)):new a(t):nv(t)?GT(c,t):_T(VT,c,t):new a(RT(t)),e,c)})),LT&&LT(c,iv),UT(xT(a),(function(e){e in c||ST(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){vT(e,l);var o,s,a,d=0,h=0;if(NT(t)){if(!cv(t))return nv(t)?GT(c,t):_T(VT,c,t);o=t,h=CT(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw new XT(sv);if((s=p-h)<0)throw new XT(sv)}else if((s=AT(n)*r)+h>p)throw new XT(sv);a=s/r}else a=RT(t),o=new QT(s=a*r);for(qT(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new $T(o)});d<a;)u(e,d++)})),LT&&LT(c,iv),l=c.prototype=MT(rv)),l.constructor!==c&&ST(l,"constructor",c),KT(l).TypedArrayConstructor=c,tv&&ST(l,tv,n);var h=c!==a;d[n]=c,pT({global:!0,constructor:!0,forced:h,sham:!ev},d),ov in c||ST(c,ov,r),ov in l||ST(l,ov,r),FT(n)}):Vg.exports=function(){};var hv=Vg.exports;hv("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),hv("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var pv=Tc,mv=FE,_v=hn,fv=u,gv=s,Ev=TE.aTypedArray,Tv=TE.exportTypedArrayMethod,vv=I("".slice);Tv("fill",(function(e){var t=arguments.length;Ev(this);var i="Big"===vv(_v(this),0,3)?mv(e):+e;return fv(pv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),gv((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,TE.exportTypedArrayStaticMethod)("from",QE,CE);var yv=n,Sv=u,Iv=TE,Av=mr,Rv=PE,Cv=Be,bv=s,kv=yv.RangeError,Dv=yv.Int8Array,wv=Dv&&Dv.prototype,Nv=wv&&wv.set,Ov=Iv.aTypedArray,Mv=Iv.exportTypedArrayMethod,Pv=!bv((function(){var e=new Uint8ClampedArray(2);return Sv(Nv,e,{length:1,0:3},1),3!==e[1]})),Lv=Pv&&Iv.NATIVE_ARRAY_BUFFER_VIEWS&&bv((function(){var e=new Dv(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));Mv("set",(function(e){Ov(this);var t=Rv(arguments.length>1?arguments[1]:void 0,1),i=Cv(e);if(Pv)return Sv(Nv,this,i,t);var r=this.length,n=Av(i),o=0;if(n+t>r)throw new kv("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!Pv||Lv);var xv=xl,Vv=s,Uv=Te,Fv=Ta,Bv=ya,Hv=Sa,Wv=re,Gv=Aa,jv=TE.aTypedArray,Jv=TE.exportTypedArrayMethod,qv=n.Uint16Array,Kv=qv&&xv(qv.prototype.sort),zv=!(!Kv||Vv((function(){Kv(new qv(2),null)}))&&Vv((function(){Kv(new qv(2),{})}))),Yv=!!Kv&&!Vv((function(){if(Wv)return Wv<74;if(Bv)return Bv<67;if(Hv)return!0;if(Gv)return Gv<602;var e,t,i=new qv(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Kv(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));Jv("sort",(function(e){return void 0!==e&&Uv(e),Yv?Kv(this,e):Fv(jv(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))}),!Yv||zv);var Xv=nn,Qv=u,Zv=I,$v=x,ey=H,ty=M,iy=Am,ry=_n,ny=Se,oy=Om,sy=Hf,ay=rt("replace"),cy=TypeError,ly=Zv("".indexOf);Zv("".replace);var dy=Zv("".slice),uy=Math.max;Xv({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d,u=$v(this),h=0,p="";if(!ty(e)){if(iy(e)&&(i=ry($v(oy(e))),!~ly(i,"g")))throw new cy("`.replaceAll` does not allow non-global regexes");if(r=ny(e,ay))return Qv(r,e,u,t)}for(n=ry(u),o=ry(e),(s=ey(t))||(t=ry(t)),a=o.length,c=uy(1,a),l=ly(n,o);-1!==l;)d=s?ry(t(o,l,n)):sy(o,n,l,[],void 0,t),p+=dy(n,h,l)+d,h=l+a,l=l+c>n.length?-1:ly(n,o,l+c);return h<n.length&&(p+=dy(n,h)),p}});var hy={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},py=Et("span").classList,my=py&&py.constructor&&py.constructor.prototype,_y=my===Object.prototype?void 0:my,fy=uT.forEach,gy=Zs("forEach")?[].forEach:function(e){return fy(this,e,arguments.length>1?arguments[1]:void 0)},Ey=n,Ty=hy,vy=_y,yy=gy,Sy=Yt,Iy=function(e){if(e&&e.forEach!==yy)try{Sy(e,"forEach",yy)}catch(lq){e.forEach=yy}};for(var Ay in Ty)Ty[Ay]&&Iy(Ey[Ay]&&Ey[Ay].prototype);Iy(vy);var Ry=n,Cy=hy,by=_y,ky=Hs,Dy=Yt,wy=jo,Ny=rt("iterator"),Oy=ky.values,My=function(e,t){if(e){if(e[Ny]!==Oy)try{Dy(e,Ny,Oy)}catch(lq){e[Ny]=Oy}if(wy(e,t,!0),Cy[t])for(var i in ky)if(e[i]!==ky[i])try{Dy(e,i,ky[i])}catch(lq){e[i]=ky[i]}}};for(var Py in Cy)My(Ry[Py]&&Ry[Py].prototype,Py);My(by,"DOMTokenList");var Ly=ou.clear;nn({global:!0,bind:!0,enumerable:!0,forced:n.clearImmediate!==Ly},{clearImmediate:Ly});var xy=n,Vy=Rd,Uy=H,Fy=ra,By=X,Hy=_a,Wy=Nd,Gy=xy.Function,jy=/MSIE .\./.test(By)||"BUN"===Fy&&function(){var e=xy.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),Jy=nn,qy=n,Ky=ou.set,zy=function(e,t){var i=t?2:1;return jy?function(r,n){var o=Wy(arguments.length,1)>i,s=Uy(r)?r:Gy(r),a=o?Hy(arguments,i):[],c=o?function(){Vy(s,this,a)}:s;return t?e(c,n):e(c)}:e},Yy=qy.setImmediate?zy(Ky,!1):Ky;Jy({global:!0,bind:!0,enumerable:!0,forced:qy.setImmediate!==Yy},{setImmediate:Yy});var Xy=Nf.charAt,Qy=_n,Zy=wi,$y=ks,eS=Ds,tS="String Iterator",iS=Zy.set,rS=Zy.getterFor(tS);$y(String,"String",(function(e){iS(this,{type:tS,string:Qy(e),index:0})}),(function(){var e,t=rS(this),i=t.string,r=t.index;return r>=i.length?eS(void 0,!0):(e=Xy(i,r),t.index+=e.length,eS(e,!1))}));var nS=s,oS=a,sS=rt("iterator"),aS=!nS((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),r="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),r+=i+e})),i.delete("a",2),i.delete("b",void 0),!t.size&&!oS||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[sS]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==r||"x"!==new URL("https://x",void 0).host})),cS=a,lS=I,dS=u,uS=s,hS=Hn,pS=Dr,mS=h,_S=Be,fS=O,gS=Object.assign,ES=Object.defineProperty,TS=lS([].concat),vS=!gS||uS((function(){if(cS&&1!==gS({b:1},gS(ES({},"a",{enumerable:!0,get:function(){ES(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!==gS({},e)[i]||hS(gS({},t)).join("")!==r}))?function(e,t){for(var i=_S(e),r=arguments.length,n=1,o=pS.f,s=mS.f;r>n;)for(var a,c=fS(arguments[n++]),l=o?TS(hS(c),o(c)):hS(c),d=l.length,u=0;d>u;)a=l[u++],cS&&!dS(s,c,a)||(i[a]=c[a]);return i}:gS,yS=Lt,SS=gp,IS=a,AS=wt,RS=E,CS=Dd,bS=u,kS=Be,DS=function(e,t,i,r){try{return r?t(yS(i)[0],i[1]):t(i)}catch(lq){SS(e,"throw",lq)}},wS=ep,NS=ud,OS=mr,MS=function(e,t,i){IS?AS.f(e,t,RS(0,i)):e[t]=i},PS=pp,LS=sp,xS=Array,VS=I,US=2147483647,FS=/[^\0-\u007E]/,BS=/[.\u3002\uFF0E\uFF61]/g,HS="Overflow: input needs wider integers to process",WS=RangeError,GS=VS(BS.exec),jS=Math.floor,JS=String.fromCharCode,qS=VS("".charCodeAt),KS=VS([].join),zS=VS([].push),YS=VS("".replace),XS=VS("".split),QS=VS("".toLowerCase),ZS=function(e){return e+22+75*(e<26)},$S=function(e,t,i){var r=0;for(e=i?jS(e/700):e>>1,e+=jS(e/t);e>455;)e=jS(e/35),r+=36;return jS(r+36*e/(e+38))},eI=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=qS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=qS(e,i++);56320==(64512&o)?zS(t,((1023&n)<<10)+(1023&o)+65536):(zS(t,n),i--)}else zS(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&zS(t,JS(r));var c=t.length,l=c;for(c&&zS(t,"-");l<n;){var d=US;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>jS((US-s)/u))throw new WS(HS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>US)throw new WS(HS);if(r===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;zS(t,JS(ZS(m+_%f))),h=jS(_/f),p+=36}zS(t,JS(ZS(h))),a=$S(s,u,l===c),s=0,l++}}s++,o++}return KS(t,"")},tI=nn,iI=I,rI=lr,nI=RangeError,oI=String.fromCharCode,sI=String.fromCodePoint,aI=iI([].join);tI({target:"String",stat:!0,arity:1,forced:!!sI&&1!==sI.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],rI(t,1114111)!==t)throw new nI(t+" is not a valid code point");i[n]=t<65536?oI(t):oI(55296+((t-=65536)>>10),t%1024+56320)}return aI(i,"")}});var cI=nn,lI=n,dI=lu,uI=q,hI=u,pI=I,mI=a,_I=aS,fI=$i,gI=En,EI=za,TI=jo,vI=Qo,yI=wi,SI=Qa,II=H,AI=Ge,RI=Dd,CI=hn,bI=Lt,kI=G,DI=_n,wI=lo,NI=E,OI=pp,MI=sp,PI=Ds,LI=Nd,xI=Ta,VI=rt("iterator"),UI="URLSearchParams",FI=UI+"Iterator",BI=yI.set,HI=yI.getterFor(UI),WI=yI.getterFor(FI),GI=dI("fetch"),jI=dI("Request"),JI=dI("Headers"),qI=jI&&jI.prototype,KI=JI&&JI.prototype,zI=lI.TypeError,YI=lI.encodeURIComponent,XI=String.fromCharCode,QI=uI("String","fromCodePoint"),ZI=parseInt,$I=pI("".charAt),eA=pI([].join),tA=pI([].push),iA=pI("".replace),rA=pI([].shift),nA=pI([].splice),oA=pI("".split),sA=pI("".slice),aA=pI(/./.exec),cA=/\+/g,lA=/^[0-9a-f]+$/i,dA=function(e,t){var i=sA(e,t,t+2);return aA(lA,i)?ZI(i,16):NaN},uA=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},hA=function(e){var t=null;switch(e.length){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return t>1114111?null:t},pA=function(e){for(var t=(e=iA(e,cA," ")).length,i="",r=0;r<t;){var n=$I(e,r);if("%"===n){if("%"===$I(e,r+1)||r+3>t){i+="%",r++;continue}var o=dA(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var s=uA(o);if(0===s)n=XI(o);else{if(1===s||s>4){i+="�",r++;continue}for(var a=[o],c=1;c<s&&!(++r+3>t||"%"!==$I(e,r));){var l=dA(e,r+1);if(l!=l){r+=3;break}if(l>191||l<128)break;tA(a,l),r+=2,c++}if(a.length!==s){i+="�";continue}var d=hA(a);null===d?i+="�":n=QI(d)}}i+=n,r++}return i},mA=/[!'()~]|%20/g,_A={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},fA=function(e){return _A[e]},gA=function(e){return iA(YI(e),mA,fA)},EA=vI((function(e,t){BI(this,{type:FI,target:HI(e).entries,index:0,kind:t})}),UI,(function(){var e=WI(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,PI(void 0,!0);var r=t[i];switch(e.kind){case"keys":return PI(r.key,!1);case"values":return PI(r.value,!1)}return PI([r.key,r.value],!1)}),!0),TA=function(e){this.entries=[],this.url=null,void 0!==e&&(kI(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===$I(e,0)?sA(e,1):e:DI(e)))};TA.prototype={type:UI,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=this.entries,l=MI(e);if(l)for(i=(t=OI(e,l)).next;!(r=hI(i,t)).done;){if(o=(n=OI(bI(r.value))).next,(s=hI(o,n)).done||(a=hI(o,n)).done||!hI(o,n).done)throw new zI("Expected sequence with length 2");tA(c,{key:DI(s.value),value:DI(a.value)})}else for(var d in e)AI(e,d)&&tA(c,{key:d,value:DI(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=oA(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&(i=oA(t,"="),tA(r,{key:pA(rA(i)),value:pA(eA(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],tA(i,gA(e.key)+"="+gA(e.value));return eA(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var vA=function(){SI(this,yA);var e=BI(this,new TA(arguments.length>0?arguments[0]:void 0));mI||(this.size=e.entries.length)},yA=vA.prototype;if(EI(yA,{append:function(e,t){var i=HI(this);LI(arguments.length,2),tA(i.entries,{key:DI(e),value:DI(t)}),mI||this.length++,i.updateURL()},delete:function(e){for(var t=HI(this),i=LI(arguments.length,1),r=t.entries,n=DI(e),o=i<2?void 0:arguments[1],s=void 0===o?o:DI(o),a=0;a<r.length;){var c=r[a];if(c.key!==n||void 0!==s&&c.value!==s)a++;else if(nA(r,a,1),void 0!==s)break}mI||(this.size=r.length),t.updateURL()},get:function(e){var t=HI(this).entries;LI(arguments.length,1);for(var i=DI(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=HI(this).entries;LI(arguments.length,1);for(var i=DI(e),r=[],n=0;n<t.length;n++)t[n].key===i&&tA(r,t[n].value);return r},has:function(e){for(var t=HI(this).entries,i=LI(arguments.length,1),r=DI(e),n=i<2?void 0:arguments[1],o=void 0===n?n:DI(n),s=0;s<t.length;){var a=t[s++];if(a.key===r&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var i=HI(this);LI(arguments.length,1);for(var r,n=i.entries,o=!1,s=DI(e),a=DI(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?nA(n,c--,1):(o=!0,r.value=a));o||tA(n,{key:s,value:a}),mI||(this.size=n.length),i.updateURL()},sort:function(){var e=HI(this);xI(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=HI(this).entries,r=RI(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new EA(this,"keys")},values:function(){return new EA(this,"values")},entries:function(){return new EA(this,"entries")}},{enumerable:!0}),fI(yA,VI,yA.entries,{name:"entries"}),fI(yA,"toString",(function(){return HI(this).serialize()}),{enumerable:!0}),mI&&gI(yA,"size",{get:function(){return HI(this).entries.length},configurable:!0,enumerable:!0}),TI(vA,UI),cI({global:!0,constructor:!0,forced:!_I},{URLSearchParams:vA}),!_I&&II(JI)){var SA=pI(KI.has),IA=pI(KI.set),AA=function(e){if(kI(e)){var t,i=e.body;if(CI(i)===UI)return t=e.headers?new JI(e.headers):new JI,SA(t,"content-type")||IA(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),wI(e,{body:NI(0,DI(i)),headers:NI(0,t)})}return e};if(II(GI)&&cI({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return GI(e,arguments.length>1?AA(arguments[1]):{})}}),II(jI)){var RA=function(e){return SI(this,qI),new jI(e,arguments.length>1?AA(arguments[1]):{})};qI.constructor=RA,RA.prototype=qI,cI({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:RA})}}var CA,bA=nn,kA=a,DA=aS,wA=n,NA=Dd,OA=I,MA=$i,PA=En,LA=Qa,xA=Ge,VA=vS,UA=function(e){var t=kS(e),i=NS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=CS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=LS(t),p=0;if(!h||this===xS&&wS(h))for(s=OS(t),a=i?new this(s):xS(s);s>p;p++)u=o?n(t[p],p):t[p],MS(a,p,u);else for(a=i?new this:[],d=(l=PS(t,h)).next;!(c=bS(d,l)).done;p++)u=o?DS(l,n,[c.value,p],!0):c.value,MS(a,p,u);return a.length=p,a},FA=_a,BA=Nf.codeAt,HA=function(e){var t,i,r=[],n=XS(YS(QS(e),BS,"."),".");for(t=0;t<n.length;t++)i=n[t],zS(r,GS(FS,i)?"xn--"+eI(i):i);return KS(r,".")},WA=_n,GA=jo,jA=Nd,JA={URLSearchParams:vA,getState:HI},qA=wi,KA=qA.set,zA=qA.getterFor("URL"),YA=JA.URLSearchParams,XA=JA.getState,QA=wA.URL,ZA=wA.TypeError,$A=wA.parseInt,eR=Math.floor,tR=Math.pow,iR=OA("".charAt),rR=OA(/./.exec),nR=OA([].join),oR=OA(1..toString),sR=OA([].pop),aR=OA([].push),cR=OA("".replace),lR=OA([].shift),dR=OA("".split),uR=OA("".slice),hR=OA("".toLowerCase),pR=OA([].unshift),mR="Invalid scheme",_R="Invalid host",fR="Invalid port",gR=/[a-z]/i,ER=/[\d+-.a-z]/i,TR=/\d/,vR=/^0x/i,yR=/^[0-7]+$/,SR=/^\d+$/,IR=/^[\da-f]+$/i,AR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,RR=/[\0\t\n\r #/:<>?@[\\\]^|]/,CR=/^[\u0000-\u0020]+/,bR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,kR=/[\t\n\r]/g,DR=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)pR(t,e%256),e=eR(e/256);return nR(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i?r:t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=oR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},wR={},NR=VA({},wR,{" ":1,'"':1,"<":1,">":1,"`":1}),OR=VA({},NR,{"#":1,"?":1,"{":1,"}":1}),MR=VA({},OR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),PR=function(e,t){var i=BA(e,0);return i>32&&i<127&&!xA(t,e)?e:encodeURIComponent(e)},LR={ftp:21,file:null,http:80,https:443,ws:80,wss:443},xR=function(e,t){var i;return 2===e.length&&rR(gR,iR(e,0))&&(":"===(i=iR(e,1))||!t&&"|"===i)},VR=function(e){var t;return e.length>1&&xR(uR(e,0,2))&&(2===e.length||"/"===(t=iR(e,2))||"\\"===t||"?"===t||"#"===t)},UR=function(e){return"."===e||"%2e"===hR(e)},FR={},BR={},HR={},WR={},GR={},jR={},JR={},qR={},KR={},zR={},YR={},XR={},QR={},ZR={},$R={},eC={},tC={},iC={},rC={},nC={},oC={},sC=function(e,t,i){var r,n,o,s=WA(e);if(t){if(n=this.parse(s))throw new ZA(n);this.searchParams=null}else{if(void 0!==i&&(r=new sC(i,!0)),n=this.parse(s,null,r))throw new ZA(n);(o=XA(new YA)).bindURL(this),this.searchParams=o}};sC.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||FR,d=0,u="",h=!1,p=!1,m=!1;for(e=WA(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=cR(e,CR,""),e=cR(e,bR,"$1")),e=cR(e,kR,""),r=UA(e);d<=r.length;){switch(n=r[d],l){case FR:if(!n||!rR(gR,n)){if(t)return mR;l=HR;continue}u+=hR(n),l=BR;break;case BR:if(n&&(rR(ER,n)||"+"===n||"-"===n||"."===n))u+=hR(n);else{if(":"!==n){if(t)return mR;u="",l=HR,d=0;continue}if(t&&(c.isSpecial()!==xA(LR,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&LR[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?l=ZR:c.isSpecial()&&i&&i.scheme===c.scheme?l=WR:c.isSpecial()?l=qR:"/"===r[d+1]?(l=GR,d++):(c.cannotBeABaseURL=!0,aR(c.path,""),l=rC)}break;case HR:if(!i||i.cannotBeABaseURL&&"#"!==n)return mR;if(i.cannotBeABaseURL&&"#"===n){c.scheme=i.scheme,c.path=FA(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=oC;break}l="file"===i.scheme?ZR:jR;continue;case WR:if("/"!==n||"/"!==r[d+1]){l=jR;continue}l=KR,d++;break;case GR:if("/"===n){l=zR;break}l=iC;continue;case jR:if(c.scheme=i.scheme,n===CA)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=FA(i.path),c.query=i.query;else if("/"===n||"\\"===n&&c.isSpecial())l=JR;else if("?"===n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=FA(i.path),c.query="",l=nC;else{if("#"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=FA(i.path),c.path.length--,l=iC;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=FA(i.path),c.query=i.query,c.fragment="",l=oC}break;case JR:if(!c.isSpecial()||"/"!==n&&"\\"!==n){if("/"!==n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=iC;continue}l=zR}else l=KR;break;case qR:if(l=KR,"/"!==n||"/"!==iR(u,d+1))continue;d++;break;case KR:if("/"!==n&&"\\"!==n){l=zR;continue}break;case zR:if("@"===n){h&&(u="%40"+u),h=!0,o=UA(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!==f||m){var g=PR(f,MR);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n===CA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(h&&""===u)return"Invalid authority";d-=UA(u).length+1,u="",l=YR}else u+=n;break;case YR:case XR:if(t&&"file"===c.scheme){l=eC;continue}if(":"!==n||p){if(n===CA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()){if(c.isSpecial()&&""===u)return _R;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=tC,t)return;continue}"["===n?p=!0:"]"===n&&(p=!1),u+=n}else{if(""===u)return _R;if(s=c.parseHost(u))return s;if(u="",l=QR,t===XR)return}break;case QR:if(!rR(TR,n)){if(n===CA||"/"===n||"?"===n||"#"===n||"\\"===n&&c.isSpecial()||t){if(""!==u){var E=$A(u,10);if(E>65535)return fR;c.port=c.isSpecial()&&E===LR[c.scheme]?null:E,u=""}if(t)return;l=tC;continue}return fR}u+=n;break;case ZR:if(c.scheme="file","/"===n||"\\"===n)l=$R;else{if(!i||"file"!==i.scheme){l=iC;continue}switch(n){case CA:c.host=i.host,c.path=FA(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=FA(i.path),c.query="",l=nC;break;case"#":c.host=i.host,c.path=FA(i.path),c.query=i.query,c.fragment="",l=oC;break;default:VR(nR(FA(r,d),""))||(c.host=i.host,c.path=FA(i.path),c.shortenPath()),l=iC;continue}}break;case $R:if("/"===n||"\\"===n){l=eC;break}i&&"file"===i.scheme&&!VR(nR(FA(r,d),""))&&(xR(i.path[0],!0)?aR(c.path,i.path[0]):c.host=i.host),l=iC;continue;case eC:if(n===CA||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&xR(u))l=iC;else if(""===u){if(c.host="",t)return;l=tC}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",l=tC}continue}u+=n;break;case tC:if(c.isSpecial()){if(l=iC,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==CA&&(l=iC,"/"!==n))continue}else c.fragment="",l=oC;else c.query="",l=nC;break;case iC:if(n===CA||"/"===n||"\\"===n&&c.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(a=hR(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===n||"\\"===n&&c.isSpecial()||aR(c.path,"")):UR(u)?"/"===n||"\\"===n&&c.isSpecial()||aR(c.path,""):("file"===c.scheme&&!c.path.length&&xR(u)&&(c.host&&(c.host=""),u=iR(u,0)+":"),aR(c.path,u)),u="","file"===c.scheme&&(n===CA||"?"===n||"#"===n))for(;c.path.length>1&&""===c.path[0];)lR(c.path);"?"===n?(c.query="",l=nC):"#"===n&&(c.fragment="",l=oC)}else u+=PR(n,OR);break;case rC:"?"===n?(c.query="",l=nC):"#"===n?(c.fragment="",l=oC):n!==CA&&(c.path[0]+=PR(n,wR));break;case nC:t||"#"!==n?n!==CA&&("'"===n&&c.isSpecial()?c.query+="%27":c.query+="#"===n?"%23":PR(n,wR)):(c.fragment="",l=oC);break;case oC:n!==CA&&(c.fragment+=PR(n,NR))}d++}},parseHost:function(e){var t,i,r;if("["===iR(e,0)){if("]"!==iR(e,e.length-1))return _R;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return iR(e,u)};if(":"===h()){if(":"!==iR(e,1))return;u+=2,d=++l}for(;h();){if(8===l)return;if(":"!==h()){for(t=i=0;i<4&&rR(IR,h());)t=16*t+$A(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,l>6)return;for(r=0;h();){if(n=null,r>0){if(!("."===h()&&r<4))return;u++}if(!rR(TR,h()))return;for(;rR(TR,h());){if(o=$A(h(),10),null===n)n=o;else{if(0===n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!==r||l++}if(4!==r)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}(uR(e,1,-1)),!t)return _R;this.host=t}else if(this.isSpecial()){if(e=HA(e),rR(AR,e))return _R;if(t=function(e){var t,i,r,n,o,s,a,c=dR(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(n=c[r]))return e;if(o=10,n.length>1&&"0"===iR(n,0)&&(o=rR(vR,n)?16:8,n=uR(n,8===o?1:2)),""===n)s=0;else{if(!rR(10===o?SR:8===o?yR:IR,n))return e;s=$A(n,o)}aR(i,s)}for(r=0;r<t;r++)if(s=i[r],r===t-1){if(s>=tR(256,5-t))return null}else if(s>255)return null;for(a=sR(i),r=0;r<i.length;r++)a+=i[r]*tR(256,3-r);return a}(e),null===t)return _R;this.host=t}else{if(rR(RR,e))return _R;for(t="",i=UA(e),r=0;r<i.length;r++)t+=PR(i[r],wR);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return xA(LR,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&xR(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=DR(n),null!==o&&(l+=":"+o)):"file"===t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+nR(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw new ZA(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new aC(e.path[0]).origin}catch(lq){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+DR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(WA(e)+":",FR)},getUsername:function(){return this.username},setUsername:function(e){var t=UA(WA(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=PR(t[i],MR)}},getPassword:function(){return this.password},setPassword:function(e){var t=UA(WA(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=PR(t[i],MR)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?DR(e):DR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,YR)},getHostname:function(){var e=this.host;return null===e?"":DR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,XR)},getPort:function(){var e=this.port;return null===e?"":WA(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=WA(e))?this.port=null:this.parse(e,QR))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+nR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,tC))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=WA(e))?this.query=null:("?"===iR(e,0)&&(e=uR(e,1)),this.query="",this.parse(e,nC)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=WA(e))?("#"===iR(e,0)&&(e=uR(e,1)),this.fragment="",this.parse(e,oC)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var aC=function(e){var t=LA(this,cC),i=jA(arguments.length,1)>1?arguments[1]:void 0,r=KA(t,new sC(e,!1,i));kA||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},cC=aC.prototype,lC=function(e,t){return{get:function(){return zA(this)[e]()},set:t&&function(e){return zA(this)[t](e)},configurable:!0,enumerable:!0}};if(kA&&(PA(cC,"href",lC("serialize","setHref")),PA(cC,"origin",lC("getOrigin")),PA(cC,"protocol",lC("getProtocol","setProtocol")),PA(cC,"username",lC("getUsername","setUsername")),PA(cC,"password",lC("getPassword","setPassword")),PA(cC,"host",lC("getHost","setHost")),PA(cC,"hostname",lC("getHostname","setHostname")),PA(cC,"port",lC("getPort","setPort")),PA(cC,"pathname",lC("getPathname","setPathname")),PA(cC,"search",lC("getSearch","setSearch")),PA(cC,"searchParams",lC("getSearchParams")),PA(cC,"hash",lC("getHash","setHash"))),MA(cC,"toJSON",(function(){return zA(this).serialize()}),{enumerable:!0}),MA(cC,"toString",(function(){return zA(this).serialize()}),{enumerable:!0}),QA){var dC=QA.createObjectURL,uC=QA.revokeObjectURL;dC&&MA(aC,"createObjectURL",NA(dC,QA)),uC&&MA(aC,"revokeObjectURL",NA(uC,QA))}GA(aC,"URL"),bA({global:!0,constructor:!0,forced:!DA,sham:!kA},{URL:aC});var hC=u;nn({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return hC(URL.prototype.toString,this)}});let pC=!0,mC=!0;function _C(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function fC(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.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 r=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,r])},Object.defineProperty(r,"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 gC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(pC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function EC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(mC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function TC(){if("object"==typeof window){if(pC)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function vC(e,t){mC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function yC(e){return"[object Object]"===Object.prototype.toString.call(e)}function SC(e){return yC(e)?Object.keys(e).reduce((function(t,i){const r=yC(e[i]),n=r?SC(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function IC(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?IC(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{IC(e,e.get(t),i)}))})))}function AC(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&IC(e,i,n)}))})),n}const RC=TC;function CC(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=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 r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(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=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>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=r(e.video),RC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return RC("chrome: "+JSON.stringify(e)),n(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,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(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 bC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function kC(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 r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else fC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function DC(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,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.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 r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.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 wC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=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 n=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 r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function NC(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=>AC(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}),fC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>AC(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,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||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 OC(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 r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};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 r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=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]})),n.apply(this,arguments)}}function MC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return OC(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 r=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}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.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 r=[].slice.call(arguments,1);if(1!==r.length||!r[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 n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[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]=r[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 r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.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 PC(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],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function LC(e,t){fC(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var xC=Object.freeze({__proto__:null,shimMediaStream:bC,shimOnTrack:kC,shimGetSendersWithDtmf:DC,shimGetStats:wC,shimSenderReceiverGetStats:NC,shimAddTrackRemoveTrackWithNative:OC,shimAddTrackRemoveTrack:MC,shimPeerConnection:PC,fixNegotiationNeeded:LC,shimGetUserMedia:CC,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 r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function VC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){vC("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(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)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.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 UC(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 FC(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],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(pk){if("TypeError"!==pk.name)throw pk;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function BC(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 HC(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}),fC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function WC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){vC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function GC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function jC(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 r=t.apply(this,arguments);if(i){const{sender:t}=r,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 r})}function JC(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 qC(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 KC(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 zC=Object.freeze({__proto__:null,shimOnTrack:UC,shimPeerConnection:FC,shimSenderGetStats:BC,shimReceiverGetStats:HC,shimRemoveStream:WC,shimRTCDataChannel:GC,shimAddTransceiver:jC,shimGetParameters:JC,shimCreateOffer:qC,shimCreateAnswer:KC,shimGetUserMedia:VC,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 YC(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 XC(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 QC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function ZC(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($C(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function $C(e){return e&&void 0!==e.video?Object.assign({},e,{video:SC(e.video)}):e}function eb(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 r=e.iceServers[i];void 0===r.urls&&r.url?(vC("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):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 tb(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 ib(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 rb(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var nb=Object.freeze({__proto__:null,shimLocalStreamsAPI:YC,shimRemoteStreamsAPI:XC,shimCallbacksAPI:QC,shimGetUserMedia:ZC,shimConstraints:$C,shimRTCIceServerUrls:eb,shimTrackEventTransceiver:tb,shimCreateOfferLegacy:ib,shimAudioContext:rb}),ob={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+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 r=e.type;return t.push("typ"),t.push(r),"host"!==r&&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 r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].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 r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.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)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+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 r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.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:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.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 r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.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]),r.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),n&&(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={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.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 r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=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:n};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:n}}},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,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[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}(ob);var sb=ob.exports,ab=i(sb),cb=e({__proto__:null,default:ab},[sb]);function lb(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),r=ab.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[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,fC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function db(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||fC(e,"icecandidate",(e=>{if(e.candidate){const t=ab.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function ub(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=ab.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ab.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),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=ab.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function hb(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>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},fC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function pb(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 mb(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 _b(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 fb(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 gb=Object.freeze({__proto__:null,shimRTCIceCandidate:lb,shimRTCIceCandidateRelayProtocol:db,shimMaxMessageSize:ub,shimSendThrowTypeError:hb,shimConnectionState:pb,removeExtmapAllowMixed:mb,shimAddIceCandidateNullOrEmpty:_b,shimParameterlessSetLocalDescription:fb});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=TC,r=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=_C(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=_C(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=_C(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:gb,extractVersion:_C,disableLog:gC,disableWarnings:EC,sdp:cb};switch(r.browser){case"chrome":if(!xC||!PC||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=xC,_b(e,r),fb(e),CC(e,r),bC(e),PC(e,r),kC(e),MC(e,r),DC(e),wC(e),NC(e),LC(e,r),lb(e),db(e),pb(e),ub(e,r),hb(e),mb(e,r);break;case"firefox":if(!zC||!FC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=zC,_b(e,r),fb(e),VC(e,r),FC(e,r),UC(e),WC(e),BC(e),HC(e),GC(e),jC(e),JC(e),qC(e),KC(e),lb(e),pb(e),ub(e,r),hb(e);break;case"safari":if(!nb||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=nb,_b(e,r),fb(e),eb(e),ib(e),QC(e),YC(e),XC(e),tb(e),ZC(e),rb(e),lb(e),db(e),ub(e,r),hb(e),mb(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var Eb,Tb=Object.create,vb=Object.defineProperty,yb=Object.defineProperties,Sb=Object.getOwnPropertyDescriptor,Ib=Object.getOwnPropertyDescriptors,Ab=Object.getOwnPropertyNames,Rb=Object.getOwnPropertySymbols,Cb=Object.getPrototypeOf,bb=Object.prototype.hasOwnProperty,kb=Object.prototype.propertyIsEnumerable,Db=Reflect.get,wb=Math.pow,Nb=(e,t,i)=>t in e?vb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ob=(e,t)=>{for(var i in t||(t={}))bb.call(t,i)&&Nb(e,i,t[i]);if(Rb)for(var i of Rb(t))kb.call(t,i)&&Nb(e,i,t[i]);return e},Mb=(e,t)=>yb(e,Ib(t)),Pb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Lb=(e,t)=>{for(var i in t)vb(e,i,{get:t[i],enumerable:!0})},xb=(e,t,i)=>(i=null!=e?Tb(Cb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of Ab(t))!bb.call(e,n)&&n!==i&&vb(e,n,{get:()=>t[n],enumerable:!(r=Sb(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:vb(i,"default",{value:e,enumerable:!0}),e)),Vb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?Sb(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&vb(t,i,o),o},Ub=(e,t,i)=>Nb(e,"symbol"!=typeof t?t+"":t,i),Fb=(e,t,i)=>Db(Cb(e),i,t),Bb=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(jM){n(jM)}},s=e=>{try{a(i.throw(e))}catch(jM){n(jM)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),Hb=Pb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+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 n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+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,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,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,n);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,n){var o=r?r+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&&(!n||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||n&&!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=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),Wb=Pb(((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")}))}))})),Gb=Pb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=Wb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[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=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+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,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),jb=Pb(((e,t)=>{var i=Wb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[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?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},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 r=t.outerOrder||s,n=t.innerOrder||a,c=[];return 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))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),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))}))}))}))})),c.join("\r\n")+"\r\n"}})),Jb=Pb((e=>{var t=Gb(),i=jb(),r=Wb();e.grammar=r,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})),qb=Pb(((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")}))}))})),Kb=Pb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=qb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[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=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+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,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),zb=Pb(((e,t)=>{var i=qb(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[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?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},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 r=t.outerOrder||s,n=t.innerOrder||a,c=[];return 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))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),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))}))}))}))})),c.join("\r\n")+"\r\n"}})),Yb=Pb((e=>{var t=Kb(),i=zb();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})),Xb=xb(Hb()),Qb=((Eb=Qb||{})[Eb.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Eb[Eb.INVALID_OPERATION=4097]="INVALID_OPERATION",Eb[Eb.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Eb[Eb.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Eb[Eb.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Eb[Eb.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Eb[Eb.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Eb[Eb.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Eb[Eb.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Eb[Eb.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Eb[Eb.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Eb[Eb.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Eb[Eb.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Eb[Eb.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Eb[Eb.CLIENT_BANNED=16448]="CLIENT_BANNED",Eb[Eb.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Eb[Eb.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Eb[Eb.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Eb[Eb.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Eb[Eb.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Eb[Eb.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Eb[Eb.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Eb[Eb.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Eb[Eb.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Eb[Eb.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Eb[Eb.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Eb[Eb.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Eb[Eb.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Eb[Eb.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Eb[Eb.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Eb[Eb.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Eb[Eb.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Eb[Eb.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Eb[Eb.UNKNOWN=65535]="UNKNOWN",Eb),Zb=Qb,$b=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Zb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in Zb)if(Zb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),Ub(this,"code"),Ub(this,"extraCode"),Ub(this,"message"),Ub(this,"originMessage"),Ub(this,"name"),Ub(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ek=$b,tk=0,ik=!0,rk=function(e){tk=e;let t=new Date;t.setTime(t.getTime()+e),UM[ik?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(e)),ik=!1},nk=function(){return tk},ok=function(){return Date.now()+tk},sk=function(){let e=new Date;return e.setTime(ok()),e.toLocaleString()},ak=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},ck={};Lb(ck,{REPORT_TYPE:()=>gN,buildSSOPackage:()=>EN,bytes2ms:()=>Ew,calculateScaleResolutionDownNumber:()=>pN,concatArrayBuffers:()=>TN,convertObjectNumberToInt:()=>cN,copyProperties:()=>gw,deepClone:()=>Zw,deepCloneBasic:()=>fN,deepMerge:()=>Qw,delay:()=>lN,fibonacci:()=>Rw,formatedTime:()=>tN,getConstructorName:()=>Fw,getContainerFromElement:()=>eN,getEnv:()=>lw,getFirst16Bits:()=>yN,getInternalVersion:()=>Jw,getLast16Bits:()=>vN,getLoggerUrl:()=>uw,getMediaStreamTrackInfo:()=>hN,getMuteStateFromFlag:()=>zw,getNetworkType:()=>pw,getNumNetworkType:()=>fw,getReconnectionTimeout:()=>Cw,getStringByteLength:()=>nN,getTurnServer:()=>Yw,getUint32Version:()=>aN,getValueType:()=>bw,getViewListFromView:()=>$w,glog:()=>Sw,ipv4ToUint32:()=>Xw,isArray:()=>Pw,isAudioWorkletSupported:()=>Bw,isBoolean:()=>Ow,isConstructor:()=>Uw,isEmpty:()=>Kw,isFunction:()=>kw,isLangChinese:()=>Iw,isMediaStreamTrack:()=>Lw,isNumber:()=>Nw,isObject:()=>Mw,isOverseaSdkAppId:()=>dw,isPlainObject:()=>Aw,isPortrait:()=>oN,isPromise:()=>Vw,isRemoteTrack:()=>xw,isRotate90Or270:()=>mN,isSetSinkIdSupported:()=>Hw,isString:()=>ww,isUndefined:()=>Dw,loadImage:()=>sN,loadVideo:()=>_N,ms2bytes:()=>vw,ms2samples:()=>yw,normalizeUrl:()=>uN,performanceNow:()=>Gw,promiseAny:()=>Ww,samples2ms:()=>Tw,setNetworkType:()=>_w,stringify:()=>iN,stringifyIncludeValue:()=>rN,throttlePromise:()=>dN});var lk={};Lb(lk,{AUDIO_MUTE_BIT:()=>Yk,AUDIO_STAT_BIT:()=>zk,AUX_STAT_BIT:()=>Kk,AUX_STREAM_MSID:()=>eD,BACKEND_ENV:()=>Gk,BASE_DOC_URL:()=>Ak,BASE_HOST:()=>vk,CAPABILITIES_KEYS:()=>HD,CLASS_NAME:()=>OD,CLOUD_CONSOLE_URL:()=>Ik,CROSS_ROOM_BIT:()=>Zk,DATA_FREEZE_TIMING:()=>RD,DOC_URL:()=>Rk,DTLS_STATE_UNKNOWN:()=>dD,ENV_NAME:()=>wk,EXCHANGE_SDP_TIMEOUT:()=>vD,IS_WORKER:()=>_k,IS_WORKLET:()=>fk,KIBANA_EVENT:()=>gD,LOCAL_STREAM_PUBLISH_STATE:()=>AD,LOGGER_CMD_TYPE:()=>Dk,LOGGER_DOMAIN:()=>Ck,LOGGER_DOMAIN_OVERSEA:()=>bk,LOG_LEVEL:()=>Nk,LOG_LEVEL_NAME:()=>VD,MAIN_STREAM_MSID:()=>$k,MAX_RTT:()=>WD,MICROPHONE_COMMUNICATIONS:()=>xD,MICROPHONE_DEFAULT:()=>PD,MUTE_ALL_BIT:()=>Qk,NAME:()=>Hk,NETWORK_TYPE:()=>Pk,NOT_SUPPORTED_H264:()=>ID,PAUSED_RETRY_COUNT:()=>MD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>DD,PEER_CONNECTION_STATE:()=>uD,PEER_LEAVE_REASON:()=>UD,RECOVER_CAPTURE_INTERVAL:()=>BD,REMOTE_STREAM_TYPE_AUX:()=>iD,REMOTE_STREAM_TYPE_MAIN:()=>tD,RENDER_FREEZE_TIMING:()=>CD,SCHEDULE_DOMAIN:()=>wD,SCHEDULE_TIMEOUT:()=>ND,SDP_SEMANTICS_PLAN_B:()=>SD,SDP_SEMANTICS_UNIFIED_PLAN:()=>yD,SECOND_HOST:()=>yk,SIGNAL_PING_PONG_INTERVAL:()=>Mk,SIGNAL_PING_TIMEOUT:()=>Ok,SIGNAL_RECONNECTION_COUNT:()=>fD,SMALL_STAT_BIT:()=>qk,SPEAKER_DEFAULT:()=>LD,STORAGE_EXPIRES_TIME:()=>Lk,STREAM_TYPE_BIG:()=>bD,STREAM_TYPE_SMALL:()=>kD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>FD,SYNC_USER_LIST_INTERVAL:()=>ED,Scene:()=>jk,THIRD_HOST:()=>Sk,TRANSPORT_DIRECTION:()=>Wk,TRTC_ERROR_ASSISTANCE:()=>kk,TRTC_QUALITY_BAD:()=>aD,TRTC_QUALITY_DISCONNECTED:()=>lD,TRTC_QUALITY_EXCELLENT:()=>nD,TRTC_QUALITY_GOOD:()=>oD,TRTC_QUALITY_POOR:()=>sD,TRTC_QUALITY_UNKNOWN:()=>rD,TRTC_QUALITY_VERY_BAD:()=>cD,UPDATE_OFFER_TIMEOUT:()=>TD,VIDEO_MUTE_BIT:()=>Xk,VIDEO_STAT_BIT:()=>Jk,audioProfileMap:()=>xk,defaultBigVideoProfile:()=>Uk,defaultSmallVideoProfile:()=>Fk,getRetryCount:()=>mD,getScriptDir:()=>gk,innerVersion:()=>dk,loggerProxy:()=>Ek,screenProfileMap:()=>Bk,setLoggerProxy:()=>Tk,setRetryCount:()=>pD,setVersion:()=>hk,version:()=>uk,videoProfileMap:()=>Vk});var dk="4.15.00.1600",uk="5.0.0";function hk(e){uk=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));dk="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var pk,mk,_k="undefined"!=typeof importScripts,fk="undefined"!=typeof registerProcessor,gk=()=>{let e=_k?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Ek="",Tk=e=>Ek=e,vk="web.sdk.qcloud.com",yk="web.sdk.tencent.cn",Sk="web.sdk.cloud.tencent.cn",Ik="https://console.cloud.tencent.com/trtc",Ak="https://".concat(vk,"/trtc/webrtc/v5/doc"),Rk="".concat(Ak,"/zh-cn/"),Ck="https://yun.tim.qq.com",bk="https://apisgp.my-imcloud.com",kk="trtc_error_assistance",Dk={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},wk={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Nk=((mk=Nk||{})[mk.TRACE=0]="TRACE",mk[mk.DEBUG=1]="DEBUG",mk[mk.INFO=2]="INFO",mk[mk.WARN=3]="WARN",mk[mk.ERROR=4]="ERROR",mk[mk.NONE=5]="NONE",mk),Ok=18e3,Mk=2e3,Pk={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Lk=6048e5,xk={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},Vk={"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}},Uk=Vk["480p_2"],Fk=Vk["120p_2"],Bk={"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}},Hk={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",LOADEDMETADATA:"loadedmetadata",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",RESIZE:"resize",TIME_UPDATE:"timeupdate"},Wk={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Gk={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},jk=((pk=jk||{}).LIVE="live",pk.RTC="rtc",pk),Jk=1,qk=2,Kk=4,zk=8,Yk=64,Xk=16,Qk=112,Zk=128,$k="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",eD="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",tD=Hk.MAIN,iD=Hk.AUXILIARY,rD=0,nD=1,oD=2,sD=3,aD=4,cD=5,lD=6,dD="unknown",uD={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},hD=1/0;function pD(e){hD=e}function mD(){return hD}var _D,fD=30,gD={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},ED=1e4,TD=1e4,vD=1e4,yD="unified-plan",SD="plan-b",ID=1028,AD=((_D=AD||{})[_D.UNPUBLISH=-1]="UNPUBLISH",_D[_D.PUBLISHING=0]="PUBLISHING",_D[_D.PUBLISHED=1]="PUBLISHED",_D),RD=500,CD=1e3,bD=Hk.BIG,kD=Hk.SMALL,DD=1e4,wD={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},ND=2e3,OD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},MD=5,PD="default",LD=PD,xD="communications",VD=Object.keys(Nk),UD=["normal leave","timeout leave","kick","role change"],FD=10,BD=2e3,HD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],WD=1e4,GD=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))},jD=Symbol(32),JD=Symbol(16),qD=Symbol(8),KD=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,t){return t&&this.consume(),this.need=e,this.flush()}read(e){return GD(this,void 0,void 0,(function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise(((t,i)=>{var r;this.reject=i,this.resolve=e=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(e)},this.demand(e,!0)||null===(r=this.pull)||void 0===r||r.call(this,e)}))}))}readU32(){return this.read(jD)}readU16(){return this.read(JD)}readU8(){return this.read(qD)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),null===(e=this.reject)||void 0===e||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null,t=this.buffer.subarray(this.consumed),i=0,r=e=>t.length<(i=e);if("number"==typeof this.need){if(r(this.need))return;e=t.subarray(0,i)}else if(this.need===jD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===JD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===qD){if(r(1))return;e=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,i)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,i)),e=this.need}return this.consumed+=i,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise((e=>this.pull=e));this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){let t=this.buffer.length,i=t+e;if(i<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,i);else{let e=new Uint8Array(i);e.set(this.buffer),this.buffer=e}return this.buffer.subarray(t,i)}return this.buffer=new Uint8Array(e),this.buffer}};KD.U32=jD,KD.U16=JD,KD.U8=qD;var zD=128;function YD(e){let t=new KD;for(;e>=128;)t.malloc(1)[0]=255&e|zD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function XD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new KD,r=t<<3;switch(typeof e){case"boolean":let n=i.malloc(2);n[0]=r,n[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(YD(e));break;case"string":i.malloc(1)[0]=2|r;let o=(new TextEncoder).encode(e);i.write(YD(o.length));let s=i.malloc(o.length);for(let e=0;e<o.length;e++)s[e]=o[e];break;case"object":let a=new KD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=XD(e[t],t+1);i&&a.write(i)}else{let t=1;for(let i in e){let r=XD(e[i],t++);r&&a.write(r)}}0===t?a.buffer&&i.write(a.buffer):(i.malloc(1)[0]=2|r,a.buffer&&(i.write(YD(a.buffer.length)),i.write(a.buffer)))}return i.buffer||new Uint8Array(0)}var QD=class{constructor(){Ub(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(e){this.buffer.push(e>>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let t=0;t<e.length;t++)this.buffer.push(e[t])}};function ZD(e,t,i){e[i]=t>>>24&255,e[i+1]=t>>>16&255,e[i+2]=t>>>8&255,e[i+3]=255&t}function $D(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ew(e,t){return e[t]}function tw(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var iw=0,rw=2654435769,nw=16,ow=2,sw=7;function aw(e,t){let i=new QD,r=function(e,t,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&void 0!==arguments[4]?arguments[4]:2e3,encryption:arguments.length>5&&void 0!==arguments[5]?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&void 0!==arguments[6]?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:i,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}(t,e,iw);iw=iw+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let n=(new TextEncoder).encode(r.d2);i.writeInt32(n.length+4),n&&i.writeBytes(n),i.writeByte(r.uinType);let o=(new TextEncoder).encode(r.uin);i.writeInt32(o.length+4),o.length&&i.writeBytes(o);let s=new QD;s.writeInt32(0),s.writeInt32(r.reqHead.seqNumber),s.writeInt32(r.reqHead.appId),s.writeByte(r.reqHead.appId>>>24&255),s.writeByte(r.reqHead.appId>>>16&255),s.writeByte(r.reqHead.appId>>>8&255),s.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)s.writeByte(0);let a=(new TextEncoder).encode(r.reqHead.a2);s.writeInt32(a.length+4),a.length&&s.writeBytes(a);let c=(new TextEncoder).encode(r.reqHead.serviceCmd);s.writeInt32(c.length+4),c.length&&s.writeBytes(c);let l=(new TextEncoder).encode(r.reqHead.cookie);s.writeInt32(l.length+4),l.length&&s.writeBytes(l);let d=(new TextEncoder).encode(r.reqHead.imei);s.writeInt32(d.length+4),d.length&&s.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);s.writeInt32(u.length+4),u.length&&s.writeBytes(u);let h=(new TextEncoder).encode(r.reqHead.clientVersionInfo);s.writeInt16(h.length+2),h.length&&s.writeBytes(h);let p=s.length;s.data[0]=p>>>24&255,s.data[1]=p>>>16&255,s.data[2]=p>>>8&255,s.data[3]=255&p,ww(e)&&(e=(new TextEncoder).encode(e)),s.writeInt32(e.length+4),e.length&&s.writeBytes(e);let m=new Uint8Array(s.data),_=null;1===r.encryption?_=(new TextEncoder).encode(r.uin):2===r.encryption&&(_=new Uint8Array(16)),_&&(m=function(e,t){let i=e.length,r=(i+1+ow+sw)%8;r&&(r=8-r);let n=i+1+ow+sw+r,o=new Uint8Array(n),s=0,a=new Uint8Array(8),c=new Uint8Array(8),l=new Uint8Array(8),d=0;a[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)a[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<ow;)if(d<8&&(a[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){cw(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}let u=0;for(;u<i;)if(d<8&&(a[d]=e[u],d+=1,u+=1),8===d){cw(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}for(let h=0;h<sw;)if(d<8&&(a[d]=0,d+=1,h+=1),8===d){cw(a,t,c,l,o,s),s+=8,d=0;for(let e=0;e<8;e++)l[e]=o[s-8+e]}return o}(m,_)),i.writeBytes(m);let f=new Uint8Array(i.data),g=f.length;return f[0]=g>>>24&255,f[1]=g>>>16&255,f[2]=g>>>8&255,f[3]=255&g,f}function cw(e,t,i,r,n,o){for(let s=0;s<8;s++)e[s]^=r[s];!function(e,t,i,r){let n=$D(e,0),o=$D(e,4),s=[];for(let c=0;c<4;c++)s[c]=$D(t,4*c);let a=0;for(let c=0;c<nw;c++)a+=rw,a>>>=0,n+=(o<<4)+s[0]^o+a^(o>>>5)+s[1],n>>>=0,o+=(n<<4)+s[2]^n+a^(n>>>5)+s[3],o>>>=0;ZD(i,n,r),ZD(i,o,r+4)}(e,t,n,o);for(let s=0;s<8;s++)n[o+s]^=i[s];for(let s=0;s<8;s++)i[s]=e[s]}var lw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},dw=e=>Number(e)<14e8,uw=function(e,t){let i;i=Ek||(dw(e)?bk:Ck);let r=Math.floor(Math.random()*wb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},hw="unknown";function pw(){if("unknown"!==hw)return hw;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===n&&(n="2g"),r&&(hw=mw(r,n)),hw}function mw(e,t){if(Pk[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function _w(e){hw=mw(e)}function fw(){return Pk[pw()]}function gw(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function Ew(e){return Tw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Tw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function vw(e){return 4*yw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function yw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var Sw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},Iw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},Aw=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 Rw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:Rw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function Cw(e){return e>8?3e4:1e3*Rw(e)}function bw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var kw=e=>"function"==typeof e,Dw=e=>void 0===e,ww=e=>"string"==typeof e,Nw=e=>"number"==typeof e,Ow=e=>"boolean"==typeof e,Mw=e=>"object"===bw(e),Pw=e=>"array"===bw(e),Lw=e=>bw(e)==="MediaStreamTrack".toLowerCase(),xw=e=>e.isRemote,Vw=e=>"promise"===bw(e),Uw=e=>kw(e)&&e.prototype.constructor===e,Fw=e=>Uw(e)?e.prototype.constructor.name:"",Bw="undefined"!=typeof AudioWorkletNode,Hw="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function Ww(e){return new Promise(((t,i)=>{let r=[];e.forEach((n=>{n.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function Gw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var jw=e=>+e<10?"0".concat(e):e,Jw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=jw(i[1])+jw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},qw=Object.prototype.hasOwnProperty;function Kw(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(Aw(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(qw.call(e,t))return!1;return!0}return!1}function zw(e,t){return{userId:t,hasAudio:!!(e&zk),hasVideo:!!(e&Jk),hasAuxiliary:!!(e&Kk),hasSmall:!!(e&qk),audioMuted:!!(e&Yk),videoMuted:!!(e&Xk),audioAvailable:!(!(e&zk)||e&Yk),videoAvailable:!(!(e&Jk)||e&Xk)}}function Yw(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!Dw(e.username)&&!Dw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",Dw(e.credentialType)||(t.credentialType=e.credentialType)),t}function Xw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!ww(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 Qw=function(e,t,i,r){if(!Mw(e)||!Mw(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(Dw(t[n])||i&&i.includes(n)))if(Mw(e[n])&&Mw(t[n]))o+=Qw(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=Zw(t[n]),o+=1)}return o};function Zw(e){if(Pw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=Zw(e)})),t}if(Mw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=Zw(e[i])})),t}return e}var $w=e=>{let t=[];if(Pw(e))t=[...e];else if(ww(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},eN=e=>ww(e)?document.getElementById(e):e,tN=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function iN(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Pw(e))return"[".concat(e.map((e=>iN(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!Aw(e)||!Pw(i)&&!Pw(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=Aw(e[s])||Pw(e[s])?JSON.parse(iN(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(_D){return"{}"}}function rN(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((r=>{t===e[r]&&i.push(r)})),iN(e,{keysToInclude:i})}function nN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var oN=()=>{var e,t,i,r;return null!=(e=window.screen)&&e.orientation?!(null==(r=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)||!r.includes("portrait")):0===window.orientation||180===window.orientation},sN=e=>Bb(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(ww(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new ek({code:Zb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),aN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},cN=e=>(Object.keys(e).forEach((t=>{Nw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Aw(e[t])||Pw(e[t]))&&cN(e[t])})),e);function lN(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function dN(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}}function uN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function hN(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:o,sampleSize:s,channelCount:a}=null==(t=e.getSettings)?void 0:t.call(e),c=e.kind===Hk.AUDIO?"".concat(o,"x").concat(s,"@").concat(a):"".concat(i,"x").concat(r,"@").concat(n),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(l)}catch(pk){return""}}function pN(e,t){return e.width*e.height==t.width*t.height?1:oN()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function mN(e){return 90===e||270===e}function _N(e){return Bb(this,null,(function*(){return new Promise(((t,i)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=e,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then((()=>t(r))),r.onerror=()=>{i(r.error)}}))}))}function fN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if("object"!=typeof e||null===e)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach(((e,r)=>{i[r]=fN(e,t)})),i}if("[object Object]"===Object.prototype.toString.call(e)){let i={};return t.set(e,i),Reflect.ownKeys(e).forEach((r=>{i[r]=fN(e[r],t)})),i}return e}var gN=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(gN||{});function EN(e,t,i,r){try{let n=function(e,t,i,r){let n={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return Dw(r)||(n=Mb(Ob({},n),{gzip:+r})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:t,bytes_report_data:JSON.stringify(n)}}}(e,t,i,r);return aw(XD(n),i)}catch(zM){return JSON.stringify(e)}}function TN(e,t){let i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}function vN(e){return(65535&e)>>>0}function yN(e){return(4294901760&e)>>>0}function SN(e){let t=function(e){try{let t={},i=0;t.totalLength=$D(e,i),i+=4,t.version=$D(e,i),i+=4,t.encryption=ew(e,i),i+=1,t.uinType=ew(e,i),i+=1,t.uinLength=$D(e,i),i+=4,t.uin=t.uinLength>4?tw(e,i,t.uinLength-4):"",i+=t.uinLength-4;let r=e.slice(i);if(2===t.encryption){e=function(e,t){let i=0,r=new Uint8Array(8).fill(0),n=new Uint8Array(e.slice(0,8)),o=IN(n,t),s=7&o[0],a=e.length-1-s-ow-sw,c=new Uint8Array(a),l=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=s;for(let m=1;m<=ow;)if(h<8)h++,m++;else if(8===h){let r=AN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}let p=a;for(;p>0;)if(h<8)c[l++]=o[h]^d[h],h++,p--;else if(8===h){let r=AN(e,i,d,u,o,t);d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=sw;)if(h<8)o[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=AN(e,i,d,u,o,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,h=0}return c}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=$D(e,i),i+=4,t.seqNo=$D(e,i),i+=4,t.retCode=$D(e,i),i+=4,t.retStrLength=$D(e,i),i+=4,t.retStr=t.retStrLength?tw(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=$D(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?tw(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=$D(e,i),i+=4,t.cookie=t.cookieLength?tw(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=$D(e,i),i+=4,t.busiBuffLength=$D(e,i),i+=4,t.busiBuff=t.busiBuffLength?tw(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function IN(e,t){let i=e[0]<<24|e[1]<<16|e[2]<<8|e[3],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7];i>>>=0,r>>>=0;let n=rw*nw>>>0;for(let o=0;o<nw;o++)r-=(i<<4)+t[2]^i+n^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+n^(r>>>5)+t[1],i>>>=0,n-=rw,n>>>=0;return new Uint8Array([i>>>24&255,i>>>16&255,i>>>8&255,255&i,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function AN(e,t,i,r,n,o){if(t+8>e.length)return{success:!1};let s=new Uint8Array(r),a=e.slice(t,t+8),c=new Uint8Array(8);for(let l=0;l<8;l++)c[l]=n[l]^a[l];return{success:!0,ivPreCrypt:s,ivCurCrypt:a,debiBuf:IN(c,o),bufPos:t+8}}var RN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function CN(e){let{url:t,body:i,method:r="POST",timeout:n,priority:o}=e;return new Promise(((e,s)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:o}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:SN(new Uint8Array(e))||(RN?RN.decode(e):e)}))))))).then(e,s);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(4===a.readyState)if(a.status>=200&&a.status<300)try{let t=JSON.parse(a.response);e({data:t})}catch(XM){e({data:a.response})}else s({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=n||5e3,a.open(r,t,!0),a.send(i)}))}function bN(e){return Bb(this,null,(function*(){let t=Gw(),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")),r=yield(yield(yield new Response(e)).blob()).arrayBuffer();return UM.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Gw()-t,"ms")),r}catch(_D){return i}}))}var kN=Object.prototype.hasOwnProperty,DN=e=>"function"==typeof e,wN=e=>void 0===e,NN=e=>"boolean"==typeof e,ON=e=>e.isRemote,MN=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)};var PN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,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)=>Bb(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($P){let s=()=>{clearTimeout(p),h=0,m=2,i($P)},a=()=>{2!==m&&h<(DN(d)?d():d)?(h++,m=1,DN(n)&&n.call(this,h,s),p=window.setTimeout((()=>{p=-1,_(e,i)}),DN(u)?u(h):u)):(s(),DN(o)&&o.call(this,$P))};DN(r)?r.call(this,{error:$P,retry:a,reject:i,retryFuncArgs:c,retriedCount:h}):a()}}));return new Promise(_)}},LN=class{constructor(e){Ub(this,"userId"),Ub(this,"remoteUserId"),Ub(this,"id"),Ub(this,"sdkAppId"),Ub(this,"type"),Ub(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!NN(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):"","]")),UM.log(e,t,wN(this.userId)||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(MN(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(kN.call(e,t))return!1;return!0}return!1}(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)}},xN={};Lb(xN,{ANDROID_VERSION:()=>YN,CHROME_MAJOR_VERSION:()=>eM,CHROME_VERSION:()=>tM,EDGE_VERSION:()=>iO,EDG_MAJOR_VERSION:()=>oO,EDG_VERSION:()=>nO,ELECTRON_MAJOR_VERSION:()=>iM,FIREFOX_MAJOR_VERSION:()=>eO,FIREFOX_VERSION:()=>$N,HUAWEI_VERSION:()=>BO,IE_VERSION:()=>fO,IOS_MAIN_VERSION:()=>dM,IOS_VERSION:()=>aM,IPADQQB_VERSION:()=>bO,IS_ANDROID:()=>zN,IS_ANDROID_WEBVIEW:()=>sM,IS_ANY_SAFARI:()=>nM,IS_CHROME:()=>ZO,IS_CHROME_OS:()=>NO,IS_CHROMIUM_BASE:()=>QO,IS_DESKTOP_IOS_CHROME:()=>mM,IS_EDG:()=>rO,IS_EDGE:()=>tO,IS_ELECTRON:()=>PO,IS_FIREFOX:()=>ZN,IS_HEADLESS_CHROME:()=>$O,IS_HONOR:()=>FO,IS_HUAWEI:()=>UO,IS_HUAWEIBROWSER:()=>VO,IS_IE:()=>_O,IS_IE8:()=>mO,IS_IOS:()=>KN,IS_IOS_13_OR_14:()=>pM,IS_IOS_15_1:()=>hM,IS_IOS_CHROME:()=>XO,IS_IPAD:()=>GN,IS_IPADQQB:()=>CO,IS_IPAD_PRO:()=>jN,IS_IPHONE:()=>JN,IS_IPOD:()=>qN,IS_LINUX:()=>wO,IS_LOCAL:()=>_M,IS_MAC:()=>DO,IS_MACQQB:()=>AO,IS_MIBROWSER:()=>LO,IS_MQQB:()=>vO,IS_NATIVE_ANDROID:()=>QN,IS_OLD_ANDROID:()=>XN,IS_OPENHARMONY:()=>KO,IS_OPPOBROWSER:()=>GO,IS_SAFARI:()=>rM,IS_SAFARI_15_1:()=>uM,IS_SAMSUNGBROWSER:()=>HO,IS_SOGOU:()=>cO,IS_SOGOUM:()=>sO,IS_TBS:()=>dO,IS_UCBROWSER:()=>MO,IS_VIVOBROWSER:()=>JO,IS_WECHAT:()=>gO,IS_WIN:()=>kO,IS_WQQB:()=>SO,IS_WX:()=>OO,IS_X5MQQB:()=>TO,IS_XWEB:()=>hO,MACQQB_VERSION:()=>RO,MI_VERSION:()=>xO,MQQB_VERSION:()=>yO,OPENHARMONY_VERSION:()=>zO,OPPO_VERSION:()=>jO,SAFARI_VERSION:()=>oM,SAMSUNG_VERSION:()=>WO,SOGOUM_VERSION:()=>aO,SOGOU_VERSION:()=>lO,TBS_VERSION:()=>uO,UA_DATA_STRING:()=>yM,USER_AGENT:()=>VN,VIVO_VERSION:()=>qO,WECHAT_VERSION:()=>EO,WQQB_VERSION:()=>IO,XWEB_VERSION:()=>pO,browserInfo:()=>gM,getBrowserCoreNumber:()=>DM,getBrowserInfo:()=>EM,getChromeMajorVersion:()=>YO,getDeviceModel:()=>AM,getDeviceModelFromUA:()=>RM,getGPUInfo:()=>IM,getOSName:()=>bM,getOSNumber:()=>kM,getOSString:()=>wM,getOSType:()=>OM,getTerminalType:()=>NM,getUserAgentData:()=>SM,isLocalStorageEnabled:()=>fM,isMobile:()=>vM,isVersionLargerThan:()=>lM,isVersionSmallerThan:()=>cM});var VN="undefined"==typeof navigator?"":navigator.userAgent,UN=e=>new RegExp(e,"i").test(VN),FN=e=>{if(UN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=VN.match(t);if(i&&i[1])return i[1]}return""},BN=e=>{if(UN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=VN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},HN=/AppleWebKit\/([\d.]+)/i.exec(VN),WN=HN?parseFloat(HN[1]):NaN,GN=UN("iPad"),jN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&UN("Macintosh"),JN=UN("iPhone")&&!GN,qN=UN("iPod"),KN=JN||GN||qN||jN,zN=UN("Android"),YN=function(){if(zN){let e=VN.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}(),XN=zN&&UN("webkit")&&YN<2.3,QN=zN&&YN<5&&WN<537,ZN=UN("Firefox"),$N=FN("Firefox"),eO=BN("Firefox"),tO=UN("Edge"),iO=FN("Edge"),rO=UN("Edg"),nO=FN("Edg"),oO=BN("Edg"),sO=UN("SogouMobileBrowser"),aO=FN("SogouMobileBrowser"),cO=UN("MetaSr\\s"),lO=FN("MetaSr\\s"),dO=UN("TBS"),uO=FN("TBS"),hO=UN("XWEB"),pO=FN("XWEB"),mO=UN("MSIE\\s8\\.0"),_O=UN("MSIE\\/\\d+"),fO=function(){if(_O){let e=/MSIE\s(\d+)\.\d/.exec(VN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(VN)&&/rv:11.0/.test(VN)&&(t=11),t}return NaN}(),gO=UN("(micromessenger|webbrowser)"),EO=FN("MicroMessenger"),TO=!dO&&UN("MQQBrowser")&&UN("COVC"),vO=!dO&&UN("MQQBrowser")&&!UN("COVC"),yO=vO||TO?FN("MQQBrowser"):"",SO=!dO&&UN(" QQBrowser"),IO=FN(" QQBrowser"),AO=!dO&&UN("QQBrowserLite"),RO=FN("QQBrowserLite"),CO=!dO&&UN("MQBHD"),bO=FN("MQBHD"),kO=UN("Windows"),DO=!KN&&UN("MAC OS X"),wO=!zN&&UN("Linux"),NO=UN("CrOS"),OO=UN("MicroMessenger"),MO=UN("UCBrowser"),PO=UN("Electron"),LO=UN("MiuiBrowser"),xO=FN("MiuiBrowser"),VO=UN("HuaweiBrowser"),UO=UN("Huawei")||UN("HUAWEI"),FO=UN("Honor")||UN("HONOR"),BO=FN("HuaweiBrowser"),HO=UN("SamsungBrowser"),WO=FN("SamsungBrowser"),GO=UN("HeyTapBrowser"),jO=FN("HeyTapBrowser"),JO=UN("VivoBrowser"),qO=FN("VivoBrowser"),KO=UN("OpenHarmony"),zO=FN("OpenHarmony"),YO=()=>BN("Chrome"),XO=UN("CriOS"),QO=UN("Chrome"),ZO=!tO&&!cO&&!sO&&!dO&&!hO&&!rO&&!SO&&!LO&&!VO&&!HO&&!GO&&!JO&&QO,$O=UN("HeadlessChrome"),eM=YO(),tM=FN("Chrome"),iM=BN("Electron"),rM=!QO&&!vO&&!TO&&!AO&&!CO&&UN("Safari"),nM=rM||KN,oM=FN("Version"),sM=/Android.*(wv|.0.0.0)/.test(VN),aM=(()=>{if(jN)return oM;if(KN){let e=VN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function cM(e,t){let i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(i.length,r.length);n++){let e=i[n]||0,t=r[n]||0;if(e<t)return!0;if(e>t)return!1}return!1}function lM(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map((e=>Number(e))),n=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(r.length,n.length);o++){let e=r[o]||0,t=n[o]||0;if(e>t)return!0;if(e<t)return!1}return i}var dM=Number(aM.split(".")[0]),uM="15.1"===oM,hM="15.1"===aM,pM=(()=>{let e=Number(aM.split(".")[0]);return 14===e||13===e})(),mM=XO&&"11.1.1"===oM,_M="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),fM=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(qM){e=!1}return e}})(),gM=EM();function EM(){let e=new Map([[ZN,["Firefox",$N]],[rO,["Edg",nO]],[ZO,["Chrome",tM]],[XO,["ChiOS",FN("CriOS")]],[rM&&!XO,["Safari",oM]],[dO,["TBS",uO]],[hO,["XWEB",pO]],[gO&&JN,["WeChat",EO]],[SO,["QQ(Win)",IO]],[vO,["QQ(Mobile)",yO]],[TO,["QQ(Mobile X5)",yO]],[AO,["QQ(Mac)",RO]],[CO,["QQ(iPad)",bO]],[LO,["MI",xO]],[VO,["HW",BO]],[HO,["Samsung",WO]],[GO,["OPPO",jO]],[JO,["VIVO",qO]],[tO,["EDGE",iO]],[sO,["SogouMobile",aO]],[cO,["Sogou",lO]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var TM=null;function vM(){return TM&&"boolean"==typeof TM.mobile?TM.mobile:zN||KN||JN||GN||KO}var yM="";function SM(){return Bb(this,null,(function*(){if(TM)return TM;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(TM=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!yM&&(yM="UAData: ".concat(TM.platform,"/").concat(TM.platformVersion),TM.architecture&&TM.bitness&&(yM+=" ".concat(TM.architecture,"/").concat(TM.bitness)),TM.mobile&&(yM+=" mobile"),TM.model&&(yM+=" model: ".concat(TM.model.replace(/\s+/g,"/"))),TM.fullVersionList&&(yM+=" ".concat(TM.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),TM}catch(e){return null}}))}function IM(){try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let e=t.getParameter(i.UNMASKED_VENDOR_WEBGL),r=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return"".concat(e," ").concat(r)}return""}catch(e){return""}}function AM(){return(null==TM?void 0:TM.model)||RM()||""}function RM(){let e=VN.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var CM=new Map([[zN,"Android"],[KN,"iOS"],[kO,"Windows"],[DO,"MacOS"],[wO,"Linux"],[NO,"ChromeOS"]]),bM=function(){return CM.get(!0)?CM.get(!0):TM?TM.platform:"unknown"};function kM(){return kO?1:zN?2:DO?3:KN?4:wO?5:NO?6:KO?7:0}function DM(){return QO?1:rM?2:ZN?3:0}var wM=()=>{let e=bM();return null!=TM&&TM.platformVersion?e+="/".concat(TM.platformVersion):KN?e+="/".concat(aM):zN&&(e+="/".concat(YN)),e+="/".concat(gM.name,"/").concat(rM&&!XO?gM.version:gM.version.split(".")[0]),null!=TM&&TM.architecture&&(e+="/".concat(TM.architecture)),e};function NM(){return zN?4:JN?2:GN?3:DO?12:kO?5:wO?13:KO?22:1}function OM(){return zN?"Android":JN?"iPhone":GN?"iPad":DO?"Mac":kO?"Windows":wO?"Linux":"unknown"}var MM=new(xb(Hb(),1).default),PM=(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.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.AUDIO_CONTEXT_LONG_SUSPENDED="155",e.REMOTE_VIDEO_PLAY_START="156",e.REMOTE_VIDEO_PLAY_FINISH="157",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.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SSO_SWITCH="266",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(PM||{}),LM=PM,xM=new class{constructor(){Ub(this,"enable",!1),Ub(this,"ssoFailCount",0),MM.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&MM.emit("266",{enable:!0})})),MM.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&MM.emit("266",{enable:!1})}},VM=class e{constructor(){Ub(this,"_isEnableUploadLog",!0),Ub(this,"_localJoinedUser",new Map),Ub(this,"_queue",[]),Ub(this,"_timeoutId",-1),Ub(this,"_logLevel",1),Ub(this,"_logLevelToUpload",2),!_k&&!fk&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){MM.on(LM.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&Nk[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),MM.on(LM.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),MM.once(LM.JOIN_FAILED,(()=>{this.startUpload()})),MM.on(LM.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()),5e3)}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:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(ww(i.userId)&&Nw(i.sdkAppId)){let{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return Bb(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:r,logs:n}=t[e],o={timestamp:sk(),sdkAppId:String(r),userId:i,version:uk,log:n.map((e=>e.log)).join("\n")},s=JSON.stringify(o),a=xM.enable?EN(o,2002,r):s;yield this.uploadLogWithRetry(a,r,a instanceof Uint8Array,s),n.forEach((e=>e.uploaded=!0))}}catch(zM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return PN({retryFunction:()=>CN({url:uw(t,Dk.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&(xM.handleUploadFailed(),this.uploadLogWithRetry(r,t,!1,r))})),settings:{retries:3,timeout:2e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;return t.setTime(ok()),"[".concat(ak(t),"] <").concat(Nk[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Dw(Nk[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(ww(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(pk){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,o={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i};MM.emit(LM.LOG,{log:o}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(o)}log(t,i){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;var s;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,n,o),t<this._logLevel)return;let a=(null==(s=Nk[t])?void 0:s.toLowerCase())||"info";e.PRINT_LOG_TAG?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[a](...i)}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 LN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Nk[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};Ub(VM,"PRINT_LOG_TAG",!(KN||zN||$O));var UM=new VM,FM=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)}))},BM=new class{constructor(){Ub(this,"_prefix","TRTC"),Ub(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){fM()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix))try{let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}catch(zM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(fM())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(qM){UM.warn(qM)}}getItem(e){if(!fM())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(pk){UM.warn(pk)}}setItem(e,t){if(fM())try{let i={expiresIn:Date.now()+Lk,value:t};this._queue.set(this.getRealKey(e),i)}catch(_D){UM.warn(_D)}}deleteItem(e){if(!fM())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(pk){return UM.warn(pk),!1}}clear(){if(fM())try{localStorage.clear()}catch(qM){UM.warn(qM)}}},HM={};Lb(HM,{HTTPS_API:()=>kL,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>XL,IS_GET_CAPABILITIES_SUPPORTED:()=>YL,IS_GET_SETTINGS_SUPPORTED:()=>zL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>KL,IS_INSERTABLE_STREAM_SUPPORTED:()=>QL,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>dx,IS_RTC_RTP_SENDER_SUPPORTED:()=>jL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ZL,IS_SEI_SUPPORTED:()=>$L,IS_SPC_SUPPORTED:()=>WL,basis:()=>ox,capabilityCheck:()=>cx,checkSystemRequirementsInternal:()=>SL,decodeSupportStatus:()=>yL,detectVideoCodecCapabilities:()=>px,detectVideoDecoderCapabilities:()=>_x,detectVideoEncoderCapabilities:()=>mx,encodeSupportStatus:()=>vL,getBrowserInfo:()=>hL,getDisplayResolution:()=>wL,getH264ProfileLevelIds:()=>fx,isAddTransceiverSupported:()=>HL,isBrowserSupported:()=>pL,isCanvasCaptureStreamAPISupported:()=>ML,isCanvasSmallStreamSupported:()=>PL,isGetReceiversSupported:()=>UL,isGetSendersSupported:()=>FL,isGetTransceiversSupported:()=>BL,isGetUserMediaSupported:()=>NL,isMediaDevicesSupported:()=>_L,isMediaSessionSupported:()=>ix,isMediaStreamTrackGeneratorSupported:()=>TL,isMediaStreamTrackProcessorSupported:()=>EL,isReplaceTrackSupported:()=>JL,isRequestVideoFrameCallbackSupported:()=>lx,isSIMDSupported:()=>nx,isScaleResolutionDownBySupported:()=>LL,isScreenCaptureApiAvailable:()=>AL,isSelectedCandidatePair:()=>DL,isSetParametersSupported:()=>qL,isSetSinkIdSupported:()=>RL,isSmallStreamSupported:()=>xL,isStopTransceiverSupported:()=>GL,isTRTCSupported:()=>IL,isUnifiedPlanDefault:()=>VL,isUsedInHttpProtocol:()=>gL,isWebAudioSupported:()=>OL,isWebCodecSupported:()=>tx,isWebCodecsSupported:()=>mL,isWebRTCSupported:()=>ex,isWebTransportSupported:()=>rx});var WM={};Lb(WM,{AUDIO_LEVEL_SCALE:()=>PP,AudioCodecPipelineType:()=>BP,AudioDecoderDowngradeState:()=>_P,AudioPlayerMode:()=>NP,AudioType:()=>yP,BASIC_TYPE:()=>VP,BannedReason:()=>OP,CONNECTION_CLOSED_REASON:()=>iP,CheckPermissionType:()=>qP,ClientEvent:()=>rP,CodecType:()=>HP,ConnectionEvent:()=>tP,ConnectionState:()=>mP,DECODE_FAILED_ERROR_CODE:()=>WP,DenoiserMode:()=>LP,DeviceType:()=>KP,FacingMode:()=>DP,FrameWorkType:()=>eP,LeaveReason:()=>MP,LocalTrackEvent:()=>oP,MULTI_VIDEO_DATA_TYPE:()=>RP,MediaType:()=>TP,MediaTypeLabel:()=>vP,MonitorEventId:()=>CP,MutedFlag:()=>dP,NetworkQualityValue:()=>bP,PlayerState:()=>sP,ReceiveMode:()=>kP,RemoteStreamType:()=>AP,RemoteTrackEvent:()=>lP,RoomEvent:()=>aP,SMALL_MODE:()=>JP,SceneNumber:()=>uP,StreamEvent:()=>nP,StreamType:()=>IP,SubscribeMediaType:()=>xP,TIMER_TYPE:()=>jP,TRACK_ACTION:()=>EP,TRACK_KIND:()=>gP,TrackEvent:()=>cP,UserRole:()=>pP,UserRoleNumber:()=>hP,VideoCodec:()=>UP,VideoCodecPipelineType:()=>FP,VideoContentHint:()=>GP,VideoDecoderDowngradeState:()=>fP,VideoPlayerMode:()=>wP,VideoType:()=>SP});var GM,jM,JM,qM,KM,zM,YM,XM,QM,ZM,$M,eP=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(eP||{}),tP=(($M=tP||{}).TRACK_ADDED="track-added",$M.TRACK_UPDATED="track-updated",$M.TRACK_SUBSCRIBED="track-subscribed",$M.STREAM_ADDED="stream-added",$M.STREAM_REMOVED="stream-removed",$M.STREAM_UPDATED="stream-updated",$M.STREAM_PUBLISHED="stream-published",$M.STREAM_SUBSCRIBED="stream-subscribed",$M.STREAM_UNSUBSCRIBED="stream-unsubscribed",$M.STATE_CHANGED="state-changed",$M.ERROR="error",$M.CONNECTION_STATE_CHANGED="connection-state-changed",$M.FIREWALL_RESTRICTION="firewall-restriction",$M.SEI_MESSAGE="sei-message",$M.CLOSED="closed",$M),iP=(e=>(e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e))(iP||{}),rP=((ZM=rP||{}).STREAM_ADDED="stream-added",ZM.STREAM_REMOVED="stream-removed",ZM.STREAM_UPDATED="stream-updated",ZM.STREAM_SUBSCRIBED="stream-subscribed",ZM.CONNECTION_STATE_CHANGED="connection-state-changed",ZM.PEER_JOIN="peer-join",ZM.PEER_LEAVE="peer-leave",ZM.MUTE_AUDIO="mute-audio",ZM.MUTE_VIDEO="mute-video",ZM.UNMUTE_AUDIO="unmute-audio",ZM.UNMUTE_VIDEO="unmute-video",ZM.CLIENT_BANNED="client-banned",ZM.NETWORK_QUALITY="network-quality",ZM.AUDIO_VOLUME="audio-volume",ZM.SEI_MESSAGE="sei-message",ZM.ERROR="error",ZM),nP=((QM=nP||{}).PLAYER_STATE_CHANGED="player-state-changed",QM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",QM.CONNECTION_STATE_CHANGED="connection-state-changed",QM.DEVICE_AUTO_RECOVERED="device-auto-recovered",QM.ERROR="error",QM),oP=((XM=oP||{}).DEVICE_AUTO_RECOVERED="1",XM.DEVICE_RECOVER_FAILED="5",XM.DEVICE_CHANGED="2",XM.ERROR="3",XM.PUBLISH_STATE_CHANGED="4",XM.ENCODE_FAILED="6",XM.TRACK_ENDED="7",XM.RENDER="render",XM),sP=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(sP||{}),aP=((YM=aP||{}).PEER_JOIN="peer-join",YM.PEER_LEAVE="peer-leave",YM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",YM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",YM.BANNED="banned",YM.NETWORK_QUALITY="network-quality",YM.AUDIO_VOLUME="audio-volume",YM.SEI_MESSAGE="sei-message",YM.ERROR="error",YM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",YM.REMOTE_PUBLISHED="remote-published",YM.REMOTE_UNPUBLISHED="remote-unpublished",YM.FIREWALL_RESTRICTION="firewall-restriction",YM.HEARTBEAT_REPORT="heartbeat-report",YM.CUSTOM_MESSAGE="custom-message",YM.LAYER_DATA="layerData",YM.FIRST_VIDEO_FRAME="first-video-frame",YM.DUMP="dump",YM.AUDIO_FRAME="audio-frame",YM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",YM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",YM.NTP_TIME_UPDATED="ntp-time-updated",YM),cP=(e=>(e.PLAYER_STATE_CHANGED="player-state-changed",e.MUTE="mute",e.UNMUTE="unmute",e.ERROR="error",e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",e.FIRST_VIDEO_FRAME="first-video-frame",e.VIDEO_SIZE_CHANGED="video-size-changed",e))(cP||{}),lP=((zM=lP||{}).DECODE_FAILED="decode-failed",zM.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",zM.REMOTE_PUBLISH_CHANGED="remote-publish-changed",zM.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",zM),dP=((KM=dP||{})[KM.VIDEO=1]="VIDEO",KM[KM.SMALL=2]="SMALL",KM[KM.AUX=4]="AUX",KM[KM.AUDIO=8]="AUDIO",KM[KM.VIDEO_MUTE=16]="VIDEO_MUTE",KM[KM.AUX_MUTE=32]="AUX_MUTE",KM[KM.AUDIO_MUTE=64]="AUDIO_MUTE",KM),uP=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(uP||{}),hP=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(hP||{}),pP=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(pP||{}),mP=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(mP||{}),_P=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(_P||{}),fP=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(fP||{}),gP=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(gP||{}),EP=(e=>(e.ADD="add",e.REMOVE="remove",e))(EP||{}),TP=(e=>(e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e))(TP||{}),vP={1:"audio",2:"auxVideo",4:"video"},yP=((qM=yP||{})[qM.opus=111]="opus",qM),SP=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(SP||{}),IP=(e=>(e.Big="big",e.Small="small",e))(IP||{}),AP=(e=>(e.Main="main",e.Aux="auxiliary",e))(AP||{}),RP=(e=>(e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e))(RP||{}),CP=((JM=CP||{})[JM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",JM[JM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",JM[JM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",JM[JM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",JM[JM.MUTE_AUDIO=32772]="MUTE_AUDIO",JM[JM.MUTE_VIDEO=32773]="MUTE_VIDEO",JM[JM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",JM[JM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",JM[JM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",JM[JM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",JM[JM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",JM[JM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",JM[JM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",JM[JM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",JM[JM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",JM[JM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",JM[JM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",JM[JM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",JM[JM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",JM[JM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",JM[JM.JOIN=32788]="JOIN",JM[JM.LEAVE=32789]="LEAVE",JM[JM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",JM[JM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",JM[JM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",JM[JM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",JM[JM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",JM[JM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",JM[JM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",JM[JM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",JM[JM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",JM[JM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",JM[JM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",JM[JM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",JM[JM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",JM[JM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",JM[JM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",JM[JM.PUBLISH_AUX=32805]="PUBLISH_AUX",JM[JM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",JM[JM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",JM[JM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",JM[JM.VIDEO_DECODER=4005]="VIDEO_DECODER",JM),bP=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e))(bP||{}),kP=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e))(kP||{}),DP=(e=>(e.user="user",e.environment="environment",e))(DP||{}),wP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e))(wP||{}),NP=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(NP||{}),OP=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(OP||{}),MP=((jM=MP||{})[jM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",jM[jM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",jM[jM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",jM[jM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",jM[jM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",jM[jM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",jM[jM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",jM[jM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",jM[jM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",jM),PP=1e8,LP=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(LP||{}),xP=class{constructor(){Ub(this,"mediaType",0)}set audio(e){e?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(e){e?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(e){e?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(e){e?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},VP=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(VP||{}),UP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(UP||{}),FP=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(FP||{}),BP=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(BP||{}),HP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(HP||{}),WP=((GM=WP||{})[GM.SUCCESS=0]="SUCCESS",GM[GM.FAILED=1]="FAILED",GM[GM.WEBCODEC_INIT=2]="WEBCODEC_INIT",GM[GM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",GM[GM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",GM[GM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",GM[GM.WASM_INIT=6]="WASM_INIT",GM[GM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",GM[GM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",GM[GM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",GM[GM.TEST=10]="TEST",GM[GM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",GM),GP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(GP||{}),jP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(jP||{}),JP=(e=>(e.CANVAS="canvas",e.API="api",e))(JP||{}),qP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(qP||{}),KP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(KP||{}),zP={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_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"},YP={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=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(r,"(), received type: ").concat(bw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(bw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,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,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},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/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:r}=e;return"failed to subscribe ".concat(i," ").concat(r," 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 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:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},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:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},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 in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"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_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:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," 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,"()")},XP=(e,t)=>t?"".concat(Ak,"/").concat(e,"/").concat(t):"".concat(Ak,"/").concat(e,"/index.html"),QP=()=>{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=null==localStorage?void 0:localStorage.getItem(kk);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,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function ZP(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";kw(YP[t])?o=YP[t](i):ww(YP[t])&&(o=YP[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=QP();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(kw(l[t])?a=l[t](i):ww(l[t])&&(a=l[t]));let d=o;return Iw()&&(c&&c[t]&&(kw(c[t])?s=c[t](i):ww(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(XP("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(XP("en",a),"\n")),d}var $P,eL=xb(Jb(),1),tL=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];Ub(this,"countMap",new Map),Ub(this,"distributionMap",new Map),Ub(this,"version"),Ub(this,"log",UM.createLogger({id:"kv"})),e&&(MM.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Hk.AUDIO?501700:511700,cost:i})})),MM.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Hk.AUDIO?501700:511700,error:i})})),MM.on("266",(e=>{let{enable:t}=e;this.log.info("".concat(t?"enable":"disable"," sso")),t?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})})))}getReportData(e,t){let i={msg_sdk_basic_info:{uint32_sdk_version:aN(this.version||uk),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}}))}})),str_user_sig:e,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),i}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:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.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:r=100,useUV:n=!1,max:o=5e3}=e;var s;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;i>o&&(i=o),this.countMap.set(t,(this.countMap.get(t)||0)+1);let a=(null==(s=this.distributionMap)?void 0:s.get(t))||new Map,c=0;if(Nw(r))c=Math.floor(i/r);else for(let l=r.length-1;l>0;l--)if(i>r[l]){c=l;break}a.set(c,(a.get(c)||0)+1),this.distributionMap.set(t,a)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=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:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=Zb.UNKNOWN;i&&(Nw(i)?r=i:(!Dw(i.extraCode)||!Dw(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},iL=(e=>(e[e.enterRoom=500700]="enterRoom",e[e.exitRoom=500701]="exitRoom",e[e.switchRole=500702]="switchRole",e[e.destroy=500703]="destroy",e[e.startLocalAudio=500704]="startLocalAudio",e[e.updateLocalAudio=500705]="updateLocalAudio",e[e.stopLocalAudio=500706]="stopLocalAudio",e[e.startLocalVideo=500707]="startLocalVideo",e[e.updateLocalVideo=500708]="updateLocalVideo",e[e.stopLocalVideo=500709]="stopLocalVideo",e[e.startScreenShare=500710]="startScreenShare",e[e.updateScreenShare=500711]="updateScreenShare",e[e.stopScreenShare=500712]="stopScreenShare",e[e.startRemoteVideo=500713]="startRemoteVideo",e[e.updateRemoteVideo=500714]="updateRemoteVideo",e[e.stopRemoteVideo=500715]="stopRemoteVideo",e[e.muteRemoteAudio=500716]="muteRemoteAudio",e[e.setRemoteAudioVolume=500717]="setRemoteAudioVolume",e[e.use=500718]="use",e[e.switchRoom=500719]="switchRoom",e[e.sendSEIMessage=5e5]="sendSEIMessage",e[e.sendCustomMessage=500001]="sendCustomMessage",e))(iL||{}),rL=(e=>(e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e))(rL||{}),nL=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e))(nL||{}),oL=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e))(oL||{}),sL=(($P=sL||{})[$P.DECODER_TYPE=514700]="DECODER_TYPE",$P[$P.DECODER_HW_SW=514701]="DECODER_HW_SW",$P[$P.DECODE_RESULT=514702]="DECODE_RESULT",$P[$P.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",$P[$P.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",$P[$P.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",$P[$P.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",$P[$P.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",$P[$P.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",$P[$P.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",$P[$P.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",$P[$P.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",$P[$P.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",$P[$P.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",$P[$P.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",$P[$P.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",$P[$P.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",$P),aL=new tL(!0),cL=new tL(!1),lL=aL,dL={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},uL=new Map([[ZN,["Firefox",$N]],[rO,["Edg",nO]],[ZO,["Chrome",tM]],[rM,["Safari",oM]],[dO,["TBS",uO]],[hO,["XWEB",pO]],[gO&&JN,["WeChat",EO]],[SO,["QQ(Win)",IO]],[vO,["QQ(Mobile)",yO]],[TO,["QQ(Mobile X5)",yO]],[AO,["QQ(Mac)",RO]],[CO,["QQ(iPad)",bO]],[LO,["MI",xO]],[VO,["HW",BO]],[HO,["Samsung",WO]],[GO,["OPPO",jO]],[JO,["VIVO",qO]],[tO,["EDGE",iO]],[sO,["SogouMobile",aO]],[cO,["Sogou",lO]]]);function hL(){let e=uL.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var pL=function(){return!(MO||tO||rO&&oO<80||ZN&&eO<56)},mL=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},_L=function(){if(!navigator.mediaDevices)return gL()||UM.error(YP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},fL=!1;function gL(){return"http:"===location.protocol&&!_M&&(fL||UM.error(ZP({key:zP.NOT_SUPPORTED_HTTP})),fL=!0,!0)}var EL=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},TL=function(){return!(null==window||!window.MediaStreamTrackGenerator)},vL=function(){return Bb(this,null,(function*(){var e,t,i;if(dL.detail.isH264EncodeSupported&&dL.detail.isVp8EncodeSupported)return{isH264EncodeSupported:dL.detail.isH264EncodeSupported,isVp8EncodeSupported:dL.detail.isVp8EncodeSupported,isH265EncodeSupported:dL.detail.isH265EncodeSupported};let r,n=!1,o=!1,s=!1;try{let a=new RTCPeerConnection,c=document.createElement(Hk.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),r=yield a.createOffer(),n=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),o=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),s=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),a.close(),{isH264EncodeSupported:n,isVp8EncodeSupported:o,isH265EncodeSupported:s}}catch(KM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},yL=function(){return Bb(this,null,(function*(){var e;if(dL.detail.isH264DecodeSupported&&dL.detail.isVp8DecodeSupported)return{isH264DecodeSupported:dL.detail.isH264DecodeSupported,isVp8DecodeSupported:dL.detail.isVp8DecodeSupported,isH265DecodeSupported:dL.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;HL()?(n.addTransceiver(Hk.VIDEO,{direction:"recvonly"}),t=yield n.createOffer()):t=yield n.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let o=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return n.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:o}}catch(zM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var SL=dN((e=>Bb(void 0,null,(function*(){let t=Date.now(),i=ex(),r=_L(),n=mL();if(dL.detail.isWebRTCSupported=i,dL.detail.isMediaDevicesSupported=r,dL.detail.isWebCodecsSupported=n,dL.detail.isScreenShareSupported=AL(),dL.detail.isSmallStreamSupported=xL(),37===e)return Object.assign(dL.detail,yield function(){return Bb(this,null,(function*(){return bL||(bL=new Promise((e=>Bb(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!mL())return void e(t);let i=null,r=null,n=null,o=()=>{n&&clearTimeout(n),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let s=0,a=()=>{!r||!i||(r.fillStyle="hsl(".concat(s%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(s),10,30),s++)};n=setTimeout((()=>{o(),e(t)}),5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map((e=>Bb(this,null,(function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,n)=>Bb(this,null,(function*(){try{let o=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:n});o.configure(e.encodeConfig),a();let s=new VideoFrame(i,{timestamp:0});o.encode(s,{keyFrame:!0}),s.close(),yield o.flush(),o.close()}catch($M){n($M)}}))))}catch(p){return UM.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise(((i,n)=>Bb(this,null,(function*(){try{let o=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:n});o.configure(e.decodeConfig),o.decode(t),yield o.flush(),o.close()}catch($M){n($M)}}))))}catch(p){UM.warn("".concat(e.type," decoder error:"),p)}return r})))))).forEach((e=>{"h264"===e.type?(t.isH264EncodeSupported=e.encodeSupported,t.isH264DecodeSupported=e.decodeSupported):"vp8"===e.type&&(t.isVp8EncodeSupported=e.encodeSupported,t.isVp8DecodeSupported=e.decodeSupported)})),o(),e(t)}catch(s){o(),UM.warn("detectWebCodecsSupported failed:",s),e(t)}})))),bL)}))}()),dL.detail.isBrowserSupported=n,dL.result=r&&n,dL.result||UM.error("".concat(navigator.userAgent," ").concat(rN(dL.detail,!1))),ax(e),lL.addNumber({key:523800,value:Date.now()-t}),dL;if(dL.result&&dL.detail.isH264EncodeSupported&&dL.detail.isVp8EncodeSupported&&dL.detail.isH265EncodeSupported&&dL.detail.isH264DecodeSupported&&dL.detail.isVp8DecodeSupported&&dL.detail.isH265DecodeSupported)return dL;let o=pL(),{encode:s,decode:a}=yield function(){return Bb(this,null,(function*(){let[e,t]=yield Promise.all([vL(),yL()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:c,vp8:l}=s,{h264:d}=a,{h265:u}=s,{vp8:h,h265:p}=a;if(!c||!l){let e=yield vL();UM.warn("detect encode again h264:".concat(c," vp8:").concat(l," result: ").concat(JSON.stringify(e))),c=e.isH264EncodeSupported,l=e.isVp8EncodeSupported}if(c&&d&&zN&&QO&&!hO&&!dO&&(!GO||115!==eM)){let{encode:e,decode:t}=yield function(){return Bb(this,null,(function*(){return CL||(CL=new Promise((e=>Bb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),n=r.getContext("2d");r.width=640,r.height=480;let o=setInterval((()=>{n.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),66),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)}),2e3);let c=r.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=eL.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=eL.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>Bb(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,n]=yield Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Hk.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Hk.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),UM.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&UM.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(yM)),e))),CL)}))}();c=e,d=t}return dL.result=o&&i&&r&&(c||l)&&(d||h),dL.detail.isBrowserSupported=o,dL.detail.isWebRTCSupported=i,dL.detail.isH264EncodeSupported=c,dL.detail.isVp8EncodeSupported=l,dL.detail.isH265EncodeSupported=u,dL.detail.isH264DecodeSupported=d,dL.detail.isVp8DecodeSupported=h,dL.detail.isH265DecodeSupported=p,dL.result||UM.error("".concat(navigator.userAgent," ").concat(rN(dL.detail,!1))),ax(),lL.addNumber({key:523800,value:Date.now()-t}),dL})))),IL=function(){return dL.result},AL=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},RL="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,CL=null;var bL=null;var kL=(e,t,i)=>{"http:"===location.protocol&&!_M&&(e[t]=()=>{throw new ek({code:Zb.INVALID_OPERATION,message:YP.NOT_SUPPORTED_HTTP})})},DL=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(Ow(e.selected)&&!e.selected)};function wL(){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 NL(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function OL(){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 ML(){return"captureStream"in HTMLCanvasElement.prototype}function PL(){return!(gO||KN||eM&&eM<63)&&!(!pL()||!ML())}function LL(){return!(eM<74||tO||dM<11||eO<46)}function xL(){return PL()||LL()}var VL=function(){if(Dw(window.RTCRtpTransceiver)||!HL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:yD}),e.addTransceiver(Hk.AUDIO),t=!0}catch(pk){}return null==e||e.close(),t};function UL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function FL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function BL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function HL(){return!(11===dM&&!mM)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var WL=!(!HL()||QO&&eM<86);function GL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var jL="RTCRtpSender"in window;function JL(){return jL&&"replaceTrack"in window.RTCRtpSender.prototype}function qL(){return jL&&"setParameters"in window.RTCRtpSender.prototype&&FL()}var KL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,zL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,YL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,XL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,QL=jL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&YO()>=86,ZL="RTCRtpScriptTransform"in window,$L=jL&&(QL||ZL),ex=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function tx(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Dw(window.AudioDecoder)||(e.AudioDecoder=!0),Dw(window.AudioEncoder)||(e.AudioEncoder=!0),Dw(window.VideoDecoder)||(e.VideoDecoder=!0),Dw(window.VideoEncoder)||(e.VideoEncoder=!0),Dw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function ix(){return"mediaSession"in navigator&&!Dw(navigator.mediaSession.setActionHandler)}function rx(){return!Dw(window.WebTransport)}function nx(){return"undefined"!=typeof WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function ox(){let e={browser:"".concat(gM.name,"/").concat(gM.version),os:bM(),displayResolution:wL(),isScreenShareSupported:AL(),isWebRTCSupported:ex(),isGetUserMediaSupported:NL(),isWebAudioSupported:OL(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:tx(),isMediaSessionSupported:ix(),isWebTransportSupported:rx()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var sx="checkResult";function ax(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;BM.setItem(sx+e,{ua:navigator.userAgent,checkResult:dL})}function cx(e){gL();let t=BM.getItem(sx+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!Mw(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,dL.detail)&&(dL=t.checkResult),SL(e)}function lx(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var dx="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function ux(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var hx=!1;function px(){return Bb(this,null,(function*(){var e;try{if(hx||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=kM(),i=DM();if(0===t||0===i)return;hx=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,o]=yield Promise.all([mx(r),_x(r)]);n&&Object.keys(n).forEach((e=>{let r=ux(e.toLowerCase());lL.addEnum({key:513707,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})})),o&&Object.keys(o).forEach((e=>{let r=ux(e.toLowerCase());lL.addEnum({key:514713,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})}))}catch(qM){UM.info("detectVideoCodecCapabilities failed",qM)}}))}function mx(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Bb(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(mk){}return o}))}function _x(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1920,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1080,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:30,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return Bb(this,null,(function*(){let o={};try{for(let s of e){let e=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(s),width:t,height:i,bitrate:n,framerate:r}});o[s]=e}}catch(mk){}return o}))}function fx(){let e={sender:new Set,receiver:new Set,senderHex:new Set,receiverHex:new Set};try{if(RTCRtpSender&&"function"==typeof RTCRtpSender.getCapabilities){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter((e=>"video/h264"===e.mimeType.toLowerCase())).forEach((t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1]){let t=i[1];e.senderHex.add(t);let r=parseInt(t,16);isNaN(r)||e.sender.add(r)}}}))}if(RTCRtpReceiver&&"function"==typeof RTCRtpReceiver.getCapabilities){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter((e=>"video/h264"===e.mimeType.toLowerCase())).forEach((t=>{if(t.sdpFmtpLine){let i=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(i&&i[1]){let t=i[1];e.receiverHex.add(t);let r=parseInt(t,16);isNaN(r)||e.receiver.add(r)}}}))}}catch(qM){UM.warn("get H264 profile levelId failed",qM)}return e}var gx=xb(Hb(),1),Ex=Symbol("instance"),Tx=Symbol("cacheResult"),vx=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,Rx.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},yx=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(r,n,o)=>{let s=i.action||n;if(!i.context){let i=Sx.get(r)||[];Sx.has(r)||Sx.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=Cx.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[Tx]:Promise.resolve(r[Tx]);r.state instanceof vx&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof vx&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new yx(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new yx(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._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=r.state,h=new vx(u,t,s);Rx.call(r,h);let p=e=>{var n;return r[Tx]=e,h.aborted||(Rx.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[Tx])),e},m=e=>(Rx.call(r,u,e),d(e));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(ZM){return m(new yx(r._state,"".concat(r.name," ").concat(s," from ").concat(e," to ").concat(t," failed: ").concat(ZM),ZM instanceof Error?ZM:new Error(String(ZM))))}}}}var Ax="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 Rx(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(Cx.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Cx=class e extends gx.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=e.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);let n=r[Ex];n?this.name=n.name+"-"+n.count++:r[Ex]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Sx.get(e)||[],i=new Set,r=[],n=[],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?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(t){let i;return"string"==typeof t?(i=e.instances.get(t),i||e.instances.set(t,i=new e(t,void 0,Object.create(e.prototype)))):(i=e.instances2.get(t),i||e.instances2.set(t,i=new e(t.constructor.name,void 0,Object.create(e.prototype)))),i}static getState(t){var i;return null===(i=e.get(t))||void 0===i?void 0:i.state}updateDevTools(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Ax(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){Rx.call(this,e)}};Cx.STATECHANGED="stateChanged",Cx.UPDATEAFSM="updateAFSM",Cx.INIT="[*]",Cx.ON="on",Cx.OFF="off",Cx.instances=new Map,Cx.instances2=new WeakMap;var bx="undefined"!=typeof window,kx=bx&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},Dx=bx&&window.cancelIdleCallback||function(e){clearTimeout(e)},wx=bx&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Nx=class e{static generateTaskID(){return this.currentTaskID++}static run(e,t,i){null!=i&&i.fps&&(i.delay=i.delay||Number((1e3/i.fps).toFixed(2))),i=Ob("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i);let r=Mb(Ob({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i),{delay:i.delay});return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(t){return t.intervalID=setInterval((()=>{t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}static intervalInWorker(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=t=>{var i;if("tick"===t.data.type){let r=e.workerTasks.get(t.data.taskId);r&&(e.isBreakLoop(r)?(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let i=()=>{if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=Gw(),n=()=>{if(i=Gw()-r,i>=t.delay&&(r=Gw()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=kx(n,{timeout:t.delay})};return t.ricID=kx(n,{timeout:t.delay})}static raf(t){let i,r=Gw(),n=()=>document.hidden&&t.backgroundTask?(i=Gw()-r,r=Gw(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=Gw()-r,i>=t.delay&&(r=Gw()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(n));if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let e=()=>{if(document.hidden){let e=Gw()-r;e>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-e)}};document.addEventListener("visibilitychange",e),t.onVisibilitychange=e,document.hidden&&e()}return t.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:r,ricID:n,onVisibilitychange:o}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&wx&&wx(r),n&&Dx(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Ub(Nx,"taskMap",new Map),Ub(Nx,"currentTaskID",1),Ub(Nx,"sharedWorker",null),Ub(Nx,"workerTasks",new Map);var Ox=Nx;Hk.SEI_MESSAGE;var Mx={LOADED_DATA:Hk.LOADEDDATA,LOADED_META_DATA:Hk.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:Hk.RESIZE,TIME_UPDATE:"time-update"},Px={};Lb(Px,{create:()=>xx,remove:()=>Vx});var Lx=new WeakMap;function xx(e,t){Lx.has(e)||Lx.set(e,[]);let i=Lx.get(e),r={add:(e,n)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,n)),t.addEventListener(e,n)):(i.push(t.off.bind(t,e,n)),t.on(e,n)),r)};return r}function Vx(e){let t=Lx.get(e);t&&(t.forEach((e=>e())),Lx.delete(e))}var Ux=new class{constructor(){Ub(this,"_roomIdMap",new Map),Ub(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:uk,env:wk.QCLOUD,browserVersion:gM.name+gM.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){_M||!UM.isAbleToUpload||this._configs.env===wk.QCLOUD&&this.uploadEventToKibana(Mb(Ob({},e),{result:"success"}))}logFailedEvent(e){if(_M||!UM.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||Zb.UNKNOWN};this._configs.env===wk.QCLOUD&&this.uploadEventToKibana(Mb(Ob({},o),{error:r}))}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:r}=e,n={timestamp:sk(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:uk,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack)));let o=xM.enable?EN(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(uw(this._configs.sdkAppId,Dk.LOG),o)}sendRequest(e,t){setTimeout((()=>CN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},Fx=new WeakMap;function Bx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=PN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=Fx.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=Fx.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;DN(r)&&r.call(this,t,i),null!=(n=Fx.get(e))&&n.has(o)&&(Fx.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=Fx.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):Fx.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=Fx.get(e))?void 0:t.delete(o)}))},s}}function Hx(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=Fx.get(e))&&n.has(t)){let{stopRetry:n,args:s}=Fx.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=Fx.get(e))||o.delete(t))}return s.apply(this,c)},o}}var Wx=class extends Cx{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,Ub(this,"id"),Ub(this,"element",null),Ub(this,"track"),Ub(this,"url"),Ub(this,"attr"),Ub(this,"mode"),Ub(this,"muted"),Ub(this,"_log"),Ub(this,"_isPausedByUserCall",!1),Ub(this,"_pausedRetryCount"),Ub(this,"_isElementPlayingFired",!1),Ub(this,"_interval"),Ub(this,"_delayDestroyTimeoutId",0),Ub(this,"_playSuccessResolve"),Ub(this,"_isReplayByRecreateMediaStreamCalled",!1),Ub(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=MD,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isPaused(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}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 Bb(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(pk){let t=ZP({key:zP.PLAY_FAILED,data:{media:this.kind,error:pk}});if(this._log.warn(pk),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ek({code:Zb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!nM?this._delayDestroyTimeoutId||(null==(t=this.element)||t.remove(),this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Hk.ENDED),this._interval>0&&Ox.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),null==(e=this.element)||e.pause(),this._isPausedByUserCall=!0,this instanceof hV&&QO&&eM>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():hM?this.replay():(this.element&&this.track&&QO&&eM>=128&&(this.element.srcObject=new MediaStream([this.track])),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 xx(this.element,this.element).add(Hk.PLAYING,e).add(Hk.ENDED,e).add(Hk.PAUSE,e).add(Hk.ERROR,e).add(Hk.LOADEDDATA,e).add(Hk.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==Px||Px.create(e,e).add(Hk.ENDED,t).add(Hk.MUTE,t).add(Hk.UNMUTE,t),e.readyState===Hk.ENDED&&this.handleTrackEvent({type:Hk.ENDED}),e.muted&&this.handleTrackEvent({type:Hk.MUTE})}}bindAutoPlayEvent(){MM.on(LM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&Vx(e)}unbindEvents(){this.element&&Vx(this.element),this.unbindTrackEvents(),MM.off(LM.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Hk.PLAYING:aV()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Hk.PLAYING),this._interval&&(Ox.clearTask(this._interval),this._interval=-1);break;case Hk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Hk.ENDED);break;case Hk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Hk.PAUSE),KN&&(this._interval=Ox.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.doResume()}),{delay:3e3}));break;case Hk.ERROR:if(this.element&&this.element.error){this.handlePaused(Hk.ERROR);let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),Ux.uploadEvent({log:"stat-".concat(this.kind,"-").concat(gD.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),FO||UO?this.emit(Mx.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Hk.LOADEDDATA:this.kind===Hk.VIDEO&&this.emit(Mx.LOADED_DATA);break;case Hk.LOADEDMETADATA:this.kind===Hk.VIDEO&&this.emit(Mx.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),Ux.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),lL.addSuccessEvent({key:this.kind===Hk.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),Ux.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),lL.addFailedEvent({key:this.kind===Hk.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(Mx.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{lN(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,r;this._log.warn("element onerror ".concat(null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code," fired after recreated mediaStream")),i(null==(r=this.element)?void 0:r.error)}),lN(5e3).then((()=>{var e,r;(!this.isPlaying||null!=(e=this.element)&&e.error)&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){return Bb(this,null,(function*(){switch(e.type){case Hk.ENDED:this.handleStopped(Hk.ENDED);break;case Hk.MUTE:this.handlePaused(Hk.MUTE);break;case Hk.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(Hk.UNMUTE))}}))}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};Ub(Wx,"PlayerEvent",Mx),Vb([Bx({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],Wx.prototype,"doReplayByRecreateMediaStream",1),Vb([Ix([],"PLAYING",{sync:!0,success(e){this.emit(Mx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],Wx.prototype,"handlePlaying",1),Vb([Ix("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(Mx.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],Wx.prototype,"handlePaused",1),Vb([Ix([],"STOPPED",{sync:!0,success(e){this.emit(Mx.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],Wx.prototype,"handleStopped",1);var Gx,jx="trtc_autoplay",Jx="".concat(jx,"_mask"),qx="".concat(jx,"_wrapper"),Kx="".concat(jx,"_header"),zx="".concat(jx,"_content"),Yx="".concat(jx,"_action_wrapper"),Xx="".concat(jx,"_question"),Qx="".concat(jx,"_collapse"),Zx="".concat(jx,"_action_confirm"),$x="".concat(jx,"_detail"),eV="#2473E8",tV="dialog",iV="".concat(tV,"-show"),rV="".concat(tV,"-1"),nV="".concat(tV,"-2"),oV=!1,sV=!1,aV=()=>sV,cV="".concat(Ak,"/").concat(Iw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),lV="<br><a href='".concat(cV,"' target='_blank'>").concat(Iw()?"其他方案?":"Any other solution?","</a>"),dV="".concat(Iw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(lV):"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(lV)),uV=class{constructor(){if(Ub(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Ub(this,"_dialogNode",null),Ub(this,"_bodyPosition",""),Ub(this,"_showDetail",!1),Ub(this,"_isCollapseClicked",!1),Ub(this,"_isQuestionClicked",!1),Iw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!oV){let e=document.createElement("style");e.innerHTML=".".concat(Jx,"{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(Jx," div:not(.").concat(Yx,"){display:block !important;}.").concat(qx,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(qx," a{color:").concat(eV,";}.").concat(Kx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(zx,"{margin:8px 0;}.").concat(Yx,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Qx,"{margin-right:auto;cursor:pointer}.").concat(Xx,"{height:100%;line-height:16px;cursor:pointer;}.").concat(Zx,"{margin-left:8px;color:#fff;background:").concat(eV,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(Zx,":hover{opacity:0.9;}.").concat(Qx,",.").concat(Zx,",.").concat(zx,",.").concat(Xx,"{font-size:14px;}@media screen and (max-width:750px){.").concat(qx,"{width:80vw;}}"),document.head.appendChild(e),oV=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(Jx,"\"><div class='").concat(qx,"'><div class='").concat(Kx,"'>").concat(location.host,"</div><div class='").concat(zx,"'>").concat(this.content,"</div><div class='").concat($x,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(dV,"</div><div class='").concat(Yx,"'></div></div></div>").trim();let t=document.createElement("button");t.className=Zx,t.innerText=Iw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=Xx,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 r=document.createElement("div");r.className=Qx,r.innerText="".concat(Iw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(Yx));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){aV()||(sV=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(qx)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",UM.info("show autoplay dialog"),Ux.uploadEvent({log:iV}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,sV=!1)}onConfirm(){UM.warn("confirm clicked, try resume stream"),MM.emit(LM.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat($x));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||Ux.uploadEvent({log:rV}),this._isCollapseClicked=!0}onQuestionClick(){window.open(cV,"_blank"),this._isQuestionClicked||Ux.uploadEvent({log:nV}),this._isQuestionClicked=!0}},hV=class extends Wx{constructor(e){super(e,Hk.VIDEO),Ub(this,"stat",{}),Ub(this,"_calculateTimeout",-1),Ub(this,"viewMirror",!1),Ub(this,"objectFit"),Ub(this,"container"),Ub(this,"canvas"),Ub(this,"_preSize",{width:0,height:0}),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,Dw(e.viewMirror)||(this.viewMirror=e.viewMirror),Dw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted)}initializeElement(){var e;let t=document.createElement(Hk.VIDEO);this.track&&2!==this.mode&&(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,zN&&(t.poster="noposter"),null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}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(Hk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Hk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(Hk.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===Hk.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,i,r,n,o,s,a,c;if(2===this.mode)return;super.handleElementEvent(e);let l=e.type;if(l===Hk.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=MD,this._log.info("view container ".concat(null==(i=this.container)?void 0:i.id," is recreated"))),this._pausedRetryCount>0&&!aV()&&!this._isPausedByUserCall&&(this._log.info("[".concat(MD-this._pausedRetryCount+1,"/").concat(MD,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;l===Hk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):l===Hk.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}l===Hk.RESIZE&&(this._preSize.height!==(null==(r=this.element)?void 0:r.videoHeight)||this._preSize.width!==(null==(n=this.element)?void 0:n.videoWidth))&&(this._log.info("video size changed to ".concat(null==(o=this.element)?void 0:o.videoWidth,"x").concat(null==(s=this.element)?void 0:s.videoHeight)),this._preSize.height=(null==(a=this.element)?void 0:a.videoHeight)||0,this._preSize.width=(null==(c=this.element)?void 0:c.videoWidth)||0,this.emit(Mx.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,n,o;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(n=this.container)||n.appendChild(e)):this.element&&(null==(o=this.container)||o.appendChild(this.element)))}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}setPoster(e){this.element&&(this.element.poster=e)}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Mx.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(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}calculateStat(){try{if(lx()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(i)}),2e3))};this.element.requestVideoFrameCallback(i)}}catch(pk){this._log.warn("init stat failed",pk)}}};function pV(e,t){return Bb(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),UM.info("worklet addModule success")}catch(pk){throw UM.info("worklet addModule catch error. ".concat(pk.message)),pk}}))}"undefined"!=typeof AudioContext?Gx=AudioContext:"undefined"!=typeof webkitAudioContext?Gx=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(Gx=mozAudioContext);var mV,_V=1500,fV=-1,gV=0,EV=-1,TV=!1,vV=0,yV=-1,SV=-1;!function e(){try{if(mV)return;(mV=new Gx({sampleRate:48e3})).onstatechange=()=>{UM.info("context state: ".concat(mV.state).concat("running"!==mV.state?" visibilityState: ".concat(document.visibilityState):"")),IV()},clearTimeout(fV)}catch(t){UM.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof Gx)),fV=setTimeout(e,1e3)}}();var IV=()=>{"suspended"===mV.state?(gV=Gw(),-1===EV&&(EV=setTimeout((()=>{"suspended"===mV.state&&(TV=!0,MM.emit("155",{isSuspended:!0}))}),_V)),CV(),document.addEventListener("click",IV)):"interrupted"===mV.state?CV():(gV&&(lL.addNumber({key:507800,value:Gw()-gV,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),gV=0),-1!==EV&&(clearTimeout(EV),EV=-1,TV&&(TV=!1,MM.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",IV),document.removeEventListener("click",IV))},AV=0,RV=-1;function CV(){return new Promise(((e,t)=>{if("running"===mV.state)return e();Date.now()-AV<1e3?(clearTimeout(RV),RV=setTimeout((()=>{AV=Date.now(),mV.resume().then(e,t)}),1e3)):(clearTimeout(RV),AV=Date.now(),mV.resume().then(e,t))})).catch((e=>{UM.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",IV)}))}document.addEventListener("click",IV);var bV=e=>mV,kV=class{constructor(e){this.name=e,Ub(this,"node"),Ub(this,"node2"),Ub(this,"pre",new Set),Ub(this,"next",new Set),Ub(this,"context"),Ub(this,"connectedNodes",new Set),Ub(this,"nextInputChannelMap",new Map),Ub(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(_D){UM.error(_D)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),lL.addSuccessEvent({key:502701})}catch(zM){UM.error(zM),lL.addFailedEvent({key:502701,error:zM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),lL.addSuccessEvent({key:502702})}catch(pk){UM.error(pk),lL.addFailedEvent({key:502702,error:pk})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{let i=this.nextInputChannelMap.get(t);e._connect(t.node,i)||t.connectNext(e)}))}_connect(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},DV=class extends kV{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,Ub(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,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},wV=class{constructor(){Ub(this,"source",new kV),Ub(this,"gain",new kV),Ub(this,"destination",new kV)}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(bV().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=PV(e);t&&this.source.replaceNode(t)}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}},NV=class extends wV{constructor(e){super(),this.context=e,Ub(this,"aec",new kV("aec")),Ub(this,"mixNode",new kV("mixNode")),Ub(this,"silentNode",new kV("silentNode")),Ub(this,"denoiser",new kV("denoiser")),Ub(this,"voiceChanger",new kV("voiceChanger")),this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.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.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},OV=class{constructor(){Ub(this,"audioContext",bV()),Ub(this,"destination",this.audioContext.createMediaStreamDestination()),Ub(this,"inputs",new Set),Ub(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]}},MV=new WeakMap;function PV(e){try{let t=MV.get(e);if(t)return t;let i=bV();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return MV.set(e,t),t}catch(qM){if(!(ZN&&qM instanceof Error&&"NotSupportedError"===qM.name))throw qM;UM.warn(qM)}}var LV=class e{constructor(e){Ub(this,"_volume",0),Ub(this,"_volumeDb",0),Ub(this,"_log"),Ub(this,"_scriptProcessorNode",null),Ub(this,"_audioWorkletNode",null),Ub(this,"_interval",200),Ub(this,"ready",this.preload());let{log:t}=e;this._log=t,MM.on(LM.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-e.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!e.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';e.workletReady=pV(e.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return e.workletReady.then((()=>this.initAudioWorklet())).catch((e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor())))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(e.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{e.lastMessageTime=Date.now(),this._volume=i.data.volume||0,this._volumeDb=i.data.volumeDb||0,!t&&i.data.cacheLen&&i.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(qM){this._log.error("volumeMeter init audio worklet error: ".concat(qM)),Ux.logFailedEvent({userId:this._log.userId,eventType:gD.LOAD_WORKLET,error:qM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=bV().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{e.lastMessageTime=Date.now();let i=t.inputBuffer.getChannelData(0),r=0;for(let e=0;e<i.length;++e)r+=i[e]*i[e];this._volume=Math.sqrt(r/i.length)||0}}catch(qM){this._log.error("volumeMeter init script processor error: ".concat(qM))}}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,MM.off(LM.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}};Ub(LV,"lastMessageTime",0),Ub(LV,"audioContext",bV()),Ub(LV,"workletReady");var xV=LV,VV=class extends kV{constructor(e){super(),Ub(this,"_volumeMeter"),this._volumeMeter=new xV(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return Bb(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},UV=xV,FV=xb(Hb(),1),BV=e=>t=>t.deviceId===e,HV=class{constructor(e,t){Ub(this,"kind"),Ub(this,"type"),Ub(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&&jV(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(BV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");UM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(BV(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");UM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},WV=class extends FV.EventEmitter{constructor(){super(),Ub(this,"audioInputs",new HV(Hk.AUDIO,"Input")),Ub(this,"videoInputs",new HV(Hk.VIDEO,"Input")),Ub(this,"audioOutputs",new HV(Hk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||Ox.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){JV().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return Bb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield JV(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}hasBlueTooth(){var e;if(1e3*(null==(e=bV())?void 0:e.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some((e=>t.some((t=>e.label.toLowerCase().includes(t)))))||this.audioInputs.devices.some((e=>t.some((t=>e.label.toLowerCase().includes(t)))))}},GV=fk||_k?null:new WV;function jV(e){return e.deviceId===e.groupId&&""===e.groupId}function JV(){return Bb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(gL()||!_L())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{jV(e)&&(e.kind===Hk.AUDIO_INPUT?i.audio=!0:e.kind===Hk.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),i.audio&&CV()}catch(zM){UM.debug("capture before getDevices failed: ",zM)}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&&XV.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function qV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return GV.update(e?1:0).then((e=>e.audioInputs.devices))}function KV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return GV.update(e?2:0).then((e=>e.videoInputs.devices))}var zV=!1;function YV(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Bb(this,null,(function*(){return(KN||rM)&&(e=!1),GV.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var XV=new Set;function QV(e,t){return Bb(this,null,(function*(){let i=(yield qV()).find((e=>e.deviceId===PD));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var ZV,$V=class extends wV{constructor(e){super(),this.log=e,Ub(this,"volumeMeter"),Ub(this,"volumeMeterAfter3A"),Ub(this,"volumeDestination"),Ub(this,"analyser",new DV),this.volumeMeter=new VV({log:this.log}),this.volumeMeterAfter3A=new VV({log:this.log}),this.volumeDestination=new kV,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},eU=class e extends Wx{constructor(e){super(e,Hk.AUDIO),Ub(this,"_outputDeviceId"),Ub(this,"_volume",1),Ub(this,"_destination",bV().createMediaStreamDestination()),Ub(this,"pipeline"),Ub(this,"volumeMeterMode","worklet"),Ub(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new $V(this._log)}get duration(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*((null==(e=this.element)?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===aM||"15.3"===aM||"15.4"===aM)&&this.muted)return void this._log.info("audioElement is muted.");let t=ZV||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.url&&(t.crossOrigin="anonymous",t.src=this.url),this.element=t,Nw(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===ZV&&(ZV=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Mx.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return Bb(this,null,(function*(){if(this.track||this.url)return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==t?void 0:t.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(bV().createAnalyser()),function(){Bb(this,null,(function*(){try{zV||(zV=!0,UM.info("speakers:".concat((yield YV()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}(),Fb(e.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}setSinkId(e){return Bb(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()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},tU=class extends eU{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Mx.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},iU=class extends eU{constructor(e){super(e),Ub(this,"_sourceElement"),Ub(this,"_output",new kV),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(bV().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Mx.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.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(e<=1&&!KN)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(KN){if(!this.enableVolumeControlInIOS)return;!function(){if(!KN||-1!==SV)return;let e=()=>{Gw()-vV<500||(mV&&"running"===mV.state&&mV.currentTime===yV&&(UM.warn("context is fake running, auto resume"),mV.suspend().catch((e=>{UM.warn("context suspend failed: ".concat(e))}))),yV=mV.currentTime,vV=Gw())};SV=setInterval((()=>{e()}),2e3),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&e()}))}()}if(ZN&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Vx(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&nM&&(ZV=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},rU=class extends Cx{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?iU:hV)}=e;var s;super(),Ub(this,"id",FM()),Ub(this,"userId",""),Ub(this,"isRemote"),Ub(this,"mediaType"),Ub(this,"room"),Ub(this,"user"),Ub(this,"_log"),Ub(this,"_inputTrack"),Ub(this,"_outputTrack"),Ub(this,"isPlayCalled"),Ub(this,"container",null),Ub(this,"player"),Ub(this,"subVideoPlayerMap"),Ub(this,"muted",!1),Ub(this,"abortCtrl"),Ub(this,"objectFit","cover"),Ub(this,"mirror"),Ub(this,"rotation"),Ub(this,"isScreen",!1),Ub(this,"manager"),Ub(this,"trackSettings"),Ub(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=UM.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof jB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof jB}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:null==n?void 0:n.enableVolumeControlInIOS}),this.player.on(Mx.PLAYER_STATE_CHANGED,(e=>{MM.emit(LM.PLAYER_STATE_CHANGED,Ob({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Hk.VIDEO&&(this.player.on(Mx.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(Mx.LOADED_DATA),MM.emit(LM.VIDEO_LOADED_DATA,{track:this})})),this.player.on(Mx.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(Mx.LOADED_META_DATA)})),this.player.on(Mx.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})),this.player.on(Mx.RESIZE,(e=>{this.emitFirstVideoFrameEvent(Mx.RESIZE),this.emit("video-size-changed",Ob({userId:this.userId,streamType:2===this.mediaType?"auxiliary":"main"},e))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Mx.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||UM}get kind(){return 1===this.mediaType?Hk.AUDIO:Hk.VIDEO}get isAudio(){return this.kind===Hk.AUDIO}get strMediaType(){return 4===this.mediaType?Hk.VIDEO:2===this.mediaType?Hk.SCREEN:Hk.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}play(e,t){return Bb(this,null,(function*(){let i=Pw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!Dw(t.muted)&&this.setPlayerMute(t.muted),t&&!Dw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof hV&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Pw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!Dw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Hk.VIDEO)&&this.setPlayerMute(!0),t&&!Dw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof hV&&(this.player.setObjectFit(this.objectFit),t&&!Dw(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof hV&&this.player.setContainer(i)),MM.emit(LM.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(t),Pw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(QM){throw this.handleAutoPlayFailed(QM),QM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Hk.VIDEO||Dw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Ow(this.mirror))return i.setViewMirror(this.mirror),void(!this.isRemote&&r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return Bb(this,null,(function*(){if(!this._outputTrack||this.kind===Hk.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(Dw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new hV({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+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(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ON(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return Bb(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(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),MM.emit(e?LM.TRACK_MUTED:LM.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}installTrackEvent(e){xx(e,e).add(Hk.MUTE,this.onTrackMuted).add(Hk.UNMUTE,this.onTrackUnmuted).add(Hk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Hk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Vx(e)}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,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),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._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),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((e=>this.handleAutoPlayFailed(e))),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(ON(this)?this.jitterBufferDelay:0),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(e){if(this.room&&this.room.enableAutoPlayDialog)new uV;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof hV?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=null==(t=this.mediaTrack)?void 0:t.getSettings(),o=(null==n?void 0:n.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,s=(null==n?void 0:n.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===Mx.RESIZE&&!o&&!s||e===Mx.LOADED_META_DATA&&!o&&!s||(e===Mx.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,mN(this.rotation)&&([o,s]=[s,o]),this.emit("first-video-frame",{width:o,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};Vb([Ix([],Cx.INIT,{sync:!0})],rU.prototype,"close",1);var nU=Object.prototype.hasOwnProperty;var oU=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(Aw(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(nU.call(e,t))return!1;return!0}return!1},sU=PN({retryFunction:function(e){return Bb(this,null,(function*(){let t=function(e){return{audio:cU(e),video:lU(e)}}(e);UM.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];if(t.audio&&(i=yield qV(),UM.info("microphones: ".concat(iN(i.map((e=>Mb(Ob({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:n})))),t.video&&(r=yield KV(),UM.info("cameras: ".concat(iN(r,{keysToInclude:n}))),"user"===t.video.facingMode&&!t.video.deviceId)){let e=r.filter((e=>!e.label.includes("infrared"))).find((e=>e.label.includes("facing front")));e&&(t.video.deviceId=e.deviceId,UM.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let i=yield navigator.mediaDevices.getUserMedia(t);return YL&&i.getTracks().forEach((t=>{var i;let r=t.getCapabilities();UM.info("".concat(t.kind," capabilities: ").concat(iN(r,{keysToInclude:HD}))),!Dw(e.echoCancellation)&&-1===(null==(i=r.echoCancellation)?void 0:i.indexOf(e.echoCancellation))&&UM.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(r.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))})),t.audio&&CV(),i}catch(QM){let{message:n}=QM;throw"NotFoundError"===QM.name&&(e.video&&r&&0===r.length&&(n=ZP({key:zP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=ZP({key:zP.MICROPHONE_NOT_FOUND}))),new ek({code:Zb.INITIALIZE_FAILED,name:QM.name,message:n,constraint:QM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name||"AbortError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!rM||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&aU(n[0].microphoneId,!1),n[0].cameraId&&aU(n[0].cameraId,!0)},onRetrying:e=>{UM.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{Ux.logFailedEvent({eventType:gD.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{Ux.logSuccessEvent({eventType:gD.GET_USER_MEDIA_RETRY}),Ux.uploadEvent({log:"stat-".concat(gD.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function aU(e,t){return Bb(this,null,(function*(){let i=(t?yield KV():yield qV()).find((t=>t.deviceId===e));i&&kw(i.getCapabilities)&&UM.warn(iN(i.getCapabilities(),{keysToInclude:HD}))}))}function cU(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!oU(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(Nw(e.channelCount)&&(t.channelCount=e.channelCount),(Ow(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),Ow(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Ow(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!oU(t)||t)}function lU(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&&!oU(i)?i:(e.width&&(i.width={ideal:e.width},t&&!ZN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!ZN&&(i.height.max=e.height)),ZN&&DO&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!oU(i)||i)}var dU=sU;function uU(e){return mU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Bb(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function hU(e){return mU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Bb(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function pU(e){return mU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return Bb(this,null,(function*(){try{return yield t.apply(this,r)}catch(zM){e.call(this,zM)}}))}))}function mU(e){return function(t,i,r){return r.value=e(r.value,i),r}}var _U=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&UM.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{UM.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),fU=0,gU=class{constructor(){Ub(this,"log",UM.createLogger({id:"fq".concat(++fU)})),Ub(this,"isRunning",!1),Ub(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=Ob({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},EU=new WeakMap,TU=new WeakMap;function vU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let t=EU.get(this)||new gU;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return EU.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function yU(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=EU.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=TU.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new ek({code:Zb.API_CALL_ABORTED,message:e}))})),EU.delete(this),TU.delete(this),n.apply(this,a)},r}}function SU(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=TU.get(this)||new Map,s=r.get(o(t))||new gU;return r.set(o(t),s),TU.set(this,r),s.push({fn:n,args:t,context:this})},r}}function IU(e,t){return mU(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=Gw();return Vw(e)?e.then((e=>(t?lL.addSuccessEvent({key:r,cost:Gw()-a}):lL.addSuccessEvent({key:r}),e))).catch((e=>{throw lL.addFailedEvent({key:r,error:e}),e})):(lL.addSuccessEvent({key:r}),e)}catch(mk){throw lL.addFailedEvent({key:r,error:mk}),mk}}))}var AU={};function RU(){}Lb(AU,{Events:()=>BU,Inspect:()=>NU,LastSink:()=>OU,Sink:()=>MU,Subscribe:()=>PU,TimeoutError:()=>HU,audit:()=>zF,bindCallback:()=>IF,bindNodeCallback:()=>AF,buffer:()=>eF,bufferCount:()=>$U,bufferTime:()=>NB,call:()=>CU,catchError:()=>MB,combineLatest:()=>YU,concat:()=>qU,concatMap:()=>TB,concatMapTo:()=>vB,count:()=>wF,create:()=>xU,debounce:()=>QF,debounceTime:()=>ZF,defer:()=>rF,delay:()=>OB,deliver:()=>VU,dispose:()=>kU,elementAt:()=>$F,empty:()=>bF,every:()=>nB,exhaustMap:()=>bB,exhaustMapTo:()=>kB,expand:()=>LB,filter:()=>PF,find:()=>eB,findIndex:()=>tB,first:()=>iB,fromAnimationFrame:()=>yF,fromArray:()=>dF,fromEvent:()=>_F,fromEventPattern:()=>mF,fromFetch:()=>gF,fromIterable:()=>EF,fromPromise:()=>fF,fromReadableStream:()=>vF,fromReader:()=>TF,groupBy:()=>DB,identity:()=>bU,ignoreElements:()=>LF,iif:()=>zU,inspect:()=>DU,interval:()=>uF,last:()=>rB,map:()=>cB,mapTo:()=>lB,max:()=>NF,merge:()=>jU,mergeMap:()=>IB,mergeMapTo:()=>AB,min:()=>OF,never:()=>RF,nothing:()=>RU,of:()=>lF,pairwise:()=>sB,pipe:()=>LU,race:()=>JU,range:()=>SF,reduce:()=>DF,retry:()=>HB,scan:()=>oB,setAsapScheduler:()=>aF,share:()=>GU,shareReplay:()=>KU,skip:()=>BF,skipUntil:()=>HF,skipWhile:()=>WF,startWith:()=>QU,subject:()=>iF,subscribe:()=>UB,sum:()=>MF,switchMap:()=>mB,switchMapTo:()=>fB,take:()=>xF,takeLast:()=>FF,takeUntil:()=>VF,takeWhile:()=>UF,tap:()=>FB,throttle:()=>qF,throwError:()=>CF,timeInterval:()=>wB,timeout:()=>BB,timer:()=>hF,toPromise:()=>xB,toReadableStream:()=>VB,withLatestFrom:()=>ZU,zip:()=>XU});var CU=e=>e(),bU=e=>e;function kU(){this.dispose()}var DU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,wU=1,NU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new FU(e,this,this.streamId++);return BU.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},OU=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=RU,this.error=RU,this.next=RU,this.dispose=RU,this.subscribe=RU,this.doDefer()}subscribe(e){return e instanceof NU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(CU),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}},MU=class extends OU{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)}},PU=class extends OU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:RU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:RU,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:RU;if(super(),this._next=t,this._error=i,this._complete=r,this.then=RU,e instanceof NU){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{BU.defer(n,0)})),BU.create(n),BU.pipe(n),this.sourceId=n.id,this.subscribe(e),BU.subscribe({id:n.id,end:!0}),t==RU?this._next=e=>BU.next(n,0,e):this.next=e=>{BU.next(n,0,e),t(e)},r==RU?this._complete=()=>BU.complete(n,0):this.complete=()=>{this.dispose(),BU.complete(n,0),r()},i==RU?this._error=e=>BU.complete(n,0,e):this.error=e=>{this.dispose(),BU.complete(n,0,e),i(e)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function LU(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return i.reduce(((e,t)=>t(e)),e)}function xU(e,t,i){if(DU()){let r=Object.defineProperties(Object.setPrototypeOf(e,NU.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}});BU.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof NU&&BU.addSource(r,t)}return r}return e}function VU(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return i=>{if(i instanceof NU){let n=xU((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,BU.pipe(n),n}return t=>i(new e(t,...r))}}}function UU(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var FU=class extends MU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{BU.defer(this.source,this.id)}))}next(e){BU.next(this.source,this.id,e),this.sink.next(e)}complete(){BU.complete(this.source,this.id),this.sink.complete()}error(e){BU.complete(this.source,this.id,e),this.sink.error(e)}},BU={addSource(e,t){UU("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){UU("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;UU("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){UU("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){UU("defer",{id:e.id,streamId:t})},pipe(e){UU("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){UU("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=wU++),UU("create",{name:e.toString(),id:e.id})}},HU=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},WU=class extends OU{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()}};function GU(){return e=>{let t=new WU(e);if(e instanceof NU){let i=xU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,BU.pipe(i),i}return xU(t.add.bind(t),"share",arguments)}}function jU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU((e=>{let i=new MU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function JU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU((e=>{let i=new Map;t.forEach((t=>{let r=new MU(e);i.set(t,r),r.complete=()=>{i.delete(t),0===i.size?e.complete():r.dispose()},r.next=e=>{i.delete(t),i.forEach((e=>e.dispose())),r.resetNext(),r.resetComplete(),r.next(e)}})),t.forEach((e=>i.get(e).subscribe(e)))}),"race",arguments)}function qU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU((e=>{let i=0,r=t.length,n=new MU(e);n.complete=()=>{i<r&&!n.disposed?(n.doDefer(),n.subscribe(t[i++])):e.complete()},n.complete()}),"concat",arguments)}function KU(e){return t=>{let i=new WU(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},xU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function zU(e,t,i){return xU((r=>e()?t(r):i(r)),"iif",arguments)}function YU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU((e=>{let i=t.length,r=i,n=i,o=new Array(i),s=()=>{0==--n&&e.complete()};t.forEach(((t,i)=>{let n=new MU(e);n.next=t=>{r--,n.next=t=>{o[i]=t,0===r&&e.next(o)},n.next(t)},n.complete=s,n.subscribe(t)}))}),"combineLatest",arguments)}function XU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU((e=>{let i=t.length,r=i,n=new Array(i),o=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new MU(e),s=[];n[i]=s,r.next=t=>{s.push(t),n.every((e=>e.length))&&e.next(n.map((e=>e.shift())))},r.complete=o,r.subscribe(t)}))}),"zip",arguments)}function QU(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>xU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<n&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}var ZU=VU(class extends MU{constructor(e){super(e);let t=new MU(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];t.next=e=>this.buffer=e,t.complete=RU,t.subscribe(YU(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),$U=VU(class extends MU{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((e=>this.sink.next(e))),super.complete()}},"bufferCount"),eF=VU(class extends MU{constructor(e,t){super(e),this.buffer=[];let i=new MU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=RU,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),tF=function(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{c(r.next(e))}catch(t){o(t)}}function a(e){try{c(r.throw(e))}catch(t){o(t)}}function c(e){e.done?n(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(s,a)}c((r=r.apply(e,t||[])).next())}))};function iF(e){let t=arguments,i=GU()(xU((t=>{i.next=e=>t.next(e),i.complete=()=>t.complete(),i.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return i.next=RU,i.complete=RU,i.error=RU,i}function rF(e){return xU((t=>t.subscribe(e())),"defer",arguments)}var nF={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},oF="undefined"!=typeof Promise?nF.promise:nF.setImmediate?nF.setImmediate:nF.setTimeout,sF=e=>t=>{oF((()=>e(t)))},aF=e=>{"function"==typeof e?oF=e:nF[e]&&(oF=nF[e])},cF=e=>sF((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function lF(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return xU(cF(t),"of",arguments)}function dF(e){return xU(cF(e),"fromArray",arguments)}function uF(e){return xU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function hF(e,t){return xU((i=>{let r=0,n=setTimeout((()=>{if(i.removeDefer(o),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),o=()=>clearTimeout(n);i.defer(o)}),"timer",arguments)}function pF(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function mF(e,t){return xU(pF(e,t),"fromEventPattern",arguments)}function _F(e,t){if("on"in e&&"off"in e)return xU(pF((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return xU(pF((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return xU(pF((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function fF(e){return xU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function gF(e,t){return xU(rF((()=>fF(fetch(e,t)))),"fromFetch",arguments)}function EF(e){return xU(sF((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(pk){t.error(pk)}})),"fromIterable",arguments)}function TF(e){let t=i=>tF(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:n}=yield e.read();r?i.complete():(i.next(n),t(i))}));return xU((e=>{t(e)}),"fromReader",arguments)}function vF(e){return xU((t=>{let i=new AbortController,r=i.signal;t.defer((()=>i.abort("cancelled"))),e.pipeTo(new WritableStream({write(e){t.next(e)},close(){t.complete()},abort(e){t.error(e)}}),{signal:r}).then((()=>t.complete()),(e=>t.error(e)))}),"fromReadableStream",arguments)}function yF(){return xU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function SF(e,t){return xU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<n&&!i.disposed;)i.next(r++);return i.complete(),"range"}),"range",arguments)}function IF(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return xU((i=>{let n=r.concat((e=>(i.next(e),i.complete())));e.apply(t,n)}),"bindCallback",arguments)}function AF(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return xU((i=>{let n=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,n)}),"bindNodeCallback",arguments)}function RF(){return xU((()=>{}),"never",arguments)}function CF(e){return xU((t=>t.error(e)),"throwError",arguments)}function bF(){return xU((e=>e.complete()),"empty",arguments)}var kF=class extends MU{constructor(e,t,i){super(e),this.f=t;let r=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===i?this.next=e=>{this.acc=e,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},DF=VU(kF,"reduce"),wF=e=>VU(kF,"count")(((t,i)=>e(i)?t+1:t),0),NF=()=>VU(kF,"max")(Math.max),OF=()=>VU(kF,"min")(Math.min),MF=()=>VU(kF,"sum")(((e,t)=>e+t),0),PF=VU(class extends MU{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),LF=VU(class extends MU{next(e){}},"ignoreElements"),xF=VU(class extends MU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&(this.doDefer(),this.complete())}},"take"),VF=VU(class extends MU{constructor(e,t){super(e);let i=new MU(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=kU,i.subscribe(t)}},"takeUntil"),UF=VU(class extends MU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),FF=e=>DF(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),BF=VU(class extends MU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),HF=VU(class extends MU{constructor(e,t){super(e),e.next=RU;let i=new MU(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=kU,i.subscribe(t)}},"skipUntil"),WF=VU(class extends MU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),GF={leading:!0,trailing:!1},jF=class extends MU{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},JF=class extends MU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:GF;super(e),this.durationSelector=t,this.config=i,this._throttle=new jF(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=RU,this._throttle.complete(),super.complete()}},qF=VU(JF,"throttle"),KF={leading:!1,trailing:!0},zF=e=>VU(JF,"audit")(e,KF),YF=class extends MU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},XF=class extends MU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new YF(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},QF=VU(XF,"debounce"),ZF=e=>VU(XF,"debounceTime")((t=>hF(e))),$F=VU(class extends MU{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),eB=e=>t=>xF(1)(WF((t=>!e(t)))(t)),tB=VU(class extends MU{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),iB=VU(class extends MU{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),rB=VU(class extends MU{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),nB=VU(class extends MU{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),oB=VU(class extends MU{constructor(e,t,i){super(e),this.f=t,void 0===i?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),sB=VU(class extends MU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),aB=class extends MU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},cB=VU(aB,"map"),lB=e=>VU(aB,"mapTo")((t=>e)),dB=class extends MU{constructor(e,t,i){super(e),this.data=t,this.context=i}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},uB=class e extends MU{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(t,i){let r=this.currentSink=new i(this.sink,t,this);this.complete===e.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},hB=class extends dB{},pB=class extends uB{next(e){this.subInner(e,hB),this.next=e=>{this.currentSink.dispose(),this.subInner(e,hB)}}},mB=VU(pB,"switchMap");function _B(e){return(t,i)=>e((()=>t),i)}var fB=_B(VU(pB,"switchMapTo")),gB=class extends dB{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},EB=class extends uB{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),gB),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},TB=VU(EB,"concatMap"),vB=_B(VU(EB,"concatMapTo")),yB=class extends dB{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},SB=class extends uB{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,yB),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},IB=VU(SB,"mergeMap"),AB=_B(VU(SB,"mergeMapTo")),RB=class extends dB{dispose(){this.context.resetNext(),super.dispose()}},CB=class extends uB{next(e){this.next=RU,this.subInner(e,RB)}},bB=VU(CB,"exhaustMap"),kB=_B(VU(CB,"exhaustMapTo")),DB=VU(class extends MU{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),i=this.groups.get(t);void 0===i&&(i=iF(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},"groupBy"),wB=VU(class extends MU{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),NB=VU(class extends MU{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval((()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0}),this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),OB=VU(class extends MU{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout((()=>{let e=this.buffer.shift();if(e){let{time:t,data:i}=e;super.next(i),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}}),e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout((()=>super.complete()),this.delayTime)}},"delay"),MB=VU(class extends MU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),PB=class extends dB{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},LB=VU(class extends uB{constructor(e,t){super(e,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(e){this.sink.next(e),this.expandValue(e)}expandValue(e){let t=new PB(this.sink,e,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(e,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&0===this.inners.size&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),xB=()=>e=>new Promise(((t,i)=>{let r;new PU(e,(e=>r=e),i,(()=>t(r)))})),VB=()=>e=>{let t;return new ReadableStream({start(i){t=new PU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},UB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:RU,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:RU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:RU;return r=>new PU(r,e,t,i)},FB=VU(class extends MU{constructor(e,t){super(e),t instanceof Function?this.next=i=>{t(i),e.next(i)}:(t.next&&(this.next=i=>{t.next(i),e.next(i)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=i=>{t.error(i),e.error(i)}))}},"tap"),BB=VU(class extends MU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new HU(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),HB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof NU){let i=xU((r=>{let n=e,o=new MU(r);o.error=e=>{n-- >0?o.subscribe(t):r.error(e)},o.sourceId=i.id,o.subscribe(t)}),"retry",[e]);return i.source=t,BU.pipe(i),i}return i=>{let r=e,n=new MU(i);n.error=e=>{r-- >0?t(n):i.error(e)},t(n)}}},WB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(WB||{}),GB=class e extends rU{constructor(e,t){super({mediaType:e,PlayerClass:t}),Ub(this,"isRemote",!1),Ub(this,"deviceId"),Ub(this,"groupId",""),Ub(this,"label",""),Ub(this,"sourceTrack"),Ub(this,"enableAutoSwitchWhenRecapturing",!0),Ub(this,"_isRecapturing",!1),Ub(this,"_lastRecaptureTime",0),Ub(this,"_onMuteTimeoutId",-1),Ub(this,"_encodeCheckTimeoutId",-1),Ub(this,"recaptureMode",0),Ub(this,"profile"),Ub(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){xx(e,e).add(Hk.MUTE,this.onTrackMuted).add(Hk.UNMUTE,this.onTrackUnmuted).add(Hk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Hk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Vx(e)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Bb(this,null,(function*(){var i;let r=this.sourceTrack;try{let r,n=Gw();MM.emit(LM.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(t||null==(i=this.sourceTrack)||i.stop(),r=yield dU(e));let o=r.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.sourceTrack=o,this.updateDeviceIdInUse(),this.listenDeviceChange()),MM.emit(LM.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Gw()-n}),r}catch(mk){throw MM.emit(LM.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:mk}),this.log.error("getUserMedia error observed ".concat(mk)),mk}finally{t&&(null==r||r.stop())}}))}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}get hasFlag(){var e,t;let i=zw((null==(e=this.room)?void 0:e.localPublishFlag)||0,(null==(t=this.room)?void 0:t.userId)||"");return 4===this.mediaType&&i.hasVideo||1===this.mediaType&&i.hasAudio||2===this.mediaType&&i.hasAuxiliary}publish(e,t){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),Promise.all([t,new Promise(((t,i)=>Bb(this,null,(function*(){var r,n;this.hasFlag||this.muted?t():LU(_F(e,"local-publish-flag-changed"),PF((()=>this.hasFlag)),VF(jU(_F(this,Cx.INIT),_F(this,"ready"))),UB(t)),!(((null==(n=null==(r=this.room)?void 0:r.networkQuality)?void 0:n.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>Bb(this,null,(function*(){var e,t,r,n,o,s;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this.isPublished||this.isPublishing)&&this.isMediaTrackActive){let e=this.kind===Hk.AUDIO,t=this.stat.bytesSent>0;if(lL[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(n=null==(r=this.room)?void 0:r.videoCodec)?void 0:n.toUpperCase())||"H264"];e&&lL[t?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!t){if(lL.addEnum({key:e?503701:513703,value:kM()}),Ux.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(AM()||wM()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(s=null==(o=this.room)?void 0:o.videoCodec)?void 0:s.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield lN(5e3),this.stat.bytesSent>0||this.hasFlag)))return;this.emit("6",this),i(new ek({message:"".concat(this.strMediaType," encode failed"),code:e?Zb.AUDIO_ENCODE_FAILED:Zb.VIDEO_ENCODE_FAILED}))}}}))),5e3))}))))])}unpublish(){this.room&&this.room.localTracks.delete(this),MM.emit(LM.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return Bb(this,null,(function*(){if(this.sourceTrack&&zL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return Bb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Hk.AUDIO||t!==PD||(yield QV(r,n)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),JV().then((i=>{let r=i.find((i=>{let r=i.deviceId===e;return t&&(r=r&&i.groupId===t),r}));r&&this.emit("2",r)})))}}))}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.sourceTrack||this.kind===Hk.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(Hk.AUDIO_INPUT);return!!XV.has(i)}(this.sourceTrack)||this.kind===Hk.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(Hk.VIDEO_INPUT);return!!XV.has(i)}(this.sourceTrack)||this._isRecapturing||e&&DO&&rM)}onTrackMuted(){if(super.onTrackMuted(),_U(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<BD)return void setTimeout((()=>this.onTrackMuted()),BD);this._onMuteTimeoutId=setTimeout((()=>Bb(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((KN||zN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return Bb(this,null,(function*(){if(Fb(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<BD)return void setTimeout((()=>this.onTrackEnded()),BD);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Bb(this,null,(function*(){var i;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||null==(i=this.sourceTrack)||i.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let n={useExactDeviceId:!0};if("user"===e||"environment"===e)n.facingMode=e;else{let t;("audio"===this.kind?yield qV():yield KV()).find((t=>t.deviceId===e))&&(t=e),n.deviceId=t}return this.capture(n,t).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),MM.emit(LM.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),MM.emit(LM.LOCAL_TRACK_RECAPTURE,{track:this,error:e})})).finally((()=>{t&&(null==r||r.stop())}))}))}getRecoverCaptureDeviceId(){return Bb(this,null,(function*(){let e=this instanceof XB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(JB.get(t)||0)+1;if(JB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield KV()).find((e=>!JB.has(e.deviceId))):(yield qV()).find((e=>!JB.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};Vb([Ix(Cx.INIT,"ready",{ignoreError:!0,sync:!0})],GB.prototype,"setStateToReady",1),Vb([vU()],GB.prototype,"capture",1),Vb([Ix("ready","publish",{ignoreError:!0,success(){MM.emit(LM.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){var t;null==(t=this.room)||t.localTracks.delete(this);let i="error";if(e.cause instanceof ek){let t=e.cause;t.message.includes("timeout")?i="timeout":t.code===Zb.API_CALL_ABORTED&&(i="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e.cause||e})}}),IU(521714,!1),wH(10)],GB.prototype,"publish",1),Vb([mU((e=>function(){return Bb(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"}),clearTimeout(this._encodeCheckTimeoutId)}))})),Ix([],"ready",{sync:!0})],GB.prototype,"unpublish",1);var jB=GB,JB=new Map;MM.on(LM.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&JB.delete(e.track.deviceId)}));var qB=class e extends jB{constructor(e){super(1,tU),Ub(this,"mediaType",1),Ub(this,"volume",0),Ub(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Ub(this,"playerMuted",!0),Ub(this,"pipeline"),Ub(this,"earMonitorGainNode",new kV),Ub(this,"_output",new kV),Ub(this,"codecPipeline",[]),Ub(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Ub(this,"mixedAudioReferenceMap",new Map),Ub(this,"isAudioContextLongSuspended",!1),Ub(this,"after3aSilenceStartTime",0),this.manager=e,this.pipeline=new NV(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),MM.on(LM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return UV.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){Dw(e)||(0!==e||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=Gw())}setInputMediaStreamTrack(t){return Bb(this,null,(function*(){let i=this.trackSettings||{};lL.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),lL.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),lL.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:n}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:n}))),this.pipeline.source.channelCount=n||1,this.pipeline.replaceSource(t),yield Fb(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(t){return Bb(this,arguments,(function(t){var i=this;let{deviceId:r,customSource:n,useExactDeviceId:o=!0,retryWhenExactFailed:s}=t,a=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield Fb(e.prototype,i,"capture").call(i,{video:!1,audio:!0,microphoneId:r,echoCancellation:i.profile.echoCancellation,autoGainControl:i.profile.autoGainControl,noiseSuppression:i.profile.noiseSuppression,sampleRate:i.profile.sampleRate,channelCount:i.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:s,customSource:n},a);return CV(),t}()}))}switchDevice(e){return Bb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==PD)return;if(yield QV(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),MM.emit(LM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(_D){throw this.log.error("switch microphone failed ".concat(_D)),this.deviceId&&this.recapture(this.deviceId),_D}}}))}listenDeviceChange(){GV&&!GV.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&GV.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return Bb(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(WB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){VH(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield qV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&GV.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(GV.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return Bb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let o=e.getConstraints(),s=!1;!Dw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,o.echoCancellation=i,s=!0),!Dw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!Dw(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,o.autoGainControl=n,s=!0),s&&(ZN||rM?yield e.applyConstraints(o).catch((e=>t._log.warn("update3A failed: ",e))):t.deviceId&&(yield t.recapture(t.deviceId,!0)))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&lL.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),KN&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(bV().createGain()),this._output.setNode(bV().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!rM&&!KN)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;eM<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(lL.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info("mixAudioReference() => ".concat(t));let i=PV(e);if(!i)return;let r=new kV,n=bV().createGain();n.gain.value=1;let o=new kV;r.pipeTo(o).pipeTo(this.pipeline.mixNode),r.setNode(i),o.setNode(n),this.mixedAudioReferenceMap.set(t,[r,o])}unMixAudioReference(e){let[t,i]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info("unMixAudioReference() => ".concat(e)),t.deleteNode(),null==i||i.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[i,r]=this.mixedAudioReferenceMap.get(e)||[];null!=r&&r.node&&(r.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(r.node.gain.value)))}addAudioProcessor(e,t,i){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach((e=>{let[t,i]=e;t.deleteNode(),i.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),GV.off("audioInputAdded",this.handleMicrophoneAdded,this),GV.off("audioInputRemoved",this.handleMicrophoneRemoved,this),MM.off(LM.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Bb(this,null,(function*(){try{yield Fb(e.prototype,this,"recapture").call(this,t,i)}catch(zM){let r=(yield qV()).find((e=>e.deviceId!==t));if(!r)throw zM;yield Fb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,ntp:ok()}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}handleAudioContextLongSuspended(e){let{isSuspended:t}=e;if(this.pipeline.isProcessEnabled)if(t){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(nM?"":", non-Safari"));let e=this.sourceTrack||this.mediaTrack;e&&this.setOutputMediaStreamTrack(e)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}},KB=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=[],r=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===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}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 n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},zB=class{constructor(){Ub(this,"_seiMessageList",[]),Ub(this,"_smallSeiMessageList",[]),Ub(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new KB(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}isEmpty(){return!this._seiMessageList.length}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let r=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},YB=class e extends jB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,hV),Ub(this,"profile",Ob({},Uk)),Ub(this,"avoidCropping",!1),Ub(this,"_scaleResolutionDownBy"),Ub(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),Ub(this,"small"),Ub(this,"isNeedToSetBandwidth"),Ub(this,"muteImage"),Ub(this,"manager"),Ub(this,"_seiCodec",new zB),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(Mb(Ob({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(zL&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}get hasSmall(){var e;return!(null==(e=this.manager)||!e.hasSmall)}setMute(t){return Bb(this,null,(function*(){var i,r,n;if(ww(t)){if(this.muteImage===t)return;yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),yield null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t}),this.muteImage=t,Fb(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(n=this.manager)?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Fb(e.prototype,this,"setMute").call(this,t)}))}capture(t){return Bb(this,arguments,(function(t){var i=this;let{deviceId:r,facingMode:n,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:a=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:n||i.facingMode,cameraId:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:a,customSource:s};if("environment"===t.facingMode){let e=yield i.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return Fb(e.prototype,i,"capture").call(i,t)}()}))}setProfile(e){let t=this.fallbackProfile(e);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(Mb(Ob({},this.profile),{width:1920,height:1080})))}applyProfile(){return Bb(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,n=this.settings,o=n.height!==this.profile.height||n.width!==this.profile.width||n.frameRate!==this.profile.frameRate;if(o&&(16===dM&&this.deviceId?yield this.recapture(this.deviceId):(yield null==(e=this.sourceTrack||this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),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){this.isNeedToSetBandwidth=!1;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),i=e*t;return o&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Hk.VIDEO,videoType:Hk.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return zL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:pN(this.settings,this.profile)}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 Bb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),MM.emit(LM.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(_D){throw this.log.error("switch camera failed ".concat(_D)),this.deviceId&&this.recapture(this.deviceId),_D}}))}getDeviceIdWhenUsingBackCamera(){return Bb(this,null,(function*(){let e;try{if(UO&&!KO&&XL){let t=(yield KV(!0)).map((e=>{var t;return Mb(Ob({},e),{capabilities:null==(t=e.getCapabilities)?void 0:t.call(e)})})).filter((e=>{var t,i;return null==(i=null==(t=e.capabilities)?void 0:t.facingMode)?void 0:i.includes("environment")})),i=t[0];t.forEach((e=>{var t,r,n,o;let{capabilities:s}=e;(null!=(t=s.width)&&t.max&&null!=(r=s.height)&&r.max?s.width.max*s.height.max:0)>(null!=(n=i.capabilities.width)&&n.max&&null!=(o=i.capabilities.height)&&o.max?i.capabilities.width.max*i.capabilities.height.max:0)&&(i=e)})),null!=i&&i.capabilities&&(this._log.info("use max resolution back camera",i),e=i.deviceId)}}catch(_D){this._log.warn("get max res camera failed",_D)}return e}))}updateSmallConfig(e){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),r&&(null==(i=this.room)||i.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=e.width>e.height,r=Ob({},e);return e.width*e.height<=19200&&zN&&QO&&(this.log.warn("".concat(t?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),r.width=i?240:180,r.height=i?180:240,r.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&pM&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),cM(aM,"14.3")&&lM(aM,"14.0",!0)&&this.on("7",(()=>{let e=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=e?640:480,this.profile.height=e?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=e?640:360,this.profile.height=e?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))})),!t&&this.avoidCropping&&(QO||ZN)&&!vM()&&e.width*e.height<=230400&&e.width/e.height==16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),r}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){GV&&!GV.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&GV.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return Bb(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(WB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){VH(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield KV();e[0]?this.recapture(e[0].deviceId):t=!0}t&&GV.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return Bb(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(GV.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}))}encodeFrame(e,t){if(!this.manager)return e;let i=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,mediaType:i}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return Dw(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){GV.off("videoInputAdded",this.handleCameraAdded,this),GV.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return Bb(this,null,(function*(){try{yield Fb(e.prototype,this,"recapture").call(this,t)}catch(_D){let r=(yield KV()).find((e=>e.deviceId!==t));if(!r)throw _D;yield Fb(e.prototype,this,"recapture").call(this,r.deviceId)}}))}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||Dw(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};Vb([hU((function(e){this.setContentHint(e.contentHint||"motion")}))],YB.prototype,"capture",1);var XB=YB,QB={};Lb(QB,{REPORT_TYPE:()=>gN,buildSSOPackage:()=>EN,bytes2ms:()=>Ew,calculateScaleResolutionDownNumber:()=>pN,concatArrayBuffers:()=>TN,convertObjectNumberToInt:()=>cN,copyProperties:()=>gw,deepClone:()=>Zw,deepCloneBasic:()=>fN,deepMerge:()=>Qw,delay:()=>lN,fibonacci:()=>Rw,formatedTime:()=>tN,getConstructorName:()=>Fw,getContainerFromElement:()=>eN,getEnv:()=>lw,getFirst16Bits:()=>yN,getInternalVersion:()=>Jw,getLast16Bits:()=>vN,getLoggerUrl:()=>uw,getMediaStreamTrackInfo:()=>hN,getMuteStateFromFlag:()=>zw,getNetworkType:()=>pw,getNumNetworkType:()=>fw,getReconnectionTimeout:()=>Cw,getStringByteLength:()=>nN,getTurnServer:()=>Yw,getUint32Version:()=>aN,getValueType:()=>bw,getViewListFromView:()=>$w,glog:()=>Sw,ipv4ToUint32:()=>Xw,isArray:()=>Pw,isAudioWorkletSupported:()=>Bw,isBoolean:()=>Ow,isConstructor:()=>Uw,isEmpty:()=>Kw,isFunction:()=>kw,isLangChinese:()=>Iw,isMediaStreamTrack:()=>Lw,isNumber:()=>Nw,isObject:()=>Mw,isOverseaSdkAppId:()=>dw,isPlainObject:()=>Aw,isPortrait:()=>oN,isPromise:()=>Vw,isRemoteTrack:()=>xw,isRotate90Or270:()=>mN,isSetSinkIdSupported:()=>Hw,isString:()=>ww,isUndefined:()=>Dw,loadImage:()=>sN,loadVideo:()=>_N,ms2bytes:()=>vw,ms2samples:()=>yw,normalizeUrl:()=>uN,performanceNow:()=>Gw,promiseAny:()=>Ww,samples2ms:()=>Tw,setNetworkType:()=>_w,stringify:()=>iN,stringifyIncludeValue:()=>rN,throttlePromise:()=>dN});var ZB=[-1,-1,1,-1,-1,1,1,1],$B=[0,0,1,0,0,1,1,1],eH=class e extends Cx{constructor(e,t){if(super(),this.context=e,Ub(this,"name"),Ub(this,"input"),Ub(this,"output"),Ub(this,"texture"),Ub(this,"ctx2d",null),Ub(this,"fbo"),Ub(this,"width",0),Ub(this,"height",0),Ub(this,"x",0),Ub(this,"y",0),Ub(this,"program"),Ub(this,"vertexShader"),Ub(this,"fragmentShader"),Ub(this,"totalFrames",0),Ub(this,"dropFrames",0),Ub(this,"matchInputSize",!0),Ub(this,"texCoordBuffer"),Ub(this,"positionBuffer"),Ub(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Ub(this,"cost",0),Ub(this,"_canvas",null),Ub(this,"_image"),Ub(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof fH)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==dM?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer($B),this.positionBuffer=this.createBuffer(ZB),!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.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(zM){this.context.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(zM.message||zM)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];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 _H&&this.render(e)||this.context instanceof fH&&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)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];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 _H){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),r=0;r<t;r++)i[r]=arguments[r];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),r=0;r<t;r++)i[r]=arguments[r];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(t,i,r,n,o,s,a,c,l){let d=!(Dw(s)||Dw(a)||Dw(c)||Dw(l));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,s,a,c,l):this.ctx2d.putImageData(t,i,r),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,s,a,c,l,i,r,n,o):this.ctx2d.drawImage(t,i,r,n,o),this.emit(e.RENDER,t)),"undefined"!=typeof VideoFrame&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,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:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},Ob({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.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};Ub(eH,"RENDER","render"),Vb([Ix(Cx.INIT,"connected",{sync:!0})],eH.prototype,"connect",1),Vb([Ix("connected",Cx.INIT,{ignoreError:!0,sync:!0})],eH.prototype,"disconnect",1),Vb([Ix([],"closed",{sync:!0})],eH.prototype,"close",1);var tH=eH,iH=LU(uF(250),cB((()=>performance.now())),GU()),rH=[0,1,1,1,0,0,1,0],nH=class extends tH{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),Ub(this,"_intervalId",0),Ub(this,"_sequence",0),Ub(this,"checkGLError",!1),Ub(this,"checkVisibilityChange"),e instanceof fH?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(rH)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),Ox.clearTask(this._intervalId),this._intervalId=Ox.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(Ox.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof _H){let e=this.context.ctx.getError();e&&this.context.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:5,message:"".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(),this.emit(tH.RENDER,this.context._canvas),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;"closed"!==this.state&&(this._intervalId&&(Ox.clearTask(this._intervalId),this._intervalId=0,1===e&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),Ox.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),Ox.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},oH=class extends nH{constructor(e,t){super(e,t),Ub(this,"_videoTrack"),Ub(this,"_muteOb"),Ub(this,"_closedOb",_F(this,"closed")),Ub(this,"_subscription"),Ub(this,"_canvasContainer"),Number(oM)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=_F(this._videoTrack,"mute"),LU(_F(this._videoTrack,"ended"),VF(this._closedOb),UB((()=>{this.context.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){var e;this._subscription=LU(this._muteOb,VF(this._closedOb),fB((e=5e3,t=>{let i=performance.now();LU(iH,WF((t=>t-i<e)),xF(1))(t)})),PF((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),UB((()=>{this.context.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},sH=class extends oH{render(e){var t;let i=!(null==(t=this.input)||!t.requestFrame(e));if(this.context._canvas2d){let e=this.context._canvas2d.getContext("2d");e.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),e.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return i}},aH=class extends oH{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.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=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},cH=class extends tH{constructor(e,t){super(e,Ob({name:"imageSource"},t)),Ub(this,"_lastImage"),Ub(this,"_totalFrames",0),Ub(this,"_autoResize",!1),Ub(this,"_canvasRendered"),Ub(this,"videoCallbackId",0),Ub(this,"waitingFirstFrame",!0),Ub(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===dM&&(this._canvasRendered=iF(),LU(this._canvasRendered,QU(this._image),mB((e=>e instanceof HTMLCanvasElement?_F(e,"rendered"):bF())),VF(_F(this,"closed")),UB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),lx()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:n}=this,{image:o}=this;if(o instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:n}=o),!r||!n)return!1;o.width=r,o.height=n}else if(o instanceof HTMLImageElement||o instanceof ImageData||o instanceof ImageBitmap){if(({width:r,height:n}=o),o!==this._lastImage)this._lastImage=o;else if(r===this.width&&n===this.height)return!0}else o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?(({width:r,height:n}=o),this._lastImage=o):"undefined"!=typeof VideoFrame&&o instanceof VideoFrame&&(({displayWidth:r,displayHeight:n}=o),null==(i=this._lastImage)||i.close(),this._lastImage=o);if(!this._autoResize)return!0;if(this.width===r&&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,o)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)}this.resize(r,n)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},lH=class extends cH{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",LU(_F(this._player,Mx.PLAYER_STATE_CHANGED),VF(_F(this,"closed")),PF((e=>{let{state:t}=e;return"PLAYING"===t})),UB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},dH=class extends lH{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new hV({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},uH=class extends tH{constructor(e,t,i){super(e,Mb(Ob({name:"textSource"},i),{create2d:!0})),Ub(this,"hasChange",!0),Ub(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return(null==(e=this.ctx2d)?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return(null==(e=this.ctx2d)?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:i,font:r}=this;super.resize(e,t),this.color=i,this.font=r}drawMultilineText(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1.2;if(!this.ctx2d)return;let r=this.ctx2d.measureText(this.content);t+=r.fontBoundingBoxAscent||r.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),o=(n?parseInt(n[1],10):16)*i,s=this.content.split("\n");for(let a=0;a<s.length;a++)this.ctx2d.fillText(s[a],e,t+a*o)}},hH=class extends Cx{constructor(e){super(),Ub(this,"frameRate"),Ub(this,"_canvas"),Ub(this,"log"),Ub(this,"hasAlpha",!1),Ub(this,"name"),Ub(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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,t){return new dH(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new oH(this,e)}createVideoImageSource(e,t){return new cH(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new lH(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new uH(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};Ub(hH,"_ids",0);var pH={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},mH=class extends hH{constructor(){super(...arguments),Ub(this,"defaultProgam"),Ub(this,"defaultVShader"),Ub(this,"defaultFShader"),Ub(this,"ctx"),Ub(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(hH._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",pH),!this.ctx)throw new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:2,message:"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 ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,lL.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};Ub(mH,"UNAVAILABLE","unavailable"),Vb([Ix(Cx.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),lL.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),lL.addSuccessEvent({key:512700})}})],mH.prototype,"create",1),Vb([Ix("created",Cx.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(mH.UNAVAILABLE,e),this.removeAllListeners()}})],mH.prototype,"destroy",1);var _H=mH,fH=class extends hH{constructor(){super(...arguments),Ub(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(hH._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",(()=>{this.log.error("2d context lost")})),this._canvas.addEventListener("contextrestored",(()=>{this.log.warn("2d context restored")}))}destroy(e){let t="";e&&(t=e.message,this.error=e,lL.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),lL.addSuccessEvent({key:512703})}};function gH(e,t,i,r,n){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let o={sWidth:e,sHeight:t,dWidth:i,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(0===e||0===t)return o;switch(n){case void 0:case"fill":break;case"contain":{let n=Math.min(i/e,r/t);o.dWidth=e*n,o.dHeight=t*n,o.dx=(i-o.dWidth)/2,o.dy=(r-o.dHeight)/2;break}case"cover":{let n=Math.max(i/e,r/t),s=i/n,a=r/n;o.sx=(e-s)/2,o.sy=(t-a)/2,o.sWidth=s,o.sHeight=a;break}}return o}Vb([Ix(Cx.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),lL.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),lL.addSuccessEvent({key:512701})}})],fH.prototype,"create",1),Vb([Ix("created",Cx.INIT,{ignoreError:!0,sync:!0})],fH.prototype,"destroy",1);var EH=class{constructor(e,t){this.node=e,this.layout=t,Ub(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}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},TH=class extends tH{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Ub(this,"inputs",[]),Ub(this,"backgroundColor","black")}addInput(e,t){let i=0,r=this.inputs.length;for(;i<r;){let e=Math.floor((i+r)/2);if(this.inputs[e].layout.zIndex<t.zIndex)i=e+1;else{if(!(this.inputs[e].layout.zIndex>t.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));r=e}}let n=new EH(e,t);this.inputs.splice(i,0,n)}changeInputLayout(e,t){let i=this.inputs.findIndex((t=>t.node===e));if(i<0)return;let{x:r,y:n,width:o,height:s,zIndex:a,fillMode:c,rotation:l,hidden:d}=t;if(!Dw(a)&&this.inputs.some((t=>t.layout.zIndex===a&&t.node!==e)))throw new Error("input already exists at zIndex ".concat(t.zIndex));let u=this.inputs[i];Dw(r)||(u.layout.x=r),Dw(n)||(u.layout.y=n),Dw(o)||(u.layout.width=o),Dw(s)||(u.layout.height=s),Dw(l)||(u.layout.rotation=l),Dw(d)||(u.layout.hidden=d),c&&(u.layout.fillMode=c),!Dw(a)&&a!==u.layout.zIndex&&(u.layout.zIndex=a,this.inputs.sort(((e,t)=>e.layout.zIndex-t.layout.zIndex)))}hasInput(e){return this.inputs.some((t=>t.node===e))}hasNoInput(){return 0===this.inputs.length}resize(e,t){if(!this.matchInputSize)return void super.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 _H&&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),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter((t=>t.node!==e)),0===this.inputs.length&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce(((t,i)=>i.node.requestFrame(e)||t),!1)&&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.forEach((t=>t.node.requestFrame(e))),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];if(t.hidden)continue;let i=gH(t.node.width,t.node.height,t.width,t.height,t.fillMode,mN(t.rotation));this.draw2d(t.node.image,t.x+i.dx,t.y+i.dy,i.dWidth,i.dHeight,i.sx,i.sy,i.sWidth,i.sHeight)}return!0}return!1}debugLayout(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(n&&([i,r]=[r,i]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,i,r),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,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:r,height:n,timestamp:s,fps:a,name:o},Ob({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}removeAllInputs(){this.inputs.forEach((e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof _H)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(zM){}}))}close(){super.close(),this.removeAllInputs()}},vH=[1,0,0,0,1,1,0,1],yH=class extends tH{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),Ub(this,"mirror",!1),Ub(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof _H)try{this.setTexBuffer(vH)}catch(mk){e.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(mk.message||mk)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),90===this.rotation?(this.ctx2d.translate(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/r,r/n)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/r,r/n));let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(e,t){mN(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},SH=class extends jB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,hV),Ub(this,"inputLocalVideoTracks",new Map),Ub(this,"inputLocalScreenTracks",new Map),Ub(this,"cameraNodeMap",new Map),Ub(this,"screenNodeMap",new Map),Ub(this,"textNodeMap",new Map),Ub(this,"imageNodeMap",new Map),Ub(this,"videoNodeMap",new Map),Ub(this,"endedIds",new Set),Ub(this,"videoContext"),Ub(this,"mixNode"),Ub(this,"destination"),Ub(this,"manager"),Ub(this,"stat"),Ub(this,"_checkId",0),Ub(this,"autoSetFps",!0),this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tH.RENDER,(e=>{this.emit("render",e)})),this.mixNode=new TH(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=Ox.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new fH({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout((()=>{var e;return null==(e=this.destination)?void 0:e.start(this.videoContext.frameRate)}),500)}setFpsAuto(){var e;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let t=null,i=0,r=!0;for(let[n,o]of this.inputLocalVideoTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.cameraNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n}for(let[n,o]of this.inputLocalScreenTracks)if(o.profile.frameRate>i){if(this.endedIds.has(n)){let e=this.screenNodeMap.get(n);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=o.profile.frameRate,t=n,r=!1}if(null!==t){let e=r?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);e&&(e.shouldUpdate=!0,e.tryVideoFrameCallback()),this.log.info("set mix fps: ",i)}else null==(e=this.destination)||e.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var i;null==(i=this.mixNode)||i.resize(e,t)}startMix(){return Bb(this,null,(function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),nM&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),null==(e=this.manager)||e.changeInput(this)}))}addCameraSource(e,t,i){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error("There is already a cameraSource with the same ID: ".concat(e));let r,{mediaTrack:n}=t;if(!n)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,xx(this,GV).add("videoInputRemoved",(i=>{i.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())})),t.on("output-media-track-changed",(()=>{this.endedIds.delete(e),this.updateCameraSource(e,i,t.mediaTrack)})),r=16===dM&&n instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(n.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(n,"cameraNodeSource"),r.resize(t.settings.width,t.settings.height),r.shouldUpdate=!1,this._connectMix(r,i,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,r),this.setFpsAuto()}addScreenSource(e,t,i){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error("There is already a screenSource with the same ID: ".concat(e));let{mediaTrack:r}=t;if(!r)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(r,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,color:n,layout:o}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let s=this.videoContext.createTextSource({content:i,font:r,color:n});s.resize(o.width,o.height),this._connectMix(s,o),this.textNodeMap.set(t,s)}addImageSource(e,t,i){if(this.imageNodeMap.has(e))throw new Error("There is already a imageSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.width,t.height),this._connectMix(r,i),this.imageNodeMap.set(e,r)}addVideoSource(e,t,i){if(this.videoNodeMap.has(e))throw new Error("There is already a videoSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.videoWidth,t.videoHeight),r.shouldUpdate=!1,this._connectMix(r,i),this.videoNodeMap.set(e,r)}updateCameraSource(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3?arguments[3]:void 0,n=this.cameraNodeMap.get(e);if(n){if(i){if(16===dM&&i instanceof CanvasCaptureMediaStreamTrack)if(n instanceof dH){let t=n.output;n.close(),n=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(t),this.cameraNodeMap.set(e,n)}else n.image=i.canvas;else if(n instanceof dH)n.replaceTrack(i);else{let t=n.output;n.close(),n=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),n.connect(t),this.cameraNodeMap.set(e,n)}let{width:t,height:r}=i.getSettings();t&&r&&n.resize(t,r)}r&&n.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let i=this.screenNodeMap.get(e);i&&this._changeMixLayout(i,t)}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:o}=e,s=this.textNodeMap.get(t);s&&(Dw(i)||(s.content=i),Dw(r)||(s.font=r),Dw(n)||(s.color=n),s.resize(o.width,o.height),this._changeMixLayout(s,o))}updateImageSource(e,t,i){let r=this.imageNodeMap.get(e);r&&(i&&(r.image=i,r.resize(i.width,i.height)),this._changeMixLayout(r,t))}updateVideoSource(e,t,i){let r=this.videoNodeMap.get(e);if(r){if(i){let e=r.image;e instanceof HTMLVideoElement&&this.stopVideoElement(e),r.image=i,r.resize(i.videoWidth,i.videoHeight)}this._changeMixLayout(r,t)}}_connectMix(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:r,rotation:n}=t;e.disconnect();let o=new yH(this.videoContext,this.log,r,n);o=e.connect(o),t.fillMode||(t.fillMode=i),o.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,n=e.output||e;n instanceof yH&&(Dw(i)||(n.mirror=i),Dw(r)||(n.rotation=r),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let i=this.cameraNodeMap.get(e);i&&(i.output instanceof yH&&i.output.close(),i.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let i=this.screenNodeMap.get(e);i&&(i.output instanceof yH&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof yH&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof yH&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof yH&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),Ox.clearTask(this._checkId),null==(e=this.videoContext)||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Vx(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},IH=FM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:IH,exposeOrigin:!0,permittedOrigins:["*"]})}catch(dq){}var AH=function(e){return Bb(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:rM?{max:e.width}:{ideal:e.width,max:e.width},height:rM?{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:r=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:n,sampleRate:48e3}}return t}(e);UM.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(ZO&&eM<74||rM||ZN)&&UM.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(QM){UM.warn("screen applyConstraints failed: ".concat(QM))}e.captureElement&&(yield function(e,t){return Bb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&kw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==IH)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){UM.warn("cropTo target failed ".concat(r))}}))}(n,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 Dw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);UM.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},RH=class extends XB{constructor(e){super(e,2),Ub(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Ub(this,"objectFit","contain"),Ub(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return IH===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(zM){return}}capture(e){return Bb(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,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 AH({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),t.sourceTrack=e.getVideoTracks()[0]),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof ek?e:new ek({code:Zb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return Bb(this,null,(function*(){throw new Error("Method not implemented.")}))}};Vb([hU((function(e){this.setContentHint(e.contentHint||"detail")}))],RH.prototype,"capture",1);var CH,bH=class extends qB{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}addAudioProcessor(e,t,i){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function kH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3?arguments[3]:void 0;return Bb(this,null,(function*(){let n=bV();CH||(CH=pV(n,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),yield CH;let o=n.sampleRate,s=new AudioWorkletNode(n,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:t}});return s.channelCountMode="explicit",s.channelCount=i,r&&s.port.postMessage({port:r},[r]),e.forEach(((e,t)=>e.connect(s,0,t))),new ReadableStream({start(e){s.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(s))),s.port.close()}})}))}var DH=class extends OV{constructor(e){super(),this.room=e,Ub(this,"_localAudioTrack"),Ub(this,"_localScreenAudioTrack"),Ub(this,"log",UM.createLogger({id:"am"})),Ub(this,"denoiser"),Ub(this,"voiceChanger"),Ub(this,"mixChangedDebounce"),Ub(this,"audioProcessor"),Ub(this,"encodePipeline",[]),Ub(this,"decodePipeline",[]),Ub(this,"getPCMAbortCtrlMap",new Map),Ub(this,"audioFrameEventConfigMap",new Map),Ub(this,"audioReferenceMap",new Map),Ub(this,"isLocalAudioNeedAudioProcess",!1),Ub(this,"isScreenAudioNeedAudioProcess",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return null==(e=this._localScreenAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", 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<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=kH(r).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}}getPCM(e,t){var i,r,n;if("undefined"==typeof WritableStream)return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:o,sampleRate:s=48e3,channelCount:a=1,port:c}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info("getPCM ".concat(t||"local"));let l,d,u=Math.floor(.04*s),h=new Float32Array(u),p=new Float32Array(u),m=0,_=new AbortController,f=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(n=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:n.remoteAudioTrack.mediaTrack;if(f)return kH([bV().createMediaStreamSource(new MediaStream([f]))],s,a,c).then((i=>i.pipeTo(new WritableStream({write(i){i[0][0]&&(m+i[0][0].length>u?(h.set(i[0][0].subarray(0,u-m),m),l=i[0][0].subarray(u-m),i[0][1]&&(p.set(i[0][1].subarray(0,u-m),m),d=i[0][1].subarray(u-m)),m+=u-m):(l&&(h.set(l,m),m+=l.length,l=void 0),d&&(p.set(d,m),d=void 0),h.set(i[0][0],m),i[0][1]&&p.set(i[0][1],m),m+=i[0][0].length),m>=u&&(m=0,e({userId:t,sampleRate:s,channelCount:a,data:1===a?h:[h,p]}),h=new Float32Array(u),p=new Float32Array(u)))}}),_).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),_;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!Dw(this._localScreenAudioTrack)}get hasAudioTrack(){return!Dw(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof bH?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&null!=(t=this.audioProcessor)&&t.screenAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof qB?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&null!=(i=this.audioProcessor)&&i.localAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach(((t,i)=>{e.mixAudioReference(t,i)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof MH?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixAudioReference(e,t){var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}unMixAudioReference(e){var t;null==(t=this._localAudioTrack)||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var i;null==(i=this._localAudioTrack)||i.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([null==(e=this._localAudioTrack)?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}removeInput(e){e instanceof bH?delete this._localScreenAudioTrack:e instanceof qB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var n;this.audioProcessor={localAudioWorkletNode:i,mixNode:e,silentNode:t,screenAudioWorkletNode:r},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&i&&(this._localAudioTrack.addAudioProcessor(i,e,t),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localAudioTrack)||i.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&r&&(null==(n=this._localScreenAudioTrack)||n.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach(((e,t)=>{var i;null==(i=this._localScreenAudioTrack)||i.mixAudioReference(e,t)})))}removeDenoiser(e){var t;return delete this.denoiser,null==(t=this._localAudioTrack)?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],null==(i=this._localAudioTrack)||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var i,r;delete this.audioProcessor,null==(i=this._localAudioTrack)||i.removeAudioProcessor(e),null==(r=this._localScreenAudioTrack)||r.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach((e=>null==e?void 0:e.abort("destroy"))),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}handleLocalTrackStarted(e){let{room:t,userId:i}=e;var r;if(t!==this.room||this.getPCMAbortCtrlMap.get(i))return;let n=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,n),this.getPCMAbortCtrlMap.get(i)&&(null==(r=this._localAudioTrack)||r.on("input-media-track-changed",(()=>{let e=this.getPCMAbortCtrlMap.get(i);e&&(e.abort("inputMediaTrackChanged"),e=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),""),this.getPCMAbortCtrlMap.set(i,e))})))}handleLocalTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(i))}handleRemoteTrackStarted(e){let{room:t,userId:i}=e;if(t===this.room&&!this.getPCMAbortCtrlMap.get(i)){let e=this.room.audioManager.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),i);this.getPCMAbortCtrlMap.set(i,e)}}handleRemoteTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(i))}installEvent(){MM.on("113",this.handleLocalTrackStarted,this),MM.on("114",this.handleLocalTrackStopped,this),MM.on("115",this.handleRemoteTrackStarted,this),MM.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){MM.off("113",this.handleLocalTrackStarted),MM.off("114",this.handleLocalTrackStopped),MM.off("115",this.handleRemoteTrackStarted),MM.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:n}=e;if("add"===t){if(this.audioReferenceMap.get(r)||!i||(this.audioReferenceMap.set(r,i),!this.audioProcessor))return;this.mixAudioReference(i,r)}else if("remove"===t)this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if("updateVolume"===t){if(!this.audioProcessor||Dw(n))return;this.setAudioReferenceVolume(r,n)}}};function wH(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return mU(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new ek({code:Zb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||UM).warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var NH=class e extends rU{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,Ub(this,"tinyId"),Ub(this,"isRemote",!0),Ub(this,"jitterBufferDelay",0),Ub(this,"availableState"),Ub(this,"remotePublishState"),Ub(this,"_triggerCheckDecodeSubject",iF(_F(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new Cx("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new Cx("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),LU(jU(_F(this,Cx.STATECHANGED),_F(this.remotePublishState,Cx.STATECHANGED)),cB((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),UB((e=>{this.availableState.state!==(e?Cx.ON:Cx.OFF)&&(this.availableState.state=e?Cx.ON:Cx.OFF),this.updatePlayingState(e)})));let n=LU(_F(this.player,Mx.ERROR),PF((e=>e.code===MediaError.MEDIA_ERR_DECODE))),o=LU(hF(5e3),PF((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===Hk.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),s=LU(JU(n,o),VF(_F(this,Cx.INIT)));LU(this._triggerCheckDecodeSubject,PF((()=>!this.ignoreDecodeError)),fB(s),UB((e=>{this.reportDecodeResult(!1,e)})))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get ignoreDecodeError(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Cx.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var i,r;let n=this.kind===Hk.AUDIO;if(lL[e?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),!n){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";lL[e?"addSuccessEvent":"addFailedEvent"]({key:sL["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(lL.addEnum({key:n?504701:514703,value:kM()}),Ux.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(AM()||wM()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Hk.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Cx.ON:Cx.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Ub(NH,"STATE_SUBSCRIBE","subscribe"),Vb([wH(5,1)],NH.prototype,"waitHasMediaTrack",1),Vb([Ix(Cx.INIT,NH.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),MM.emit(LM.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),IU(521716,!1)],NH.prototype,"subscribe",1),Vb([Ix(NH.STATE_SUBSCRIBE,Cx.INIT,{sync:!0,success(){this.log.info("unsubscribed"),MM.emit(LM.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],NH.prototype,"unsubscribe",1);var OH=NH,MH=class extends OH{constructor(e,t){super(e,t,1),Ub(this,"volume",0),Ub(this,"mediaType",1),Ub(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return UV.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return!!this.manager&&(this.manager.decodePipeline.some((e=>e))||(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&tx().AudioDecoder&&QL)}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let n={frame:e,track:this};if(1===i&&this.isAvailable&&"audience"===this.room.role&&(n.onAudioFrameNTPTime=e=>{let{ntp:t,frame:i,hasLeavingTag:r}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:i,hasLeavingTag:r})}),t=r(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var PH=class extends OH{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),Ub(this,"mediaType",4),Ub(this,"source"),Ub(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager,this.once("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}play(e,t){return(Ow(null==t?void 0:t.canvasRender)?t.canvasRender:17===dM)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat(),MM.emit("156",{track:this,player:this.player})}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new fH({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new nH(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),lx()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)));var r;!Nw(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},i=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let r=t.find((e=>e.uint32_video_stream_type===i));return(null==r?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),MM.emit("157",{track:this,player:this.player}),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},LH=class extends PH{constructor(e,t){super(e,t,2),Ub(this,"mediaType",2),Ub(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},xH=new Map;function VH(e,t){let i=Mb(Ob({},t),{timestamp:ok()});xH.has(e)?xH.get(e).push(i):xH.set(e,[i])}function UH(e,t,i,r){try{if(Pw(e))for(let n=0;n<e.length;n++)FH.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else FH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(zM){throw UM.error(zM),zM}}function FH(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;if(Dw(i)){if(t.required)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(Dw(t.defaultValue))return;i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),kw(t.type[r])&&i instanceof t.type[r]&&(e=!0),ww(t.type[r])&&bw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>Uw(e)?Fw(e):ww(e)?e:bw(e)))},fnName:n,value:i},link:{className:o,fnName:n}})})}else if(!Dw(t.type)&&bw(i)!==t.type)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!1===t.allowEmpty){let e=Nw(i)&&(0===i||Number.isNaN(i)),s=ww(i)&&""===i.trim();if(e||s)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}if(t.notLessThanZero&&Nw(i)&&i<0)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!Dw(t.min)&&Nw(i)&&i<t.min)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(!Dw(t.max)&&Nw(i)&&i>t.max)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(ww(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})})}else if(kw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});if(t.values&&!t.values.includes(i))throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:o,fnName:n}})});let{properties:s}=t;Aw(s)&&Mw(i)&&Object.keys(s).forEach((e=>{FH.call(this,{rule:s[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:n,className:o})}));let{arrayItem:a}=t;Aw(a)&&Pw(i)&&i.forEach(((e,t)=>{FH.call(this,{rule:a,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),kw(t.validate)&&t.validate.call(this,i,r,n,o,this)}MM.on(LM.JOIN_SUCCESS,(e=>{let{room:t}=e;VH(t.userId,{eventId:32788})})),MM.on(LM.LEAVE_START,(e=>{let{room:t}=e;VH(t.userId,{eventId:32789})})),MM.on(LM.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),VH(t.room.userId,{eventId:e})}})),MM.on(LM.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),VH(t.room.userId,{eventId:e})}})),MM.on(LM.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Hk.AUDIO?VH(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):VH(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),MM.on(LM.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Hk.AUDIO?VH(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):VH(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),MM.on(LM.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&VH(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&VH(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&VH(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),MM.on(LM.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&VH(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&VH(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&VH(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),MM.on(LM.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&VH(t.room.userId,{eventId:t.kind===Hk.VIDEO?32780:32781})})),MM.on(LM.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&VH(t.room.userId,{eventId:t.kind===Hk.VIDEO?32782:32783})})),MM.on(LM.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&VH(i.userId,{eventId:t})})),MM.on(LM.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&VH(i.userId,{eventId:t,remoteUserId:o})})),MM.on(LM.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:o,prevImplementation:s,streamType:a}=e,c=o?1:0;s||(c=o?3:2);let l={H264:0,H265:1,VP8:2}[n.toUpperCase()],d={eventId:4004,param1:c,param2:l,streamType:a||2};r&&(d.remoteUserId=r,d.eventId=4005),VH(i,d),lL.addEnum({key:r?514701:513701,value:c}),lL.addEnum({key:r?514700:513700,value:l})})),MM.on(LM.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Hk.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),VH(t.userId,e)}}));var BH=xb(Hb(),1),HH=class extends BH.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,Ub(this,"userMap",new Map),Ub(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");Dw(t)||(r+=":".concat(UD[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.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 void this.emit("7",e);let{flag:r,userId:n,tinyId:o}=e,s=zw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:zw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function WH(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return mU(((e,n)=>{let o=new WeakMap;return MM.on(LM.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),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var GH,jH=!0,JH={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",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},qH={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},KH=((GH=KH||{})[GH.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",GH[GH.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",GH[GH.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",GH[GH.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",GH[GH.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",GH[GH.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",GH[GH.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",GH[GH.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",GH[GH.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",GH[GH.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",GH[GH.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",GH[GH.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",GH[GH.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",GH[GH.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",GH[GH.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",GH[GH.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",GH[GH.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",GH[GH.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",GH[GH.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",GH[GH.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",GH[GH.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",GH[GH.INVALID_OPERATION=5100]="INVALID_OPERATION",GH[GH.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",GH[GH.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",GH[GH.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",GH[GH.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",GH[GH.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",GH[GH.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",GH[GH.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",GH[GH.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",GH[GH.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",GH[GH.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",GH[GH.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",GH[GH.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",GH[GH.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",GH[GH.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",GH[GH.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",GH[GH.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",GH[GH.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",GH[GH.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",GH[GH.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",GH[GH.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",GH[GH.DEVICE_ERROR=5300]="DEVICE_ERROR",GH[GH.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",GH[GH.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",GH[GH.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",GH[GH.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",GH[GH.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",GH[GH.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",GH[GH.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",GH[GH.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",GH[GH.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",GH[GH.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",GH[GH.SERVER_ERROR=5400]="SERVER_ERROR",GH[GH.NEED_TO_BUY=5401]="NEED_TO_BUY",GH[GH.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",GH[GH.OPERATION_FAILED=5500]="OPERATION_FAILED",GH[GH.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",GH[GH.REJOIN_FAILED=5502]="REJOIN_FAILED",GH[GH.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",GH[GH.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",GH[GH.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",GH[GH.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",GH[GH.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",GH[GH.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",GH[GH.OPERATION_ABORT=5998]="OPERATION_ABORT",GH[GH.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",GH);var zH=Mb(Ob({},YP),{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:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=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(r,"(), received type: ").concat(bw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(bw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,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,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},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:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},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_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(e){let{key:t}=e;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat("strRoomId"===t?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(e){let{key:t}=e;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},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 or screen share is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},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=YH(t),error:r}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=YH(t),error:r}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=YH(t),error:r}=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=YH(t),error:r}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=YH(t),error:r}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=YH(t),error:r}=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(r?", error: ".concat(r.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=YH(t),error:r}=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(r?" error: ".concat(r.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 YH(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var XH=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s,data:a}=e;var c;let l;l=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=KH[i];try{t=zH[a]}catch(o){t=zH.UNKNOWN_ERROR}return kw(t)?s=t(r):ww(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===qH.SERVER_ERROR?t:i||t,params:Ob({fnName:o,error:s},n)}),super(l),Ub(this,"name","RtcError"),Ub(this,"code"),Ub(this,"extraCode"),Ub(this,"functionName"),Ub(this,"message"),Ub(this,"data"),Ub(this,"handler"),Ub(this,"originError"),this.name=KH[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=l,this.data=a,5302===this.extraCode&&null!=(c=this.originError)&&c.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");kO?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):DO&&(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(t,i,r){let n=t;if(t instanceof ek){let{stack:o}=t,s={code:qH.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case Zb.INVALID_PARAMETER:s.code=qH.INVALID_PARAMETER,s.message=t.message;break;case Zb.INVALID_OPERATION:s.code=qH.INVALID_OPERATION;break;case Zb.NOT_SUPPORTED:case Zb.NOT_SUPPORTED_H264:s.code=qH.ENV_NOT_SUPPORTED,t.getCode()===Zb.NOT_SUPPORTED_H264&&(s.extraCode=t.message.includes(YP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Zb.JOIN_ROOM_FAILED:s.messageParams={fnParams:r};case Zb.SERVER_TIMEOUT:case Zb.SWITCH_ROLE_FAILED:case Zb.SWITCH_ROOM_FAILED:s.code=qH.SERVER_ERROR,s.extraCode=t.getExtraCode();break;case Zb.API_CALL_ABORTED:s.code=qH.OPERATION_ABORT;break;case Zb.DEVICE_NOT_FOUND:case Zb.DEVICE_AUTO_RECOVER_FAILED:case Zb.INITIALIZE_FAILED:s.code=5300,t.name&&(s.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}(t.name));break;case Zb.VIDEO_ENCODE_FAILED:s.extraCode=5505;case Zb.AUDIO_ENCODE_FAILED:s.extraCode=5506,s.code=qH.OPERATION_FAILED;break;case Zb.UNKNOWN:break;default:s.code=qH.OPERATION_FAILED}n=new e(s),o&&(n.stack+=o.substr(o.indexOf("\n")))}else{if(t instanceof e)return t;n=new e({code:qH.UNKNOWN_ERROR,fnName:i,originError:t})}return n}};var QH=XH;function ZH(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function $H(e){return e===JH.QOS_PREFERENCE_CLEAR?"detail":e===JH.QOS_PREFERENCE_SMOOTH?"motion":""}function eW(e,t){let i=t?Fk:Uk;return MN(e)?Ob(Ob({},i),e):Vk[e]?Vk[e]:i}var tW={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:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},iW={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}}},rW={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(ww(e)&&!document.getElementById(e))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},nW={name:"userId",required:!0,type:"string"},oW={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function sW(e,t){if(!e)throw new QH({code:qH.INVALID_OPERATION,extraCode:5101,fnName:t})}function aW(e,t,i){if(!e)throw new QH({code:qH.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function cW(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function lW(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function dW(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!xL())return UM.warn("small stream is not supported"),void delete e.option.small;let i=eW(e.option.profile),r=eW(e.option.small,!0);return((e,t)=>e.width*e.height>=t.width*t.height&&e.frameRate>=t.frameRate&&e.bitrate>=t.bitrate)(i,r)?void 0:(UM.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(i),", Small: ").concat(JSON.stringify(r))),void delete e.option.small)}var uW={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 QH({code:qH.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(ww(e.roomId))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});cW(e.roomId,i,t)}else{if(!e.strRoomId)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5015,fnName:i});lW(e.strRoomId,i,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"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:rW,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:tW},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&gL())throw new QH({code:qH.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&dW(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Mb(Ob({},rW),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:tW},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&dW(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:oW},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&gL())throw new QH({code:qH.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:oW}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:rW,publish:{type:"boolean"},option:iW},validate(e,t,i,r,n){var o;if(null==(o=null==e?void 0:e.option)||!o.videoTrack){if(gL())throw new QH({code:qH.ENV_NOT_SUPPORTED,extraCode:5201});if(!AL())throw new QH({code:qH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:rW,publish:{type:"boolean"},option:iW}},muteRemoteAudio:[nW,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[nW,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:rW,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){sW(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(aW(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new QH({code:qH.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Mb(Ob({},rW),{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){sW(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(aW(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new QH({code:qH.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&&Dw(e.streamType))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){sW(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,r){if(!$L)throw new QH({code:qH.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new QH({code:qH.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});sW(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new QH({code:qH.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(sW(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new QH({code:qH.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(sW(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new QH({code:qH.INVALID_PARAMETER,extraCode:5020,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)cW(e.roomId,i,t);else{if(!e.strRoomId)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5015,fnName:i});lW(e.strRoomId,i,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},hW={TRTC:uW},pW=class extends Error{};function mW(e,t){let i=Zw(e);for(let r=0;r<t.length;r++)Qw(i[r],t[r]);return i}function _W(e){this._resolve=Promise.resolve(e)}function fW(e){this._reject=Promise.reject(e)}var gW=class e{constructor(t,i){this.instance=t,this.group=i,Ub(this,"started",!1),Ub(this,"ops",[]),Ub(this,"startSame",(()=>!0)),Ub(this,"mergeUpdate",mW);let r=e.instances.get(t);r?r.set(i,this):e.instances.set(t,new Map([[i,this]]))}static get(t,i){if(!i)return;let r=e.instances.get(t);return r&&r.get(i)||new e(t,i)}static gets(t,i){let r=e.instances.get(t),n=[];return r&&r.forEach(((e,t)=>{i.test(t)&&n.push(e)})),n}action(e,t,i){let r=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},n=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new pW("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:_W,reject:fW};try{switch(this.state){case 1:if(0===e)throw new pW("already started");break;case 4:if(2===e)throw new pW("not started");break;default:return this.cacheOp(o)}}catch(KM){return Promise.reject(KM)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new pW("already start");break;case 3:switch(e.type){case 2:throw new pW("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new pW("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new pW("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 pW("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new pW("start not allowed after update");case 0:throw new pW("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new pW("keep start")),new pW("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}};Ub(gW,"instances",new WeakMap);var EW=gW,TW=new WeakMap,vW=(e,t)=>{if(t instanceof pW){let{stack:i}=t;t=new QH({code:qH.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function yW(e,t){return mU(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=EW.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(vW.bind(null,r))):i.apply(this,o)}))}function SW(e,t){let{merge:i,debounce:r}=t||{};return mU(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=EW.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=TW.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 r();c.action(2,t.bind(this),s).catch(vW.bind(null,n)).then(r,o)}),e);TW.has(this)?null==(l=TW.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):TW.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(vW.bind(null,n))}))}function IW(e){return mU(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(EW.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=EW.get(this,s);return a?a.action(3,t.bind(this),n).catch(vW.bind(null,i)):t.apply(this,n)}))}var AW={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",AUDIO_FRAME:"audio-frame",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",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},RW=new Set([AW.ERROR,AW.AUTOPLAY_FAILED,AW.KICKED_OUT,AW.REMOTE_USER_ENTER,AW.REMOTE_USER_EXIT,AW.REMOTE_AUDIO_AVAILABLE,AW.REMOTE_AUDIO_UNAVAILABLE,AW.REMOTE_VIDEO_AVAILABLE,AW.REMOTE_VIDEO_UNAVAILABLE,AW.CONNECTION_STATE_CHANGED,AW.PUBLISH_STATE_CHANGED,AW.SCREEN_SHARE_STOPPED,AW.DEVICE_CHANGED,AW.FIRST_VIDEO_FRAME,AW.PERMISSION_STATE_CHANGE,AW.VIDEO_SIZE_CHANGED]),CW={};Lb(CW,{ScheduleRequestType:()=>MW,getAbilityConfig:()=>LW,getScheduleDomain:()=>xW,isNeedToSchedule:()=>kW,scheduleProxy:()=>NW,sendScheduleRequest:()=>wW,setIsNeedToSchedule:()=>DW,setScheduleProxy:()=>OW});var bW=null,kW=!0;function DW(e){Ow(e)&&e!==kW&&(kW=e,UM.info("setIsNeedToSchedule ".concat(e)))}function wW(e){return Bb(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){var e;if(!kW&&bW)return{isCached:!0,result:bW};let d={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(t)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(r)),u.append("groupId",String(n)),u.append("sdkVersion",s),u.append("userSig",String(o));let h=(null==(e=yield SM())?void 0:e.model)||RM();h&&u.append("model",h),c&&u.append("role",String(c)),l&&u.append("latencyLevel",String(l)),a&&u.append("frameWorkType",String(a));let p=Gw(),m=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;Ww([UW((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=1&&(a[0]=PW(i,"config",Hk.MAIN,!0)),n())}))(PW(i,"config",Hk.MAIN),e,{get timeout(){return 1e3*Rw(2+t.count[0])}}),UW((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=PW(i,"config",Hk.BACKUP,!0)),n())}))(PW(i,"config",Hk.BACKUP),e,{get timeout(){return 1e3*Rw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(u,d,i);m.config&&(m.config.loggerDomain&&Tk(m.config.loggerDomain),Ow(m.config.scheduleCache)&&DW(!m.config.scheduleCache)),d.delta=Gw()-p;let _=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=PW(e,"config",Hk.MAIN),s=PW(e,"config",Hk.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Hk.MAIN:Hk.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];Ux.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=Mb(Ob({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){UM.error("getScheduleDetailCost error",o)}return r}(Number(i),t,p);return bW=m,{isCached:!1,result:m,detailCost:_}}catch(GM){let t=Pw(GM)?GM[0]:GM,i=Nw(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),n=new ek({code:Zb.SCHEDULE_FAILED,extraCode:i,message:ZP({key:zP.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw UM.error(r,i),n}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(wD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),MM.on("28",(()=>DW(!0))),MM.on("63",(()=>DW(!0))),MM.on("84",(()=>DW(!0))),MM.on("201",(e=>{"RECONNECTING"===e.state&&DW(!0)})),MM.on("202",(e=>{"RECONNECTING"===e.state&&DW(!0)}));var NW={main:"",backup:""};function OW(e){Pw(e)?(NW.main=e[0],NW.backup=e[1]):NW.main=e}var MW=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(MW||{});function PW(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Hk.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(NW[i]||xW(e,i,r),"/api/v1/").concat(t)}function LW(e,t,i){let r=PW(e,t),n=PW(e,t,Hk.BACKUP),o=new URLSearchParams(i).toString(),s=fetch("".concat(r,"?").concat(o)).then((e=>e.json())),a=fetch("".concat(n,"?").concat(o)).then((e=>e.json()));return Ww([s,a])}function xW(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Hk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=dw(e)?r?i===Hk.MAIN?wD.MAIN_OVERSEA_BACKUP:wD.BACKUP_OVERSEA:i===Hk.MAIN?wD.MAIN_OVERSEA:wD.BACKUP_OVERSEA:i===Hk.MAIN?wD.MAIN:wD.BACKUP,t}function VW(e,t,i){return new Promise(((r,n)=>{CN({url:e,body:t,timeout:i.timeout,priority:"high"}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var UW=(e,t)=>PN({retryFunction:VW,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var FW=class{constructor(){Ub(this,"_log"),this._log=UM.createLogger({id:"fd"})}download(e,t){return Bb(this,null,(function*(){let{type:i="blob"}=t||{};e=uN(e);try{let t,r=Gw();if(t=kw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Gw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),lL.addSuccessEvent({key:522700,cost:Gw()-r}),t.data}catch(zM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(zM)),lL.addFailedEvent({key:522700,error:zM}),zM}}))}downloadWithFetch(e,t){return Bb(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok){let e=new Error("network response was not ok: ".concat(r.status));throw e.status=r.status,e}return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(_D){throw _D}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{if(200===n.status||0===n.status&&n.response)i({data:n.response});else{let e=new Error("XHR failed, status: ".concat(n.status));e.status=n.status,r(e)}},n.onerror=r,n.send(null)}))}loadWasm(e,t){return Bb(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Gw(),r=null,n=null;if(kw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&kw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(mk){n=mk}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(mk){n=mk}if(r){let t=Gw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),lL.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),lL.addFailedEvent({key:522701,error:n}),n}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=Gw();return new Promise(((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(Gw()-t,"ms")),lL.addSuccessEvent({key:522702,cost:Gw()-t,split:1e3}),i(n)},n.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),lL.addFailedEvent({key:522702}),r(t)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)}))}};Vb([Bx({settings:{timeout:0,retries:3},onError(e,t,i){var r;404===(null==e?void 0:e.status)||null!=(r=null==e?void 0:e.message)&&r.includes("404")?(this._log.warn("download 404, stop retry"),i(e)):t()},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],FW.prototype,"download",1),Vb([Bx({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],FW.prototype,"loadScript",1);var BW=new FW;function HW(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:o}=e;return{TRTC:i,LocalMixVideoTrack:SH,LocalVideoTrack:XB,LocalScreenTrack:RH,room:r,assetsPath:o,fileDownloader:BW,innerEmitter:MM,INNER_EVENT:LM,constants:lk,environment:xN,utils:QB,eventLogger:Ux,log:this.room.getLogger(),loggerManager:UM,errorModule:n,kvStatManager:lL,rtcDectection:HM,trtc:this,rx:AU,enums:WM,schedule:CW,getDevices:JV,initVisionTaskRegistry:function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"/mediapipe/vision.js";return Bb(t,null,(function*(){window.VisionTaskRegistry||(yield BW.loadScript("".concat(e,"/").concat(i).replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels([window.VisionTaskType.ImageSegmenter])}))},audioContext:bV(),deviceDetector:GV,AudioPlayer:eU,AutoPlayDialog:uV,Timer:Ox,clearStarted:(e,t)=>{let i=e.getAlias(),r=EW.instances.get(this);if(r)if(t){let e=r.get(i+t);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(i)&&(e.started=!1)}))},startGetPCM:kH,createAudioNode:PV,getNetworkTimeOffset:nk,validateSourceNode:()=>{var e;if(ZN&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new QH({code:qH.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var WW=new WeakMap;var GW="5.14.0-beta.1";function jW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return mU(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{qW.call(this,t,n,i,this._name)}catch(zM){return Promise.reject(zM)}return e.apply(this,n)}))}function JW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return mU(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{qW.call(this,t,n,i,this._name)}catch(zM){throw zM}return e.apply(this,n)}))}function qW(e,t,i,r){if(Pw(e))for(let n=0;n<e.length;n++)KW.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else KW.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function KW(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:qH.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(Dw(i)){if(t.required)throw new QH(s(5001));if(Dw(t.defaultValue))return void(kw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),kw(t.type[r])&&i instanceof t.type[r]&&(e=!0),ww(t.type[r])&&bw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new QH({code:qH.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Uw(e)?Fw(e):ww(e)?e:bw(e)))},value:i}})}else if(!Dw(t.type)&&bw(i)!==t.type)throw new QH(s(5002));if(!1===t.allowEmpty){let e=Nw(i)&&(0===i||Number.isNaN(i)),t=ww(i)&&""===i.trim();if(e||t)throw new QH(s(5003))}if(t.notLessThanZero&&Nw(i)&&i<0)throw new QH(s(5006));if(!Dw(t.min)&&Nw(i)&&i<t.min)throw new QH(s(5007));if(!Dw(t.max)&&Nw(i)&&i>t.max)throw new QH(s(5008));if(ww(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new QH(s(5004))}else if(kw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new QH(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new QH(s(5005));let{properties:a}=t;Aw(a)&&Mw(i)&&Object.keys(a).forEach((e=>{KW.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;Aw(c)&&Pw(i)&&i.forEach(((e,t)=>{KW.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),kw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function zW(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:o}=e;return mU(((e,s)=>function(){for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...c);if(c[e.argIndex]===t)return e.value}if(t===c||e in c)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(bw(t)):t instanceof MediaStreamTrack?hN(t):(JSON.stringify(t),t)}catch(n){return"type:".concat(bw(t))}}let m=this._log||UM;if(null!=n&&n(...c))return e.apply(this,c);c.length>0?m.info("".concat(s,"() ").concat(JSON.stringify(c,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(s,"()"));let _=r?r(...c):iL[s],f=(null==o?void 0:o(...c))||!1;try{let i=e.apply(this,c),r=Gw();if(Vw(i)){let e="".concat(s.includes("Plugin")?"".concat((null==(u=(d=c[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then((i=>(m.info("".concat(s,"() success ").concat(e).concat(t.call(this,...c))),lL.addSuccessEvent({key:_,cost:Gw()-r}),i))).catch((i=>{var r;let n=(i=QH.convertFrom.call(this,i,s,1===c.length?c[0]:c)).extraCode||i.code,o=null!=(r=i.message)&&r.includes(n)?"":" code:".concat(n);throw f||m.error("".concat(s,"() failed ").concat(e).concat(t.call(this,...c)," ").concat(i).concat(o," params: ").concat(JSON.stringify(c,p))),lL.addFailedEvent({key:_,error:i}),i}))}return lL.addSuccessEvent({key:_}),i}catch(ZM){let t=(ZM=QH.convertFrom.call(this,ZM,s)).extraCode||ZM.code,i=null!=(h=ZM.message)&&h.includes(t)?"":" code:".concat(t);throw f||m.error("".concat(s,"() failed ").concat(ZM).concat(i," params: ").concat(JSON.stringify(c,p))),lL.addFailedEvent({key:_,error:ZM}),ZM}}))}var YW,XW=e=>mU(((t,i)=>function(r,n){return Bb(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new QH({code:qH.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(kw(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new QH({code:qH.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return qW.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),QW=0,ZW=class e{constructor(e){this.core=e,Ub(this,"log"),Ub(this,"customAudioReferenceMap",new Map),Ub(this,"audioRefId",0),Ub(this,"audioContext",bV()),Ub(this,"localAudioWorkletNode"),Ub(this,"screenAudioWorkletNode"),Ub(this,"mixNode"),Ub(this,"silentNode"),QW+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(QW)}),this.log.info("created id=".concat(this.getAlias()).concat(QW)),this.installEvent()}static getStartValidateRule(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,r,n){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new QH({code:qH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return YW||(YW=this.doPreload(e)),YW}doPreload(e){return Bb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield pV(this.audioContext,i)}catch(zM){this.log.error("preload audioProcessor failed. ".concat(zM))}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return e.getStartValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Bb(this,null,(function*(){var t,i,r,n;let{room:o}=this.core,{sdkAppId:s,userId:a,userSig:c,assetsPath:l=this.core.assetsPath,audioReference:d,processLevel:u,enableDump:h,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:m=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!l)throw new QH({code:qH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(l,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(s,a,c);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",s,a,i,e,t,o)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(s,a,c);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",s,a,i,e,t,o)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"enable"}),null==(i=this.screenAudioWorkletNode)||i.port.postMessage({type:"enable"}),o.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),Dw(d)||d.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})})),Dw(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),Dw(h)||null==(n=this.localAudioWorkletNode)||n.port.postMessage({type:"dump",data:{enable:h}})}))}update(e){return Bb(this,null,(function*(){var t,i,r;let{audioReference:n,enableDump:o,processLevel:s}=e;Dw(n)||(this.customAudioReferenceMap.forEach(((e,t)=>{this.customAudioReferenceMap.delete(t),this.core.room.audioManager.updateAudioReference({type:"remove",refId:e})})),n.forEach((e=>{this.customAudioReferenceMap.set(e,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(this.audioRefId++)})}))),Dw(s)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:s}}),Dw(o)||(null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:o}}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:o}}))}))}stop(){return Bb(this,null,(function*(){var e,t;let{room:i}=this.core;null==(e=this.localAudioWorkletNode)||e.port.postMessage({type:"disable"}),null==(t=this.screenAudioWorkletNode)||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)}))}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,t,i){return Bb(this,null,(function*(){let r=String(Date.now()).slice(0,-3),{auth:n,sign:o,status:s,message:a}=yield function(e){return Bb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Hk.MAIN;return"https://".concat(NW[t]||xW(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"&timestamp=").concat(n),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=dw(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",u="Init RTCAudioProcessor failed.",h="";switch(s){case 1:h="Please check your params.";break;case 2:h="You need to buy packages. Refer to: ".concat(d);break;case 3:h="Server is invalid. Please contact our engineer. ";break;case 4:h="Your packages is not active. Refer to: ".concat(d);break;case 5:h="Your packages is expired. Refer to: ".concat(d);break;case 6:h="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(u," Reason: ").concat(a,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}({sdkAppId:e,userSig:i,userId:t,timestamp:r});if(!n)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(n,". Message: ").concat(a)),new QH({code:qH.INVALID_PARAMETER,message:a});return{sign:o,status:s,timestamp:r}}))}initWorkletNode(e,t,i,r,n,o,s,a){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:n,sign:o,status:s}}),e.port.onmessage=e=>{var i;let{data:r}=e;switch(r.type){case"cost":let e=(null==r?void 0:r.value)>10?"info":"debug";return void this.log[e]("".concat("localAudio"===t?"":"[".concat(t,"] "),"avg cost: ").concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(ak(new Date(null==r?void 0:r.maxCostTimestamp)),") hist: ").concat(null==(i=null==r?void 0:r.hist)?void 0:i.join(" ")));case"log":return void this.log[r.logLevel]("".concat("localAudio"===t?"":"[".concat(t,"] ")).concat(r.value));case"dump":return void MM.emit("265",{room:a,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(e){return Bb(this,null,(function*(){var t;if(this.hitTest(e.room)&&!0===(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(_D){this.log.warn("audio processor auto start failed, error: ".concat(_D))}}))}handleLocalAudioStopped(e){return Bb(this,null,(function*(){var t;!this.hitTest(e.room)||!0!==(null==(t=this.core.room.scheduleResult.config)?void 0:t.audioProcessor)||(yield this.core.trtc.stopPlugin("AudioProcessor"))}))}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(e){return e===this.core.room}};Ub(ZW,"updateValidateRule",{type:"object"}),Ub(ZW,"stopValidateRule",{type:"object"}),Ub(ZW,"Name","AudioProcessor");var $W=ZW;var eG=0,tG=class{constructor(e,t){Ub(this,"audioObjectURL"),Ub(this,"player"),Ub(this,"publisher"),Ub(this,"mixInput"),this.mixInput=new NV(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()}updateSettings(e){this.player&&(Dw(e.volume)||(this.volume=e.volume),Dw(e.loop)||(this.loop=e.loop),Dw(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reload(e){return Bb(this,null,(function*(){if(e.url){let t=yield BW.download(e.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(e),this.updateSettings(e))}else this.mixInput.replaceSource(e.track)}))}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 Promise.all([null==(e=this.player)?void 0:e.play(),null==(t=this.publisher)?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)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function iG(e,t){if(t&&"function"!=typeof t)throw new QH({code:qH.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var rG=class e{constructor(e){this.core=e,Ub(this,"log"),Ub(this,"mixedMusicMap",new Map),Ub(this,"cacheMusicMap",new Map),eG+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(eG)}),this.log.info("created id=".concat(this.getAlias()).concat(eG))}getName(){return e.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(t){switch(t){case"start":return e.startValidateRule;case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Bb(this,null,(function*(){let{room:t}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new tG(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e);try{yield n.play()}catch(mk){yield this.handleAutoPlayFailed(n,e,mk)}this.mixedMusicMap.set(i,n),n.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:n.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),lL.addEnum({key:502700,value:3}),this.kvUpload(e)}))}handleAutoPlayFailed(e,t,i){return Bb(this,null,(function*(){if("NotSupportedError"===i.name)this.log.error("play failed, try to reload source. error: ".concat(i)),yield e.reload(t),yield e.play();else{if("NotAllowedError"!==i.name)throw i;if(this.core.room.enableAutoPlayDialog){let t=()=>{var i;null==(i=e.play())||i.finally((()=>{MM.off("154",t,this)}))};MM.on("154",t,this),new uV}else this.core.trtc.emit(AW.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>Bb(this,null,(function*(){return e.play()}))})}}))}update(e){return Bb(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),Dw(i)||o.setOperation(i),Dw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return Bb(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){if(t.mixedMusicMap.has(i)){t.log.info("remove music source, music id: ".concat(i));let e=t.mixedMusicMap.get(i);null!=e&&e.mixInput.source.node&&t.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.source.node,refId:"ax-".concat(i)}),null==e||e.stop(),t.mixedMusicMap.delete(i)}"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&lL.addCount({key:502009}),i&&lL.addCount({key:502001}),r&&lL.addCount({key:502002}),n&&lL.addCount({key:502003}),o&&lL.addCount({key:502004}),s&&lL.addCount({key:502005}),"function"!=typeof a&&lL.addCount({key:502007}),"function"!=typeof l&&lL.addCount({key:502008}),"function"!=typeof c&&lL.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{null!=e&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId: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()}};Ub(rG,"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],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new QH({code:qH.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new QH({code:qH.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});iG("onTimeUpdate",e.onTimeUpdate),iG("onEnded",e.onEnded),iG("onDurationChange",e.onDurationChange)}}),Ub(rG,"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"]}},validate(e,t,i){iG("onTimeUpdate",e.onTimeUpdate),iG("onEnded",e.onEnded),iG("onDurationChange",e.onDurationChange)}}),Ub(rG,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Ub(rG,"Name","AudioMixer");var nG,oG=rG,sG=0,aG=class e{constructor(e){this.core=e,Ub(this,"log"),Ub(this,"audioContext",bV()),Ub(this,"workletNode"),Ub(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),sG+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(sG)}),this.log.info("created id=".concat(this.getAlias()).concat(sG))}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new QH({code:qH.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return nG||(nG=this.doPreload(e)),nG}doPreload(e){return Bb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield pV(this.audioContext,i)}catch(zM){throw this.log.error("load worklet failed",zM),zM}finally{URL.revokeObjectURL(i)}}))}getName(){return e.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}start(e){return Bb(this,null,(function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new QH({code:qH.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(r,"/denoiser-wasm").concat(nx()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:n,status:o,message:s}=yield function(e,t){return Bb(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:o,timestamp:s}=t;return function*(){try{let{data:{errCode:t,errMsg:n,sign:a,status:c}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:o,timestamp:s});if("1"===c)return{auth:!0,sign:a,status:c,message:n};let l=dw(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",d="Init RTCAIDenoiser failed.",u="";switch(t){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: ".concat(l);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(l);break;case 5:u="Your packages is expired. Refer to: ".concat(l);break;case 6:u="Your version is not supported."}return{auth:!1,status:c,message:n?"".concat(d," Reason: ").concat(n,". ").concat(u):"".concat(d,", ").concat(u)}}catch(n){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(n)}}}()}))}(i,Mb(Ob({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(s)),new QH({code:qH.INVALID_PARAMETER,message:s});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:o}}),this.workletNode.port.onmessage=e=>{var t;let{data:i}=e;if("cost"===i.type){let e=(null==i?void 0:i.max)>20?"warn":(null==i?void 0:i.max)>10?"info":"debug";this.log[e]("avg cost: ".concat(i.value," max: ").concat(null==i?void 0:i.max,"(").concat(ak(new Date(null==i?void 0:i.maxCostTimestamp)),") hist: ").concat(null==(t=null==i?void 0:i.hist)?void 0:t.join(" ")))}else"log"===i.type&&this.log[i.logLevel]("".concat(i.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(e){return Bb(this,null,(function*(){this.updateConfig(e)}))}stop(){return Bb(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}updateConfig(e){if(!this.workletNode)return;let t=!1;Dw(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),Dw(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,t=!0),t&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};Ub(aG,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Ub(aG,"stopValidateRule",{type:"object"}),Ub(aG,"Name","AIDenoiser");var cG=aG;var lG=xb(Hb(),1),dG=class extends lG.EventEmitter{constructor(){super(),Ub(this,"observer"),Ub(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return Bb(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!zN&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(pk){Ux.uploadEvent({log:"stat-pressure-detector-start-failed",error:pk})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&UM.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(_D){Ux.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:_D})}}},uG=new dG;function hG(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new KB(new DataView(new Uint8Array(s).buffer),!0)}function pG(e){return"empty"===e.type||0===e.data.byteLength}function mG(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function _G(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function fG(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-_G(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(hG),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function gG(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(pG(t)||!mG(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new KB(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(pk){}return t}var EG=0,TG=class e{constructor(e){this.core=e,Ub(this,"log"),Ub(this,"_seiMessageList",[]),Ub(this,"_smallSeiMessageList",[]),Ub(this,"_subStreamSeiMessageList",[]),EG++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(EG)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(EG)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return fG({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(_D){this.log.warn(_D)}return t}decode(e){let{frame:t,track:i}=e;return gG({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(AW.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:QL?this.encode:fG,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:QL?this.decode:gG,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Ub(TG,"autoStart",!0),Ub(TG,"Name","SEI");var vG=TG;function yG(e){let{frame:t,onDump:i}=e;return null==i||i(),t}function SG(e){let{frame:t,onDump:i}=e;return null==i||i(),t}var IG={"play() error: NotAllowedError:":{tips:e=>e.includes("main <video>")||e.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:e=>e.includes("↓")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:"The remote stream audio playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:"The remote stream video playback is paused, which usually has two possibilities:\n 1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.\n 2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.",color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach((e=>{IG["".concat(e,"()")]={tips:"Call trtc.".concat(e),color:"blue",class:"blue",textColor:"#fff"}}));var AG,RG=0,CG=class e{constructor(e){this.core=e,Ub(this,"_core"),Ub(this,"log"),Ub(this,"dumpLocalVideoMap",{}),Ub(this,"dumpRemoteVideoMap",{}),Ub(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++RG)}),this.log.info("created")}getName(){return e.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return Bb(this,null,(function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))||(yield this.openDebugDiaLog(),this.addVideoProcessor())}))}update(e){return Bb(this,arguments,(function(e){var t=this;let{visible:i}=e;return function*(){i?(yield t.openDebugDiaLog(),t.addVideoProcessor()):(t.closeDebugDiaLog(),t.removeVideoProcessor())}()}))}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return Bb(this,null,(function*(){var e;if(!this.dialog)try{if(AG)yield AG;else{let t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||(null==(e=window.sessionStorage)?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(uk,"/assets/debug-dialog.js");AG=this._core.fileDownloader.loadScript(t),yield AG}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(pk){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(pk))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):yG,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):SG,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo(e){let{frame:t,mediaType:i}=e;return yG({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return SG({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}};Ub(CG,"Name","Debug"),Ub(CG,"autoStart",!0);var bG=CG,kG=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},DG=class{constructor(e,t,i){Ub(this,"trackDoneOB"),Ub(this,"startOB"),Ub(this,"stopOB"),Ub(this,"inputFrameCount",0),Ub(this,"decodedFrameCount",0),Ub(this,"type","auto"),Ub(this,"config"),Ub(this,"decoder"),Ub(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=_F(t,Cx.INIT),this.stopOB=iF(),this.startOB=iF(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=iF();LU(this.startOB,QU(0),mB((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),LU(i,VF(this.stopOB),UB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:kG(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),LU(i,xF(1),MB(bF))})),VF(this.stopOB),UB((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:kG(this.type)}),r.addSuccessEvent({key:504702})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return GU()((t=>Bb(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e;null==(e=this.decoder)||e.close()}));let{type:i}=this;try{if("webCodecs"===i)this.decoder=new AudioDecoder({error:i=>{e.log.error(i),t.error(4)},output:i=>{this.decodedFrameCount++,t.next(i),e.player.write(i)}});this.decoder.configure(this.config)}catch(zM){e.log.error(zM),t.error("webCodecs"===i?2:6)}}))))}decodeFrame(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},wG={type:"object"},NG=class e{constructor(e){this.core=e,Ub(this,"log"),Ub(this,"contextMap",new Map),Ub(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return e.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return e.Name}getValidateRule(e){return wG}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:i}=e;return this.decodeProcessorMap.has(i)?this.decodeProcessorMap.get(i)({frame:t,track:i}):t},type:3})}decode(e){return t=>{let{frame:i,track:r}=t;if(r!==e.track)return i;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(i);let n=new DG(this.core,r,e);return LU(n.trackDoneOB,xF(1),UB((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,n),n.decodeFrame(i)}}stop(e){let{track:t}=e,i=this.contextMap.get(t);i&&(i.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new DG(this.core,e.track,e))}}};Ub(NG,"Name","TRTCAudioDecoder");var OG=NG,MG=class{constructor(){Ub(this,"log"),this.log=UM.createLogger({id:"exp"})}call(e,t){return Bb(this,null,(function*(){return kw(this[e])?this[e](t):Promise.reject(new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return Bb(this,null,(function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:n=48e3,channelCount:o=1,port:s}=e,{audioManager:a}=t.room,{getPCMAbortCtrlMap:c,audioFrameEventConfigMap:l}=a;if(l.set(r,{enable:i,sampleRate:n,channelCount:o,port:s}),i)if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(c.get(e.userId))return;let i=a.getPCM((e=>{t.emit(AW.AUDIO_FRAME,e)}),e.userId);c.set(e.userId,i)}}));else{if(c.get(r))return;let e=a.getPCM((e=>{t.emit(AW.AUDIO_FRAME,e)}),r);c.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=c.get(t);null==i||i.abort("disable"),c.delete(t)}}));else{let e=c.get(r);null==e||e.abort("disable"),c.delete(r)}}))}resumeRemotePlayer(e){return Bb(this,null,(function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach((i=>{let{remoteAudioTrack:r,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=i;e.streamType?"main"===e.streamType?(r.isAvailable&&t.push(r.player.resume()),n.isAvailable&&t.push(n.player.resume())):o.isAvailable&&t.push(o.player.resume()):(r.isAvailable&&t.push(r.player.resume()),n.isAvailable&&t.push(n.player.resume()),o.isAvailable&&t.push(o.player.resume()))})),Promise.all(t)}let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);if(t)return"main"===e.streamType?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()}))}pauseRemotePlayer(e){if("*"===e.userId)e.trtcInstance.room.remotePublishedUserMap.forEach((t=>{let{remoteAudioTrack:i,remoteVideoTrack:r,remoteAuxiliaryTrack:n}=t;e.streamType?"main"===e.streamType?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause()):n.isAvailable&&n.player.pause():(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(),n.isAvailable&&n.player.pause())}));else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause()):t.remoteAuxiliaryTrack.player.pause())}}};Vb([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return mU(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return UH.call(this,t,n,i,this._name),e.apply(this,n)}))}({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],MG.prototype,"enableAudioFrameEvent",1);var PG=new MG,LG=xb(Hb(),1),xG=class extends LG.EventEmitter{constructor(){super(),Ub(this,"states",{}),Ub(this,"permissionChangeHandler"),Ub(this,"log"),this.log=UM.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:null==(e=this.states.camera)?void 0:e.state,microphone:null==(t=this.states.microphone)?void 0:t.state})}}request(e){return Bb(this,null,(function*(){if(this.log.info("request ".concat(e.join(", "))),0===e.length)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach((e=>e.stop()))}))}get(e){return Bb(this,null,(function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(e," permission state: ").concat(this.states[e].state)),this.states[e].state}catch(_D){return this.log.error("get ".concat(e," permission failed, error: ").concat(_D instanceof Error?_D.message:_D)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},VG=new xG,UG=0,FG=new Set,BG=null;hk(GW),BM.checkStorage();var HG=class e extends Xb.EventEmitter{constructor(t,i){super(),Ub(this,"_room"),Ub(this,"_eventListened",new Set),Ub(this,"_localVideoTrack",null),Ub(this,"_localAudioTrack",null),Ub(this,"_localScreenTrack",null),Ub(this,"_localScreenAudioTrack",null),Ub(this,"_localVideoConfig",null),Ub(this,"_localScreenConfig",null),Ub(this,"_localAudioConfig",null),Ub(this,"_remoteVideoConfigMap",new Map),Ub(this,"_remoteAudioConfigMap",new Map),Ub(this,"_remoteAudioVolumeMap",new Map),Ub(this,"_remoteAudioMuteMap",new Map),Ub(this,"_mediaTrackMap",new WeakMap),Ub(this,"_log",UM.createLogger({id:"t".concat(++UG)})),Ub(this,"_plugins",new Map),Ub(this,"_networkQuality",null),Ub(this,"_speakerId"),Ub(this,"enterRoomParams"),Ub(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(Ob({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,Ow(i.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=i.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(i,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),i.plugins&&i.plugins.forEach((e=>{this._use(e,i.assetsPath)})),this._use(oG,i.assetsPath),this._use($W,i.assetsPath),this._use(cG,i.assetsPath),this._use(OG,i.assetsPath),this._use(bG),i.enableSEI&&$L&&this._use(vG),this._room.on("audio-volume",(e=>{var t,r;!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*(null!=(t=this._localAudioTrack.getInternalAudioLevelAfter3A())?t:this._localAudioTrack.getAudioLevel())),floatVolume:null!=(r=this._localAudioTrack.getInternalAudioLevelAfter3A())?r:this._localAudioTrack.getInternalAudioLevel()}),1===i.volumeType&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),i.enableDbVolume&&e.forEach((e=>{var t;let i=""===e.userId?this._localAudioTrack:null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;i&&(e.volume=i.dbVolume)})),this.emit(AW.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new QH({code:qH.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(zM){let i=ZP({key:zP.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return UM.warn("".concat(i,"\n\n").concat(zM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(jH){jH=!1,5!==UM.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Ak,"/en/index.html")),console.info("* Changelog: ".concat(Ak,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),UM.info("TRTC Web SDK Version:",uk),_M||UM.debug("Build Time:","2025-10-27 11:34:11");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(IM()),i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),UM.info(t),UM.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),SM().then((e=>{e&&UM.info(yM)}))}}();let r=new e(t,i||{});return FG.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){xx(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(AW.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(AW.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().finally((()=>{this.emit(AW.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(AW.ERROR,QH.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(AW.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=Mb(Ob({},e),{uplinkRTT:Math.min(e.uplinkRTT,WD),downlinkRTT:Math.min(e.downlinkRTT,WD)});this.emit(AW.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{xx(t,t).add("player-state-changed",(i=>{let r=Mb(Ob({},i),{userId:e.userId});t.kind===Hk.VIDEO&&(r.streamType=ZH(t.streamType)),this.emit(t.kind===Hk.AUDIO?AW.AUDIO_PLAY_STATE_CHANGED:AW.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===Zb.PLAY_NOT_ALLOWED&&this.emit(AW.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{Vx(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),o!==a&&(a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(a?AW.REMOTE_VIDEO_AVAILABLE:AW.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),n!==s&&(s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(s?AW.REMOTE_AUDIO_AVAILABLE:AW.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),t.hasAuxiliary!==i.hasAuxiliary&&(i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(i.hasAuxiliary?AW.REMOTE_VIDEO_AVAILABLE:AW.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(AW.SEI_MESSAGE,Mb(Ob({},e),{streamType:ZH(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(AW.ERROR,new QH({code:qH.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(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==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,WD),upLoss:(null==(n=this._networkQuality)?void 0:n.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)/PP},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)/PP,point2pointDelay:(e.msg_audio_status.uint32_audio_p2p_delay||0)+(e.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:e.msg_audio_status.uint32_audio_cache_ms||0},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],point2pointDelay:(e.uint32_video_p2p_delay||0)+(e.uint32_video_cache_ms||0),jitterBufferDelay:e.uint32_video_cache_ms||0,codec:e.uint32_video_codec})))})))};this.emit(AW.STATISTICS,l)})).add("custom-message",(e=>{this.emit(AW.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(AW.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(AW.FIRST_VIDEO_FRAME,Mb(Ob({},e),{streamType:ZH(e.streamType)}))})).add("audio-frame",(e=>{this.emit(AW.AUDIO_FRAME,e)})),xx(this,GV).add("audioInputAdded",(e=>{this.emit(AW.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(AW.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(AW.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(AW.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>Bb(this,null,(function*(){if(this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),BG&&BG.deviceId===LD){let e=(yield YV()).find((e=>e.deviceId===LD));e&&BG.groupId!==e.groupId&&(BG=e,this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>Bb(this,null,(function*(){this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield YV())[0];if(!t||!BG||BG.groupId===t.groupId)return;let i=BG.deviceId===e.deviceId,r=BG.deviceId===LD&&BG.deviceId===t.deviceId;(i||r)&&(BG=t,this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),xx(this,VG).add("permission-state-change",(e=>{this.emit(AW.PERMISSION_STATE_CHANGE,e)}))}getNetworkTime(){return ok()}use(e){let t,i;return"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,"Chorus"===t.Name&&(this.room.enableChorus=!0),this._use(t,i)}_use(t,i){let r=this._plugins.get(t.Name);if(r)return this._log.warn("duplicate install plugin",t.Name),r;let n=new t(HW.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:QH,ErrorCode:qH,CoreErrorCode:Zb,ErrorCodeDictionary:KH}}));return this._plugins.set(t.Name,n),n.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),n}enterRoom(t){return Bb(this,null,(function*(){var i,r;this.enterRoomParams=t;let{scene:n="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:a=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!ww(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=a,Ow(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:"audience"===t.role?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,e.frameWorkType),this._checkTrackToPublish(),uG.start()}))}exitRoom(){return Bb(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return Bb(this,null,(function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(_D){if(!(_D instanceof $b)||_D.code!==Zb.API_CALL_TIMEOUT&&_D.code!==Zb.SWITCH_ROOM_FAILED)throw _D;this._log.warn("switchRoom ".concat(_D.code===Zb.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)}))}_rejoinRoom(e){return Bb(this,null,(function*(){yield this.exitRoom();let t=Ob(Ob({},this.enterRoomParams),e);yield this.enterRoom(t)}))}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.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(),function(e){let t=WW.get(e);t&&(t.forEach((e=>clearTimeout(e))),WW.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{Vx(e.remoteAudioTrack),Vx(e.remoteVideoTrack),Vx(e.remoteAuxiliaryTrack)}))}switchRole(e,t){return Bb(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)})),this._plugins.clear(),Vx(this),this.removeAllListeners(),this._room.destroy(),FG.delete(this),0===FG.size&&uG.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),MM.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return Bb(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:r,option:n}=t,o=new qB(e._room.audioManager),s={},a={muted:!0};n&&(Dw(n.microphoneId)?Dw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&Nw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),Dw(n.profile)||(ww(n.profile)?xk[n.profile]&&o.setProfile(xk[n.profile]):o.setProfile(n.profile)),Nw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),Dw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),Dw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),Dw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl),Ow(e._enableAutoSwitchWhenRecapturing)&&(o.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),o.on("5",(t=>{e.emit(AW.ERROR,new QH({code:qH.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(AW.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=QH.convertFrom(t.error)),e.emit(AW.PUBLISH_STATE_CHANGED,Mb(Ob({},t),{error:i}))})),o.on("6",(()=>{e.emit(AW.ERROR,new QH({code:qH.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),Dw(r)||o.setMute(r),xx(o,o).add("player-state-changed",(t=>{e.emit(AW.AUDIO_PLAY_STATE_CHANGED,Mb(Ob({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=Mb(Ob({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o}),MM.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return Bb(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):Dw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),Dw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),Dw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!Dw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),Dw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Qw(this._localAudioConfig,e)}))}stopLocalAudio(){return Bb(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),MM.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Vx(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return Bb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var i;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:r,publish:n=!0,capture:o=!0,mute:s,option:a}=t,c=new XB(e._room.videoManager),l={},d={};a&&(Ow(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:Dw(a.useFrontCamera)?Dw(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?Hk.FACING_MODE_USER:Hk.FACING_MODE_ENVIRONMENT,Dw(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=$H(a.qosPreference)),Dw(a.profile)||(ww(a.profile)?Vk[a.profile]&&c.setProfile(Vk[a.profile]):c.setProfile(a.profile)),Dw(a.fillMode)||(d.objectFit=a.fillMode),Dw(a.mirror)||(d.mirror=a.mirror),Dw(a.small)||(Dw(a.smallMode)||(e._room.smallMode=a.smallMode),Ow(a.small)&&!1===a.small?c.stopSmall():c.updateSmallConfig(eW(a.small,!0))),Dw(a.rotation)||c.setRotation(a.rotation),Ow(e._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",(t=>{e.emit(AW.FIRST_VIDEO_FRAME,Mb(Ob({},t),{streamType:ZH(t.streamType)}))})),c.on("5",(t=>{e.emit(AW.ERROR,new QH({code:qH.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),c.on("2",(t=>{e.emit(AW.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),c.on("4",(t=>{let i;t.error&&(i=QH.convertFrom(t.error)),e.emit(AW.PUBLISH_STATE_CHANGED,Mb(Ob({},t),{error:i}))})),c.on("6",(()=>{e.emit(AW.ERROR,new QH({code:qH.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))})),e._listenOutputTrackChanged(c),o?yield c.capture(l):null==(i=c.manager)||i.changeInput(c),Dw(s)||(yield c.setMute(s)),xx(c,c).add("player-state-changed",(t=>{e.emit(AW.VIDEO_PLAY_STATE_CHANGED,Mb(Ob({},t),{userId:"",streamType:"main"}))})).add("video-size-changed",(t=>{e.emit(AW.VIDEO_SIZE_CHANGED,Mb(Ob({},t),{streamType:ZH(t.streamType)}))})),n&&e._room.isJoined&&e._room.publish(c).catch((()=>{})),e._localVideoTrack=c,e._localVideoConfig=Mb(Ob({},t),{view:r,publish:n,capture:o}),yield e._updateVideoPlayOption({view:r,playOption:d,track:c})}()}))}updateLocalVideo(e){return Bb(this,null,(function*(){var t,i,r;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:n,publish:o,mute:s,capture:a,option:c}=e,l={};if(this._localVideoConfig.capture)!1!==a?null!=c&&c.cameraId?yield this._localVideoTrack.switchDevice(null==c?void 0:c.cameraId):Dw(null==c?void 0:c.useFrontCamera)?Dw(null==c?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==c?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(null!=c&&c.useFrontCamera?Hk.FACING_MODE_USER:Hk.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(a){let e={};e.deviceId=(null==c?void 0:c.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=c&&c.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?Hk.FACING_MODE_USER:Hk.FACING_MODE_ENVIRONMENT,e.customSource=(null==c?void 0:c.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}c&&(Dw(c.profile)||(ww(c.profile)?Vk[c.profile]&&this._localVideoTrack.setProfile(Vk[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&Dw(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),Dw(c.fillMode)||(l.objectFit=c.fillMode),Dw(c.mirror)||(l.mirror=c.mirror),Dw(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint($H(c.qosPreference)),Dw(c.small)||(Ow(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(eW(c.small,!0)))),this._room.isJoined&&Dw(o)&&this._localVideoConfig.publish&&a&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._room.isJoined&&((null!=o?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch((()=>{})):this._room.unpublish(this._localVideoTrack).catch((()=>{}))),Dw(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:n,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Qw(this._localVideoConfig,e)}))}stopLocalVideo(){return Bb(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),Vx(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return Bb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){var i,r;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:n=null,publish:o=!0,muteSystemAudio:s,option:a}=t,c=new RH(e._room.videoManager);c.on("4",(t=>{let i;t.error&&(i=QH.convertFrom(t.error)),e.emit(AW.PUBLISH_STATE_CHANGED,Mb(Ob({},t),{error:i}))})),c.once("first-video-frame",(t=>{e.emit(AW.FIRST_VIDEO_FRAME,Mb(Ob({},t),{streamType:ZH(t.streamType)}))})),e._listenOutputTrackChanged(c),"main"===t.streamType&&(c.mediaType=4);let l=null,d={},u={};a&&(Dw(a.profile)||(ww(a.profile)?Bk[a.profile]&&c.setProfile(Bk[a.profile]):c.setProfile(a.profile)),a.systemAudio&&(d.systemAudio=!0,d.echoCancellation=a.echoCancellation,d.noiseSuppression=a.noiseSuppression,d.autoGainControl=a.autoGainControl),Dw(a.fillMode)||(u.objectFit=a.fillMode),a.videoTrack&&(d.videoTrack=a.videoTrack),a.audioTrack&&(d.audioTrack=a.audioTrack),a.captureElement&&(d.captureElement=a.captureElement),a.preferDisplaySurface&&(d.preferDisplaySurface=a.preferDisplaySurface),a.qosPreference&&(d.contentHint=$H(a.qosPreference)));let h=yield c.capture(d);if(c.mediaTrack.addEventListener(Hk.ENDED,(()=>{e._stopScreenShare(),e.emit(AW.SCREEN_SHARE_STOPPED)})),h.getAudioTracks()[0]){l=new bH(e._room.audioManager);let n=h.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(l.sourceTrack=n),yield l.setInputMediaStreamTrack(n),Ow(s)&&l.mediaTrack&&(l.mediaTrack.enabled=!s),e._speakerId&&l.setAudioOutput(e._speakerId)}if(xx(c,c).add("player-state-changed",(t=>{e.emit(AW.VIDEO_PLAY_STATE_CHANGED,Mb(Ob({},t),{userId:"",streamType:"sub"}))})),o&&e._room.isJoined){let t=[c];l&&(t.push(l),e._checkScreenAudioEchoCancellation(c,l)),t.forEach((t=>e._room.publish(t).catch((()=>{}))))}e._localScreenTrack=c,e._localScreenAudioTrack=l,e._localScreenConfig=Mb(Ob({},t),{view:n,publish:o}),yield e._updateVideoPlayOption({view:n,playOption:u,track:c})}()}))}updateScreenShare(e){return Bb(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,publish:r,muteSystemAudio:n,option:o}=e,s={};if(o&&(Dw(o.fillMode)||(s.objectFit=o.fillMode),o.qosPreference)){let e=$H(o.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!Dw(r)){if(r&&!this._localScreenConfig.publish){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),e.forEach((e=>this._room.publish(e).catch((()=>{}))))}if(this._localScreenConfig.publish&&!r){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),e.forEach((e=>this._room.unpublish(e).catch((()=>{}))))}}null!=(t=this._localScreenAudioTrack)&&t.mediaTrack&&Ow(n)&&(this._localScreenAudioTrack.mediaTrack.enabled=!n),yield this._updateVideoPlayOption({view:i,playOption:s,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Qw(this._localScreenConfig,e)}))}stopScreenShare(){return Bb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return Bb(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;c.on("decode-failed",(e=>{this.emit(AW.ERROR,new QH({code:qH.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),c.on("video-size-changed",(e=>{this.emit(AW.VIDEO_SIZE_CHANGED,Mb(Ob({},e),{streamType:ZH(e.streamType)}))})),this._listenOutputTrackChanged(c),n&&(Dw(n.fillMode)||(a.objectFit=n.fillMode),Dw(n.mirror)||(a.mirror=n.mirror),Dw(n.poster)||(a.poster=n.poster),a.canvasRender=n.canvasRender,"main"===r&&!Dw(n.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,r),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!Dw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return Bb(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(Dw(s.fillMode)||(l.objectFit=s.fillMode),Dw(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&null!=u&&u.muteState.hasVideo&&(d=u.remoteVideoTrack),"sub"===o&&null!=u&&u.muteState.hasAuxiliary&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!Dw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),Qw(h,e);let p=Dw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=Dw(r)?h.view:r,_=Dw(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 Bb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Bb(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.delete(e.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)}))}_removeRemoteVideoConfig(e,t){let i="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(i);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(i)}muteRemoteAudio(e,t){return Bb(this,null,(function*(){this._remoteAudioMuteMap.set(e,t);try{if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(zM){throw zM.code!==qH.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),zM}}))}setRemoteAudioVolume(e,t){if("*"===e){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach(((e,i)=>this._remoteAudioVolumeMap.set(i,t)));let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),i&&i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return Bb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return Bb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return Bb(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){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),this.listeners(AW.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:e}=this.room.audioManager;e.get("")||e.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];try{RW.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(zM){}return super.emit(e,...i)}off(t,i,r){if(this._log.debug("off",t),"*"===t?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,i,r),(t===e.EVENT.AUDIO_FRAME||"*"===t)&&0===this.listeners(e.EVENT.AUDIO_FRAME).length){let{getPCMAbortCtrlMap:e}=this.room.audioManager;e.forEach((e=>{null==e||e.abort("off")})),e.clear()}return this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(ww(t)?e=t:(e=t.userId,n=!0===t.processed,t.streamType&&(r=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(i=t.remoteAudioTrack)}else i="sub"===r?this._localScreenAudioTrack:this._localAudioTrack;return i?n&&i.outMediaTrack&&i.outMediaTrack!==i.mediaTrack?i.outMediaTrack.clone():i.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main",processed:r=!1}=e,n=null;if(""===t)"main"===i&&this._localVideoTrack&&(n=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(n=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(n="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return n?r&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}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&&e.muteState.hasVideo)return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&null!=e&&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""}_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)))}setCurrentSpeaker(e){return Bb(this,null,(function*(){(yield YV()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),BG=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return Bb(this,null,(function*(){var t;let{userId:i}=e;if(this._remoteAudioConfigMap.has(i))return void this._log.warn("remote audio has already started. userId:".concat(i));let r=this._room.remotePublishedUserMap.get(i);if(!r)return;let n={},o=r.remoteAudioTrack;o.on("decode-failed",(e=>{this.emit(AW.ERROR,new QH({code:qH.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))})),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),s=Nw(r)?r:100;n.volume=s,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(o),LU(_F(o,"decode-failed"),VF(_F(o,Cx.INIT)),UB((()=>{this.startPlugin(OG.Name,{track:o,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:n,track:o}),MM.emit("115",{userId:i,room:this.room}),o.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:o.outMediaTrack,refId:"ra-".concat(i)})}catch(XM){throw this._remoteAudioConfigMap.delete(i),XM}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Bb(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.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),MM.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})}))}_enableVideoDecodeFallback(e,t){let i,r=this._room.videoDecodeFallbackType;r&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),LU(_F(e,"decode-failed"),VF(_F(e,Cx.INIT)),FB((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),fB(_F(e,"decode-downgrade-state-changed")),UB((r=>{i=r.state,this.emit(AW.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Mb(Ob({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return Bb(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),Dw(t)&&n&&n.view&&!Kw(i)){let e=$w(n.view);e.length>0&&(yield r.play(e,i))}if(!Dw(t)){let e=$w(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return Bb(this,arguments,(function(e){var t=this;let{playOption:i={},track:r,prevConfig:n}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(mk){}if(Dw(i.muted)||r.setPlayerMute(i.muted),Dw(i.volume)||r.setAudioVolume(i.volume/100),r instanceof qB&&r.mediaTrack){let e=!1===i.muted&&!Dw(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof MH){let e=i.muted?0:i.volume;if(Dw(e))return;t.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(r.userId),volume:i.volume})}}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===i||(this._mediaTrackMap.set(e.outMediaTrack,i),this.emit(AW.TRACK,{userId:i,streamType:ZH(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,t,i;let r=[];if(null!=(e=this._localAudioConfig)&&e.publish&&this._localAudioTrack&&r.push(this._localAudioTrack),null!=(t=this._localVideoConfig)&&t.publish&&this._localVideoTrack&&r.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),0!==r.length)return Promise.all(r.map((e=>this._room.publish(e).catch((()=>{})))))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(Dw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(ZH(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Pw(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting),t.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),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:n}));let l=new Set($w(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 Bb(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()}))}_stopScreenShare(){return Bb(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let e=[this._localScreenTrack];this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),yield Promise.all(e.map((e=>this._room.unpublish(e).catch((()=>{})))))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(!1===(null==(e=this._localScreenAudioTrack.trackSettings)?void 0:e.echoCancellation)&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Vx(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return Bb(this,null,(function*(){var i,r;if(!e||!t)return;let n=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.echoCancellation)&&("monitor"===n||"browser"===n&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(KM){this._log.warn("start audioProcessor plugin failed: ",KM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!BG||jV(BG))&&(this._initActiveSpeaker(),MM.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return Bb(this,null,(function*(){if(BG&&!jV(BG))this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:BG});else{let e=yield YV();e[0]&&!jV(e[0])?(BG=e[0],this.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):MM.on("102",this._onLocalTrackCaptured,this)}}))}_onAudioAvailable(e){let{userId:t}=e,i=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===i||this._room.autoReceiveAudio&&!i)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:i}=e;if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(t);if(r){let e="main"===i?r.remoteVideoTrack:r.remoteAuxiliaryTrack,t=[e];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&t.push(r.remoteAudioTrack),this._room.subscribe(...t).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:i}=e;i.hasAudio&&i.audioMuted||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){var i;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:Mb(Ob({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),lL.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),lL.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return Bb(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),PG.call(e,Ob({trtcInstance:this},t))}))}static setLogLevel(e,t){UM.setLogLevel(e),Dw(t)||(t?UM.enableUploadLog():UM.disableUploadLog())}static isSupported(){return SL(e.frameWorkType)}static getPermissions(e){return Bb(this,arguments,(function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield VG.request(i).catch((e=>{var t;return UM.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,r]=yield Promise.all([VG.get("camera"),VG.get("microphone")]);return{camera:e,microphone:r}}()}))}static getCameraList(){return KV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return qV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return YV(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return Bb(this,null,(function*(){if(!zN||t!==JH.SPEAKER&&t!==JH.HEADSET)(yield YV()).forEach((e=>{e.deviceId===t&&(FG.forEach((i=>{i._setCurrentSpeaker(t),i.emit(AW.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),BG=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;FG.forEach((e=>Bb(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s,max:a}=e;switch(s&&(cL.version=s),t){case"count":cL.addCount({key:i,useUV:o});break;case"enum":cL.addEnum({key:i,value:r,useUV:o});break;case"number":cL.addNumber({key:i,value:r,split:n,max:a})}}};Ub(HG,"VERSION",GW),Ub(HG,"_loggerManager",UM),Ub(HG,"EVENT",AW),Ub(HG,"ERROR_CODE",qH),Ub(HG,"TYPE",JH),Ub(HG,"frameWorkType",30),Vb([zW({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?null==e?void 0:e.assetsPath:"default"}})})],HG.prototype,"use",1),Vb([jW(hW.TRTC.enterRoom),yW("room",((e,t)=>{let[i]=e,[r]=t;return(i.roomId||i.strRoomId)===(r.roomId||r.strRoomId)&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId})),mU((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),zW()],HG.prototype,"enterRoom",1),Vb([zW()],HG.prototype,"exitRoom",1),Vb([jW(hW.TRTC.switchRoom),zW(),vU()],HG.prototype,"switchRoom",1),Vb([jW(hW.TRTC.switchRole),SW("room",{merge:(e,t)=>t}),zW()],HG.prototype,"switchRole",1),Vb([zW()],HG.prototype,"destroy",1),Vb([jW(hW.TRTC.startLocalAudio),yW("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),zW()],HG.prototype,"startLocalAudio",1),Vb([jW(hW.TRTC.updateLocalAudio),SW("audio",{debounce:{delay:200,getKey:()=>"".concat(UG,"-localAudio"),isNeedToDebounce:e=>{var t;return!Dw(null==(t=e.option)?void 0:t.captureVolume)}}}),zW()],HG.prototype,"updateLocalAudio",1),Vb([IW("audio"),zW()],HG.prototype,"stopLocalAudio",1),Vb([jW(hW.TRTC.startLocalVideo),yW("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),zW()],HG.prototype,"startLocalVideo",1),Vb([jW(hW.TRTC.updateLocalVideo),SW("video"),zW()],HG.prototype,"updateLocalVideo",1),Vb([IW("video"),zW()],HG.prototype,"stopLocalVideo",1),Vb([jW(hW.TRTC.startScreenShare),yW("screen",(()=>!0)),zW()],HG.prototype,"startScreenShare",1),Vb([jW(hW.TRTC.updateScreenShare),SW("screen"),zW()],HG.prototype,"updateScreenShare",1),Vb([zW()],HG.prototype,"stopScreenShare",1),Vb([jW(hW.TRTC.startRemoteVideo),yW((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),zW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HG.prototype,"startRemoteVideo",1),Vb([jW(hW.TRTC.updateRemoteVideo),SW((e=>"v".concat(e.userId).concat(e.streamType))),zW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HG.prototype,"updateRemoteVideo",1),Vb([jW(hW.TRTC.stopRemoteVideo),mU((e=>function(t){return Bb(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)}))})),zW({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],HG.prototype,"stopRemoteVideo",1),Vb([IW((e=>"v".concat(e.userId).concat(e.streamType)))],HG.prototype,"_stopRemoteVideo",1),Vb([jW(...hW.TRTC.muteRemoteAudio),zW({getRemoteId:e=>e})],HG.prototype,"muteRemoteAudio",1),Vb([JW(...hW.TRTC.setRemoteAudioVolume),function(e,t){return mU(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=WW.get(this);s||(s=new Map,WW.set(this,s));let a=t(...n),c=s.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=WW.get(this))||e.delete(a)}),e);s.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=WW.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),zW({getRemoteId:e=>e})],HG.prototype,"setRemoteAudioVolume",1),Vb([XW("start"),hU((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),yW(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),zW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>rL[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],HG.prototype,"startPlugin",1),Vb([XW("update"),SW(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(Qw(e[1],t[1]),e)}),zW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>nL[e.getName()]})],HG.prototype,"updatePlugin",1),Vb([XW("stop"),IW(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),zW({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>oL[e.getName()]})],HG.prototype,"stopPlugin",1),Vb([JW(...hW.TRTC.enableAudioVolumeEvaluation)],HG.prototype,"enableAudioVolumeEvaluation",1),Vb([zW()],HG.prototype,"getVideoSnapshot",1),Vb([zW()],HG.prototype,"_setCurrentSpeaker",1),Vb([yW((e=>"a".concat(e.userId)),(()=>!0))],HG.prototype,"_startRemoteAudio",1),Vb([mU((e=>function(t){return Bb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(Mb(Ob({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),IW((e=>"a".concat(e.userId)))],HG.prototype,"_stopRemoteAudio",1),Vb([IW("room")],HG.prototype,"_exitRoom",1),Vb([IW("screen")],HG.prototype,"_stopScreenShare",1),Vb([jW(...hW.TRTC.sendSEIMessage),WH({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}})],HG.prototype,"sendSEIMessage",1),Vb([jW(hW.TRTC.sendCustomMessage),WH({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],HG.prototype,"sendCustomMessage",1),Vb([jW(hW.TRTC.create)],HG,"_create",1);var WG=HG,GG=class{constructor(){Ub(this,"_set",new Set),MM.on(LM.LEAVE_SUCCESS,this.delete,this),MM.on(LM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}handleSwitchRoomSuccess(e){let{room:t,currentRoomId:i,targetRoomId:r}=e;"rtc"!==t.scene&&(this._set.delete(this.getKey(t.userId,i,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function jG(){return Bb(this,null,(function*(){let e,t;try{let t=yield qV();e=t&&t.length}catch(p){}try{let e=yield KV();t=e&&e.length}catch(p){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=HM.basis(),d={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s,h265Encode:a,h265Decode:c},u={browser:l.browser,os:l.os,trtc:d,devices:i},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};Ux.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),Ux.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),px()}))}var JG=xb(Hb()),qG="1",KG="2",zG="3",YG="4",XG="5",QG="6",ZG="7",$G={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,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,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,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},ej=[$G.UPDATE_REMOTE_MUTE_STAT,$G.UPLINK_NETWORK_STATS,$G.USER_LIST_RES,$G.MUTE_RESULT,$G.SERVER_FIRST_PACKAGE_RECEIVED,$G.RECEIVE_CUSTOM_MSG,$G.UPDATE_NETWORK_TIME_RESULT],tj={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",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-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",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},ij="publish_change",rj="join",nj="leave",oj="quality_report",sj="mute_uplink",aj="publish",cj="publish_state_change",lj="unpublish",dj="subscribe",uj="unsubscribe",hj="subscribe_change",pj="start_publishing",mj="stop_publishing",_j="start_push_user_cdn",fj="stop_push_user_cdn",gj="start_mcu_mix",Ej="stop_mcu_mix",Tj="start_publish_cdn_stream",vj="update_publish_cdn_stream",yj="stop_publish_cdn_stream",Sj="get_user_list",Ij="change_role",Aj="update_constraint_config",Rj="rebuild_pc",Cj="join/v2",bj="publish/v2",kj="subscribe/v3",Dj="ability_status_report",wj="reconnect",Nj="channel_msg",Oj="switch_room",Mj="update_network_time",Pj=new Set;var Lj=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],xj=class extends JG.default{constructor(e){var t,i,r;super(),Ub(this,"room"),Ub(this,"sdkAppId"),Ub(this,"userId"),Ub(this,"userSig"),Ub(this,"url"),Ub(this,"backupUrl"),Ub(this,"destroyed",!1),Ub(this,"_socketInUse"),Ub(this,"_socket"),Ub(this,"_backupSocket"),Ub(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),Ub(this,"_currentState","DISCONNECTED"),Ub(this,"_isReconnecting",!1),Ub(this,"_seq",0),Ub(this,"_log"),Ub(this,"_lastMessageTime",-1),Ub(this,"_connectStartTime",-1),Ub(this,"_stopConnectRetry"),Ub(this,"bytesSent",0),Ub(this,"bytesReceived",0),Ub(this,"keepAlive",!1),Ub(this,"signalDomainWhenUnifiedProxy"),Ub(this,"stopKeepAliveTimeout"),Ub(this,"rtt",0),this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let n=(null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0;null!=(r=this.room.joinParams)&&r.keepAlive&&!n&&(n=1),n-Pj.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Pj.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=UM.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}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)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search);return Lj.forEach((i=>{let r=t.get("trtc_".concat(i));r&&(e+="&".concat(i,"=").concat(encodeURIComponent(r)))})),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 isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return Bb(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(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=Gw();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 Ww(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Hk.BACKUP:Hk.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Hk.MAIN:Hk.BACKUP),t(new ek({code:Zb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.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===Hk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(_D){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(_D){}this._backupSocket=null}}onclose(e){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.startReconnection(),this.room.isJoining&&this.emit(XG,new ek({code:Zb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(Hk.MAIN),this.unbindAndCloseSocket(Hk.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(XG,new ek({code:Zb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=nN(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values($G),o=Object.keys($G)[n.indexOf(i)],s=tj[o]||i;switch(ej.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case $G.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&rk(r.svrTime-(new Date).getTime()),this._log.info("ChannelSetup Success ".concat(Gw()-this._connectStartTime)),lL.addSuccessEvent({key:521701,cost:Gw()-this._connectStartTime}),this._connectStartTime=-1,this.emit(qG,{signalInfo:this._signalInfo});else{let e=new ek({code:Zb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:ZP({key:zP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),lL.addFailedEvent({key:521701,error:e}),this.emit(XG,e)}break;case $G.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.bakRelayIps=r.bakRelayIps,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._signalInfo.reportToken=r.reportToken,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(String(s),{data:t})}}reGetSignalChannelUrl(){return Bb(this,null,(function*(){try{if(!this.room.joinParams)return;DW(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(pk){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Hk.MAIN:Hk.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return Bb(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:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:wj,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:tj.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),lL.addSuccessEvent({key:521702,cost:Gw()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(lL.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(pk){this._log.error(pk),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},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=nN(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=()=>{clearTimeout(d),c(new ek({code:Zb.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(ZG,l);let d=setTimeout((()=>{this.off(n,u),this.off(ZG,l);let e=new ek({code:Zb.API_CALL_TIMEOUT,message:ZP({key:zP.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),u=t=>{t.data.seq===h&&(clearTimeout(d),this.off(n,u),this.off(ZG,l),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,u);let h=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return PN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t,reject:r,error:n}=e;!this.room.isJoined||this.destroyed||n.code===Zb.API_CALL_ABORTED?r(n):this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(zG,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Pj.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Hk.MAIN),this.unbindAndCloseSocket(Hk.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(ZG)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var e;let t=null==(e=this._signalInfo.bakRelayIps)?void 0:e.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(tj.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(tj.JOIN_ROOM_RESULT,t))};this.on(tj.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(KG,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(zG):"DISCONNECTED"===e&&this.emit(QG))}};Vb([Bx({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&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||this.destroyed)&&t())}})],xj.prototype,"connect",1);var Vj=xb(Hb()),Uj=0,Fj=!1,Bj=new Set,Hj=!1,Wj=class{constructor(e){Ub(this,"userId"),Ub(this,"tinyId"),Ub(this,"_sdpSemantics"),Ub(this,"_isUplink"),Ub(this,"_room"),Ub(this,"_log"),Ub(this,"_signalChannel"),Ub(this,"_isErrorObserved",!1),Ub(this,"_waitForPeerConnectionConnectedPromise"),Ub(this,"_waitForPeerConnectionConnectedPromiseReject",null),Ub(this,"_peerConnection",null),Ub(this,"_emitter",new Vj.default),Ub(this,"_currentState","DISCONNECTED"),Ub(this,"_isReconnecting",!1),Ub(this,"_reconnectionCount",0),Ub(this,"_reconnectionTimer",-1),Ub(this,"_isFirstConnection",!0),Ub(this,"_prevTime",-1),Ub(this,"_localAddress"),Ub(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=UM.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Gw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,lL.addSuccessEvent({key:521705,cost:Math.min(Gw()-this._prevTime,3e4)})):this._isReconnecting&&lL.addSuccessEvent({key:521706,cost:Gw()-this._prevTime}),this._prevTime=-1}catch(qM){throw this._isFirstConnection?(this._isFirstConnection=!1,lL.addFailedEvent({key:521705,error:qM})):this._isReconnecting&&this._reconnectionCount>=3&&lL.addFailedEvent({key:521706,error:qM}),qM}}initialize(){let e={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(),Bj.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 ek({code:Zb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return dD;let e=null;if(this._isUplink){if(!FL()||0===this._peerConnection.getSenders().length)return dD;e=this._peerConnection.getSenders()[0].transport}else{if(!UL()||0===this._peerConnection.getReceivers().length)return dD;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:dD}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===uD.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===uD.FAILED||e.target.connectionState===uD.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new ek({message:r,code:Zb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===uD.CONNECTED||e.target.connectionState===uD.COMPLETED)&&(this.logSelectedCandidate(),Ux.logSuccessEvent({userId:this._room.userId,eventType:gD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(Uj=0,Fj=!1,Hj=!0,Bj.add(this)):Bj.delete(this),MM.emit(LM.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 Bb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(DL(t)){let i=e.get(t.localCandidateId),r=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)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.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),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{MM.off(LM.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new ek({code:Zb.API_CALL_TIMEOUT,message:"connection timeout"});var i;Uj+=1,i=this._signalChannel.isConnected,Uj>2&&!Fj&&0===Bj.size&&i&&(this._log.warn("firewall restriction"),Fj=!0,this._emitter.emit("firewall-restriction")),t(e)}),DD);MM.on(LM.LEAVE_SUCCESS,r,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(zG,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=mD()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new ek({code:this._isUplink?Zb.UPLINK_RECONNECTION_FAILED:Zb.DOWNLINK_RECONNECTION_FAILED,message:ZP({key:this._isUplink?zP.UPLINK_RECONNECTION_FAILED:zP.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(zG,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"))}setOffer(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}};Vb([IU(521712,!1)],Wj.prototype,"setOffer",1),Vb([IU(521713,!1)],Wj.prototype,"setAnswer",1);var Gj=xb(Yb()),jj=function(e){return Gj.default.parse(e)},Jj=function(e){return Gj.default.write(e)};function qj(e){return Object.keys(e).filter((t=>e[t]))}var Kj=class e extends Wj{constructor(e){super(Mb(Ob({},e),{isUplink:!1})),Ub(this,"_flag",0),Ub(this,"isRobot",!1),Ub(this,"role","anchor"),Ub(this,"remoteAudioTrack"),Ub(this,"remoteVideoTrack"),Ub(this,"remoteAuxiliaryTrack"),Ub(this,"ssrc",{audio:0,video:0,auxiliary:0}),Ub(this,"_isSDPExchanging",!1),Ub(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new MH(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new PH(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new LH(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}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 zw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.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===Hk.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 r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===$k?Hk.MAIN:Hk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Hk.AUDIO;i.kind===Hk.VIDEO&&(n=r===Hk.MAIN?Hk.VIDEO:Hk.AUXILIARY);let o=this.remoteAudioTrack;n===Hk.VIDEO?o=this.remoteVideoTrack:n===Hk.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=jj(e);return t.media.forEach((e=>{e.type===Hk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),Jj(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=jj(e);return i.media.forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),Jj(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return Bb(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===uD.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===uD.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(mk){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(mk.message," ").concat(JSON.stringify(this.muteState))),new ek({code:Zb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):mk}}))}unsubscribe(e){return Bb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=Ob({},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 n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(r," [").concat(qj(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(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},r=uj,n=tj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=hj,n=tj.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new ek({code:i.code,message:ZP({key:zP.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return Bb(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(_D){throw e.closePeerConnection(!0),_D}}()}))}exchangeSDP(e){return Bb(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,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:dj,commandDesc:"exchange sdp",data:r,responseCommand:tj.SUBSCRIBE_RESULT,timeout:vD});if(!this._peerConnection){let e=new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(_D){throw this._isSDPExchanging=!1,_D}}))}createOffer(){return Bb(this,null,(function*(){let e={voiceActivityDetection:!1};HL()&&this._sdpSemantics===yD?(this._peerConnection.addTransceiver(Hk.AUDIO,{direction:Wk.RECVONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Wk.RECVONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Wk.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield yL();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=jj(e);return t.media.forEach((e=>{var t,i;if(e.type===Hk.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),Jj(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=jj(e);return t.media.forEach((e=>{e.type===Hk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),Jj(t)}(t.sdp),this._sdpSemantics===yD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return Bb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===ID)throw new ek({code:Zb.NOT_SUPPORTED_H264,message:ZP({key:zP.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new ek({code:t,message:ZP({key:zP.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch(KM){throw this._log.error(KM),KM}}))}updateSSRC(e){try{jj(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Hk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes($k)}));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($k)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(eD)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(_D){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return Bb(this,null,(function*(){if(!(Fb(e.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(_D){let t=Cw(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}get audioReceiver(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}};Vb([mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],Kj.prototype,"subscribe",1),Vb([IU(521717,!1)],Kj.prototype,"unsubscribe",1),Vb([hU(Wj.prototype.afterConnect),uU(Wj.prototype.beforeConnect)],Kj.prototype,"connect",1);var zj=Kj,Yj={voiceActivityDetection:!1},Xj=class e extends Wj{constructor(e){super(Mb(Ob({},e),{isUplink:!0})),Ub(this,"localMainAudioTrack",null),Ub(this,"localMainVideoTrack",null),Ub(this,"localAuxAudioTrack",null),Ub(this,"localAuxVideoTrack",null),Ub(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Ub(this,"_isPublishingAux",!1),Ub(this,"_publishingLocalAudioTrack"),Ub(this,"_publishingLocalVideoTrack"),Ub(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}),Ub(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}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,r,n;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==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),HL()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.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||Hk.AUDIO,{direction:Wk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Hk.VIDEO:s||Hk.VIDEO,{direction:Wk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Hk.VIDEO,{direction:Wk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Hk.VIDEO,{direction:Wk.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:Hk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Hk.VIDEO,videoType:o?Hk.AUXILIARY:Hk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Hk.VIDEO,videoType:Hk.SMALL}),e.push(2))}yield t.setTransceiverDirection(Wk.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.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(r)));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),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return Bb(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(Wk.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Wk.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 Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!BL())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=Mb(Ob({},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=Mb(Ob({},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(Wk.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Bb(this,null,(function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:cj,data:t,responseCommand:tj.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:lj,commandDesc:"unpublish",responseCommand:tj.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Zb.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:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),zL){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(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.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),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Aj,data:this._mediaSettings,responseCommand:tj.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Bb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Hk.AUXILIARY:Hk.MAIN," stream")),HL()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return Bb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Hk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Wk.INACTIVE&&(yield this.setTransceiverDirection(Wk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return Bb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;BL()&&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===Hk.VIDEO&&e instanceof XB&&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===SD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=jj(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Hk.VIDEO)return!0;return!1}removeSender(e){let t=null;BL()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&kw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return Bb(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?Hk.AUXILIARY:Hk.MAIN," stream")),HL()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return Bb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Hk.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Wk.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return Bb(this,null,(function*(){if(!ZN)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Wk.INACTIVE,"|").concat(Wk.RECVONLY,"|").concat(Wk.SENDONLY,")")))&&o++,t.includes(o)){if(e===Wk.INACTIVE&&i.includes("a=".concat(Wk.RECVONLY)))return r=!0,"a=".concat(e);if(e===Wk.SENDONLY&&i.includes("a=".concat(Wk.INACTIVE)))return r=!0,"a=".concat(Wk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return Bb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Hk.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===Hk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Hk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return Bb(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=HL()?e.kind===Hk.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?Hk.AUXILIARY:Hk.MAIN," stream")),e.kind===Hk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Hk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return Bb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(Yj);ZN&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this.setOffer(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===Hk.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:ij,data:n,responseCommand:tj.UPDATE_OFFER_RESULT,timeout:TD,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(zM){throw this._log.error(zM),zM}}))}setBandwidth(e){return Bb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!qL())return o?r===Hk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(HL()){let t=0;r===Hk.VIDEO&&(t=n===Hk.SMALL?2:n===Hk.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));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(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Hk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";ZN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Hk.SMALL?n=1:i===Hk.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e))),e}updateAudioBandwidthRestriction(e,t){let i="AS";return ZN&&(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 Bb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(pk){throw this.closePeerConnection(!0),this.uninstallEvents(),pk}}))}exchangeSDP(){return Bb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(pk){throw pk}}))}createOffer(){return Bb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(Yj);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(pk){throw pk}}))}doExchangeSDP(){let e={command:aj,responseCommand:tj.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof RH||this.localAuxVideoTrack instanceof RH,state:this._room.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:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=jj(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),Jj(r)}acceptAnswer(e){return Bb(this,null,(function*(){var t,i,r,n,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==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Hk.AUXILIARY:Hk.BIG;s=yield this.setBandwidth({bandwidth:e,type:Hk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Hk.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:Hk.VIDEO,videoType:Hk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(XM){throw this._log.error("failed to accept remote answer ".concat(XM)),XM}}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(sj,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return Bb(this,null,(function*(){if(!(Fb(e.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:lj,responseCommand:tj.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(_D){let t=Cw(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)&&MM.emit(LM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{jj(e).media.forEach(((e,t)=>{if(e.type===Hk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===SD&&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(_D){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Hk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Hk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Hk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Hk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Hk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===ID?(this._log.error(YP.NOT_SUPPORTED_H264ENCODE),new ek({code:Zb.NOT_SUPPORTED_H264,message:ZP({key:zP.NOT_SUPPORTED_H264ENCODE})})):new ek({code:Zb.UNKNOWN,message:ZP({key:zP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:tj.PUBLISH_RESULT,code:e,message:t}})})}};Vb([mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],Xj.prototype,"publish",1),Vb([IU(521715,!1)],Xj.prototype,"unpublish",1),Vb([hU(Wj.prototype.afterConnect),uU(Wj.prototype.beforeConnect)],Xj.prototype,"connect",1);var Qj=Xj,Zj=class{constructor(e,t){this.room=e,Ub(this,"_log"),Ub(this,"_prevReportTime",0),Ub(this,"_prevReport",{}),Ub(this,"_prevStats",null),Ub(this,"_prevEncoderImplementation",""),Ub(this,"_prevAuxEncoderImpl",""),Ub(this,"_prevQualityLimitationReason",""),Ub(this,"_prevAuxQualityLimitationReason",""),Ub(this,"_prevDecoderImplementationMap",new Map),Ub(this,"_decodeMap",new Map),Ub(this,"totalBytesSent",0),Ub(this,"totalBytesReceived",0),Ub(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return Bb(this,null,(function*(){var t;let i={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},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s,a,c,l,d,u,h;let p,m;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Hk.VIDEO){if(t.ssrc===n.video?(p=Hk.VIDEO,m=e.localMainVideoTrack):t.ssrc===n.small?p=Hk.SMALL:t.ssrc===n.auxiliary&&(m=e.localAuxVideoTrack,p=Hk.AUXILIARY),!p)return;if(i[p].bytesSent=t.bytesSent,i[p].packetsSent=t.packetsSent,i[p].framesEncoded=t.framesEncoded,Dw(t.keyFramesEncoded)||(i[p].keyFramesEncoded=t.keyFramesEncoded),Dw(t.nackCount)||(i[p].nackCount=t.nackCount),Dw(t.pliCount)||(i[p].pliCount=t.pliCount),Dw(t.retransmittedPacketsSent)||(i[p].retransmittedPacketsSent=t.retransmittedPacketsSent),Dw(t.totalEncodeTime)||(i[p].totalEncodeTime=t.totalEncodeTime),Dw(t.totalPacketSendDelay)||(i[p].totalPacketSendDelay=t.totalPacketSendDelay),!Dw(t.encoderImplementation)&&(p===Hk.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||p===Hk.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;p===Hk.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),MM.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[p===Hk.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(p===Hk.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!Dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),MM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!Dw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),MM.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else if("candidate-pair"===t.type)DL(t)&&(this.totalBytesSent=t.bytesSent,Nw(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime)));else if("media-source"===t.type)if(t.kind===Hk.AUDIO)i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,Dw(null==(c=null==(a=null==(s=e.localMainAudioTrack)?void 0:s.sourceTrack)?void 0:a.stats)?void 0:c.deliveredFramesDuration)?t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration):i.audio.totalSamplesDuration=e.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(t.kind===Hk.VIDEO)if(t.trackIdentifier===e.getVideoTrackId(Hk.VIDEO))if(null!=(u=null==(d=null==(l=e.localMainVideoTrack)?void 0:l.sourceTrack)?void 0:d.stats)&&u.deliveredFrames){let{deliveredFrames:r}=e.localMainVideoTrack.sourceTrack.stats;i.video.framesCaptured=r,e.localMainVideoTrack.stat.framesCaptured&&e.localMainVideoTrack.stat.framesCaptured>0&&r>=e.localMainVideoTrack.stat.framesCaptured?i.video.fpsCapture=Math.floor((r-e.localMainVideoTrack.stat.framesCaptured)/this.statInterval):i.video.fpsCapture=t.framesPerSecond}else i.video.fpsCapture=t.framesPerSecond;else t.trackIdentifier===e.getVideoTrackId(Hk.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond;if(!Dw(t.audioLevel)&&null!=(h=e.localMainAudioTrack)&&h.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!Dw(t.frameWidth)){let r=Hk.SMALL;t.trackIdentifier===e.getVideoTrackId(Hk.VIDEO)||t.ssrc===n.video?r=Hk.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Hk.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Hk.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel(),r=e.localMainAudioTrack.getInternalAudioLevelAfter3A();i.audio.audioCaptureEnergyAfter3a=r,i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===Hk.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Hk.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Hk.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(mk){this._log.warn("failed to getStats on sender connection ".concat(mk))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return Bb(this,null,(function*(){var t,i,r;let n={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,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{var i,o;if("codec"===t.type&&this._decodeMap.set(t.id,t),"inbound-rtp"===t.type){let c=(t.mediaType||t.kind)===Hk.AUDIO;if(c){if(t.ssrc!==r.audio||!s.hasAudio)return;n.audio.packetsReceived=t.packetsReceived,n.audio.bytesReceived=t.bytesReceived,n.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(n.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(n.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(n.audio.concealedSamples=t.concealedSamples),t.silentConcealedSamples&&(n.audio.silentConcealedSamples=t.silentConcealedSamples);let{remoteAudioTrack:i}=e;i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,n.audio.p2pDelay=i.stat.end2EndDelay,n.hasAudio=!0}else{if(ZN&&0===t.bytesReceived)return;let c;t.ssrc===r.video&&s.hasVideo&&(n.video.packetsReceived=t.packetsReceived,n.video.bytesReceived=t.bytesReceived,n.video.packetsLost=t.packetsLost,n.video.framesReceived=t.framesReceived,n.video.framesDecoded=t.framesDecoded,n.video.fpsDecoded=t.framesPerSecond,n.hasVideo=!0,e.videoCodec=UP[null==(i=this._decodeMap.get(t.codecId))?void 0:i.mimeType.split("/")[1]]||"h264",n.video.codec=e.videoCodec,c=e.remoteVideoTrack,s.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation,"(").concat(e.videoCodec,") HWDecoder: ").concat(t.powerEfficientDecoder)),MM.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,c=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=c.stat.end2EndDelay,n.hasAuxiliary=!0,n.video.codec=(null==(o=this._decodeMap.get(t.codecId))?void 0:o.mimeType.split("/")[1].toLowerCase())||"h264"),c&&(c.stat.packetsReceived=t.packetsReceived,c.stat.bytesReceived=t.bytesReceived,c.stat.packetsLost=t.packetsLost,c.stat.framesReceived=t.framesReceived,c.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=c.stat.end2EndDelay)}t.jitterBufferDelay&&(c?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&DL(t)&&(this.totalBytesReceived=t.bytesReceived,Nw(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));Dw(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===r.video)&&(n.video.frameWidth=t.frameWidth,n.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===r.auxiliary)&&(n.auxiliary.frameWidth=t.frameWidth,n.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!Dw(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=t.audioLevel||0,n.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===n.audio.audioLevel&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),Dw(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),Dw(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(KM){this._log.warn("failed to getStats on receiver connection ".concat(KM))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return Bb(this,null,(function*(){let i,r={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:r,receiverStats:n};let t=Gw(),i=yield e.getStats(),o=Gw();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);i.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(r=yield this.getSenderStats(e));for(let[e,o]of t){let e=yield this.getReceiverStats(o);n.push(e)}return t.size&&(i=this.getMediaPlayoutStats(this._spcStats)),{senderStats:r,receiverStats:n,mediaPlayoutStats:i}}))}getDifferenceValue(e,t){if(oU(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r,uplinkConnection:n}=e;var o,s,a,c,l,d,u,h,p;if(!oU(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*PP,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*PP),Dw(t.senderStats.audio.audioCaptureEnergyAfter3a)||(e.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*PP),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];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};r.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};r.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};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:m}=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=r.get("".concat(e.userId,"_").concat(tD)),n=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:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount,uint32_video_p2p_delay:e.video.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(iD)),n=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:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount,uint32_video_p2p_delay:e.auxiliary.p2pDelay,uint32_video_codec:e.video.codec};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)})),t.mediaPlayoutStats&&!oU(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let _=this._prevReport,f=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&_.msg_up_stream_info.msg_audio_status){let e=_.msg_up_stream_info.msg_audio_status,r=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)r.uint32_audio_codec_bitrate=0;else{let t=this.getDifferenceValue(e.uint32_audio_codec_bitrate,r.uint32_audio_codec_bitrate);r.uint32_audio_codec_bitrate=Math.round(8*t/m),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=r.uint32_audio_codec_bitrate}null!=(o=_.msg_device_info)&&o.uint32_audio_capture_cost?(i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(_.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/m),i.msg_device_info.uint32_audio_capture_cost>0&&(null==(a=null==n?void 0:n.localMainAudioTrack)||a.updateAfter3aSilenceStartTime(null!=(s=t.senderStats.audio.audioCaptureEnergyAfter3a)?s:t.senderStats.audio.micAudioLevel))):delete i.msg_device_info.uint32_audio_capture_cost}let g=_.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=g.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 r=0,n=0,o=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,o=t.uint32_video_codec_fps);let s=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*s/m),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/m),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_codec_fps)/m),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),Dw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),Dw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),Dw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),Dw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),Dw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/m)),Dw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/m))}));let E=_.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>E.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let T=i.msg_down_stream_info;if(T.forEach((e=>{let t=E.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(oU(e.msg_audio_status)||oU(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.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(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let o=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);o&&(o.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let s=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*s/m),i.uint32_audio_total_bitrate=Math.round(8*s/m)}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)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,o=t.uint32_video_codec_bitrate,s=t.uint32_video_receive_fps,a=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let c=this.getDifferenceValue(o,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/m);let l=this.getDifferenceValue(s,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(l/m),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_dec_fps)/m);let d=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/d)||0}))}})),!Dw(null==(c=null==f?void 0:f.mediaPlayoutStats)?void 0:c.totalSamplesDuration)&&!Dw(null==(l=t.mediaPlayoutStats)?void 0:l.totalSamplesDuration)){let e=2*Math.floor(this.getDifferenceValue(null==(d=null==f?void 0:f.mediaPlayoutStats)?void 0:d.synthesizedSamplesDuration,null==(u=t.mediaPlayoutStats)?void 0:u.synthesizedSamplesDuration)/m),r=2*Math.floor(this.getDifferenceValue(null==(h=null==f?void 0:f.mediaPlayoutStats)?void 0:h.totalSamplesDuration,null==(p=t.mediaPlayoutStats)?void 0:p.totalSamplesDuration)/m);i.msg_device_info.uint32_audio_play_cost=r-e}return f&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=f.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=(e.audio.silentConcealedSamples||0)-(t.audio.silentConcealedSamples||0),r=e.audio.concealedSamples-t.audio.concealedSamples,n=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,o=Math.floor((r-i)/n*1e3*m);if(o>1e3*m/5){let t=T.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=o)}}}})),i.msg_down_stream_info.forEach((e=>{e.msg_video_status.forEach((e=>{0===e.uint32_video_codec_bitrate&&0===e.uint32_video_receive_fps&&(e.uint32_video_width=0,e.uint32_video_height=0)}))})),i}getStatsReport(e){return Bb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},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,uint32_audio_capture_energy_after3a: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_cache_ms:0,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,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n,uplinkConnection:i}),t._prevReportTime=Date.now(),e}()}))}getMediaPlayoutStats(e){let t;if(Pw(e)){for(let i of e)if("media-playout"===i.type){let{synthesizedSamplesDuration:e,totalSamplesDuration:r}=i;t={synthesizedSamplesDuration:e,totalSamplesDuration:r};break}return t}}reset(){var e;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,null!=(e=this.room.localMainVideoTrack)&&e.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}},$j=xb(Hb());function eJ(e){return new Promise((t=>Bb(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(mk){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=Mb(Ob({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var tJ=class e extends $j.default{constructor(e){let{signalChannel:t,room:i}=e;super(),Ub(this,"_room"),Ub(this,"_signalChannel"),Ub(this,"_log"),Ub(this,"uplinkRTT",0),Ub(this,"uplinkLoss",0),Ub(this,"downlinkRTT",0),Ub(this,"downlinkLoss",0),Ub(this,"pingResults",{}),Ub(this,"_downlinkPrevStatMap",new Map),Ub(this,"_downlinkLossAndRTTMap",new Map),Ub(this,"_interval",-1),Ub(this,"_uplinkNetworkQuality",0),Ub(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=UM.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," ws-rtt: ").concat(this._signalChannel.rtt)),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," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(tj.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(KG,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return Bb(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)===uD.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].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 this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return Bb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!UL())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&&Nw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Hk.AUDIO||e.mediaType===Hk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(QM){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!==uD.DISCONNECTED&&e.connectionState!==uD.FAILED&&e.connectionState!==uD.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=Ox.run("ric",(()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];MM.emit(LM.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:i});let r=null==(t=this._room.scheduleResult.config)?void 0:t.pingDomainInfo,n={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};r&&(n=Mb(Ob({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(e.EVENT_NETWORK_QUALITY,n);let o=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&o-e.lastPingTime>1e3*r.interval){e.lastPingTime=Date.now();let t=r.domain.map((e=>eJ(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(t).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=o,this.pingResults.data=e,e.forEach((e=>{lL.addSuccessEvent({key:521718,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(Ox.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:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}};Ub(tJ,"EVENT_NETWORK_QUALITY","0"),Ub(tJ,"lastPingTime",0);var iJ=tJ;var rJ=class{constructor(e){Ub(this,"_frameWorkType"),Ub(this,"_component"),Ub(this,"_language"),Ub(this,"connectionType"),Ub(this,"_room"),Ub(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),Ub(this,"_keyPrefix"),Ub(this,"_log"),Ub(this,"_intervalId"),Ub(this,"_firstPublishedUserList"),Ub(this,"_networkQuality"),Ub(this,"_basicInfo"),Ub(this,"_pathJoinRoom"),Ub(this,"_pathLeaveRoom"),Ub(this,"_pathMainVideoMap"),Ub(this,"_pathMainAudioMap"),Ub(this,"_pathAuxiliaryMap"),Ub(this,"_remoteStreamStatMap"),Ub(this,"_localStreamStat"),Ub(this,"_eventMap",new Map),Ub(this,"_captureCostSum",0),Ub(this,"_captureCostCount",0),Ub(this,"isDestroyed",!1),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=UM.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&kw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Vw(o)?o.catch((e=>UM.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(_D){UM.error("".concat(t.name,"() error observed ").concat(_D))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:uk,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,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,SM().then((()=>{this._basicInfo.string_os_version=wM(),this._basicInfo.string_device_name=AM()||this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),MM.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(LM.JOIN_START,this.handleJoinStart).addEvent(LM.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(LM.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(LM.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(LM.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(LM.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(LM.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(LM.JOIN_FAILED,this.handleJoinFailed).addEvent(LM.LEAVE_START,this.handleLeaveStart).addEvent(LM.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(LM.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(LM.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(LM.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(LM.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(LM.PUBLISH_START,this.handlePublishStart).addEvent(LM.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(LM.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(LM.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(LM.PLAY_TRACK_START,this.handlePlayStart).addEvent(LM.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(LM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===Hk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(LM.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(LM.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(LM.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(LM.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(LM.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(LM.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(LM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(LM.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("pagehide",this.handleUnload),this._eventMap.forEach(((e,t)=>MM.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),Ox.clearTask(this._intervalId),0===this._pathJoinRoom.uint64_start_time&&(this._room=null),this.isDestroyed=!0}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()),e.params&&(Dw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Dw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),Dw(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:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,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 ek?Number(i.getExtraCode()||i.getCode()):Zb.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){var t;if(this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time){if(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;let e=null==(t=this._room.audioManager.localAudioTrack)?void 0:t.after3aSilenceStartTime;e&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Gw()-e)}else 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())}handleSwitchRoomStart(e){if(this.hitTest(e.room)){let e=Date.now();this.report().then((()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e}))}}handleSwitchRoomSuccess(e){let{room:t}=e;if(this.hitTest(t)&&0===this._pathJoinRoom.uint64_end_time){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(e){let{room:t,error:i}=e;if(this.hitTest(t)){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,i&&(this._pathJoinRoom.int32_end_ret=i instanceof ek?Number(i.getExtraCode()||i.getCode()):Zb.UNKNOWN)}}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={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:Mb(Ob({},oJ),{msg_user_info:new sJ({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new sJ({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.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&&n.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&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(n){let{statsToReport:t}=n;if(t.uint32_video_render_first||"main"!==e.streamType?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){let e=i-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,lL.addNumber({key:516820,value:e})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=i)}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:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,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;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/PP*100)>0&&(this._localStreamStat.totalAudioLevel+=e/PP,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&null!=o&&o.remoteVideoTrack.isSubscribed||i&&null!=o&&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*wb(10,6)))}})),!Kw(i)){let e="".concat(n,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=o&&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/PP*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/PP,t.audioLevelCount++),i.uint32_audio_block_time&&(t.statsToReport.uint32_audio_block_time+=i.uint32_audio_block_time))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),0===t.uint32_audio_capture_cost&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}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,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof ek?i.getExtraCode()||i.getCode():Zb.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,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=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Jk))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&zk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Kk))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),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,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),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:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Hk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Hk.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,nJ));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),e.statsToReport.uint32_audio_block_time=Math.min(e.statsToReport.uint32_audio_block_time,e.statsToReport.uint32_audio_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})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>nJ&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+nJ):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>nJ&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+nJ):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>nJ&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+nJ)}getReportData(){this._basicInfo.uint32_networkType=fw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new sJ({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Xw(this._signalInfo.relayIp),uint32_client_ip:Xw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*wb(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:Xw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return cN(e),e}report(){return Bb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(qM){this._log.warn(qM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return Bb(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=xM.enable?EN(e,2001,t):yield bN(e),r=i instanceof ArrayBuffer,n="".concat(uw(t,Dk.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(lL),this.uploadKVStat(cL)];o||s.push(CN({url:n,body:i,priority:"low"})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return Bb(this,null,(function*(){let t=e.getReportData(this._room.userSig,this._signalInfo.reportToken);if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=Mb(Ob({},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=xM.enable?EN(t,2003,this._room.sdkAppId):yield bN(t),r=i instanceof ArrayBuffer,n="".concat(uw(+this._room.sdkAppId,Dk.KV_STAT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||CN({url:n,body:i})}))}};Vb([Bx({settings:{timeout:500,retries:3}})],rJ.prototype,"upload",1);var nJ=5e3,oJ={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_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},sJ=class{constructor(e){Ub(this,"str_identifier"),Ub(this,"str_tinyid"),Ub(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},aJ=rJ,cJ=class{constructor(){Ub(this,"_startTime"),Ub(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Gw())}stop(){0===this._endTime&&(this._endTime=Gw())}getDuration(){return 0===this._endTime?Gw()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},lJ=class{constructor(e){Ub(this,"_room",null),Ub(this,"_durationMap"),Ub(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(LM.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(LM.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(LM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_main"),Hk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_main"),Hk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_auxiliary"),Hk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Hk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Hk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Hk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>MM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>MM.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{track:t}=e;if(!this.hitTest(t.room))return;let{userId:i,streamType:r,kind:n}=t;t.isSubscribed?this.addDuractionItem(i,n,r):this.stopDurationItem("".concat(i,"_").concat(r),n)}handleUnsubscribed(e){let{track:t}=e;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new cJ,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Hk.AUDIO?[n]:[],video:t===Hk.AUDIO?[]:[n]})}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()}},dJ=class{constructor(){Ub(this,"renderFreezeMap",new Map),Ub(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?"data"===t?r:i:(rM||ZN)&&i&&r&&i.duration>r.duration?i:r}set(e,t,i){"data"===i?this.dataFreezeMap.set(e,t):this.renderFreezeMap.set(e,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},uJ=class{constructor(e){Ub(this,"_room"),Ub(this,"_renderFreezeMap",new Map),Ub(this,"_isVideoPlayingEventFiredMap",new Map),Ub(this,"_dataFreezeMap",new Map),Ub(this,"_monitorFreezeData",new dJ),Ub(this,"_eventMap",new Map),Ub(this,"_videoEncodeFailedCount",0),Ub(this,"_audioEncodeFailedCount",0),Ub(this,"_encodeFailedThreshold",3),Ub(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(LM.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(LM.PLAY_TRACK_START,this.onPlayTrackStart).set(LM.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(LM.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}})).set(LM.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===Hk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Hk.MUTE?this.onVideoTrackMuted(t):r===Hk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(LM.HEARTBEAT_REPORT,this.onHearBeatReport).set(LM.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(LM.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach(((e,t)=>MM.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>MM.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,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new cJ;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{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,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;if(this.hitTest(t)){if(i.msg_up_stream_info.msg_video_status){let e=i.msg_up_stream_info.msg_video_status,t=Array.from(this._room.localTracks).find((e=>"video"===e.kind&&!e.isScreen)),r=(null==t?void 0:t.stat.bytesSent)||0;if(!1===(null==t?void 0:t.isMediaTrackActive)||r<=0)return;e.forEach((e=>{2===e.uint32_video_stream_type&&(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=t&&t.isPublished?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&(Ux.uploadEvent({userId:this._room.userId,log:"stat-".concat(gD.VIDEO_ENCODE_FAILED_DURING_CALL)}),this._videoEncodeFailedCount=0)):this._videoEncodeFailedCount=0)}))}if(i.msg_up_stream_info.msg_audio_status){let e=i.msg_up_stream_info.msg_audio_status,t=Array.from(this._room.localTracks).find((e=>"audio"===e.kind)),r=(null==t?void 0:t.stat.bytesSent)||0;if(!1===(null==t?void 0:t.isMediaTrackActive)||r<=0)return;0===e.uint32_audio_codec_bitrate&&null!=t&&t.isPublished?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&(Ux.uploadEvent({userId:this._room.userId,log:"stat-".concat(gD.AUDIO_ENCODE_FAILED_DURING_CALL)}),this._audioEncodeFailedCount=0)):this._audioEncodeFailedCount=0}}}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();if(s>RD){let e=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:e?e.duration+s:s},"data")}else n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==Hk.VIDEO||!t.isRemotePublished)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()<RD&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t={renderFreeze:0,count:0},i=this._renderFreezeMap.get(e);return i&&(t.renderFreeze=i.totalDuration,t.count=i.count),t}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}onRemoteVideoPlayStart(e){let{track:t,player:i}=e;var r;if(!lx())return;let n=0,o=()=>{document.hidden||(n=0)};document.addEventListener("visibilitychange",o);let s=(e,r)=>{var o;if(n){let e=t.decodeFPS,i=e>0&&e<=5?600+1e3/e:600,o=r.presentationTime-n;if(o>i){o=Math.min(o,5e3);let e="".concat(t.userId,"_").concat(t.streamType),i=this._monitorFreezeData.get(e,"render");i?i.duration+=o:this._monitorFreezeData.set(e,{userId:t.userId,type:t.streamType,duration:o},"render");let r=this._renderFreezeMap.get(e);r?(r.totalDuration+=o,r.count+=1):this._renderFreezeMap.set(e,{userId:t.userId,type:t.streamType,totalDuration:o,count:1})}}n=r.presentationTime,null==(o=i.element)||o.requestVideoFrameCallback(s)};null==(r=i.element)||r.requestVideoFrameCallback(s),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:o})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),n=this.eventListenerMap.get(r);n&&document.removeEventListener("visibilitychange",n.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},hJ=xb(Hb(),1),pJ=class{constructor(e,t,i,r,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,this.logger=n,Ub(this,"animationState"),Ub(this,"originalAspect"),Ub(this,"totalOffsetX",0),Ub(this,"totalOffsetY",0),Ub(this,"defaultScaleRatio",.1),Ub(this,"isRecovering",!1),Ub(this,"boundaryY",280),Ub(this,"lastActionTime",0),Ub(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=o||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}addEvent(e,t,i){let r=[{key:570704,error:null!=i?i:t?void 0:11},{key:570705,error:null!=i?i:t?void 0:22}][e-1];r&&(t?lL.addSuccessEvent({key:r.key}):lL.addFailedEvent({key:r.key,error:r.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:i,videoHeight:r}=e;this.animationState.debounceThreshold=i/30,this.animationState.movementThreshold=i/20,this.boundaryY=.6*r;try{let e=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(e.detections.length<=0)return void(1===this.vbMode&&this.recoverOriginal(i,r));let t=e.detections[0].boundingBox,n=t.originX,o=t.originY,s=t.width,a=t.height;1===this.vbMode?this.dualStageCropping(i,r,n,o,s,a):2===this.vbMode&&this.movingPortrait(i,r,n,o,s,a)}catch(QM){this.logger.error(QM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let n,o;return e>t/2?(n=t-i-r,o=i-n):(n=i,o=0),{min:n,offset:o}}calculateTargetPosition(e,t,i,r,n,o){let s,a,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,l=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(l,n,e,i),{min:p,offset:m}=this.calculateBoundary(d,o,t,r);return s=2*u+i,a=2*p+r,s/a>this.originalAspect?(s=a*this.originalAspect,h=l-s/2):(a=s/this.originalAspect,m=d-a/2),i/n>c&&(h=0,m=0,s=n,a=o),h=Math.max(0,Math.min(h,n-s)),m=Math.max(0,Math.min(m,o-a)),{sx:h,sy:m,cropWidth:s,cropHeight:a,timestamp:Date.now()}}processFacePositionCrop(e,t,i){if(!this.animationState.current||!this.animationState.target){let e={sx:0,sy:0,cropWidth:t,cropHeight:i,timestamp:Date.now()};return this.animationState.current=e,void(this.animationState.target=e)}let r=this.positionDistance(this.animationState.target,e),n=this.positionDistance(this.animationState.current,e),o=this.animationState.current.cropWidth/t;r>this.animationState.debounceThreshold*o&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&n>this.animationState.movementThreshold*o&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}processFacePositionPortrait(e){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=Ob({},e),void(this.animationState.target=Ob({},e));let t=this.positionDistance(this.animationState.current,e),i=this.positionDistance(this.animationState.target,e);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&i>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout((()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0}),this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),i=e=>e<.5?2*e*e:(4-2*e)*e-1;if(this.animationState.current&&this.animationState.target){let e=(this.animationState.target.sx-this.animationState.current.sx)*i(t);this.animationState.current.sx+=e,this.totalOffsetX+=e;let r=(this.animationState.target.sy-this.animationState.current.sy)*i(t);if(this.animationState.current.sy+=r,this.totalOffsetY+=r,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*i(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*i(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*i(t)),Nw(this.animationState.current.scaleOffsetX)&&Nw(this.animationState.target.scaleOffsetX)&&Nw(this.animationState.current.scaleOffsetY)&&Nw(this.animationState.target.scaleOffsetY)){let e=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*i(t);this.animationState.current.scaleOffsetX+=e;let r=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*i(t);this.animationState.current.scaleOffsetY+=r}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(wb(e.sx-t.sx,2)+wb(e.sy-t.sy,2))}recoverOriginal(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(e,t,i,r,n,o){let s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let a=this.calculateTargetPosition(i,r,n,o,e,t);this.processFacePositionCrop(a,e,t),n*o/a.cropWidth/a.cropHeight>s&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,n,o){var s,a,c,l,d,u,h,p,m,_,f,g;let E={sx:i+n/2+this.totalOffsetX,sy:r+o/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(a=null==(s=this.animationState.current)?void 0:s.scaleRatio)?a:1,scaleOffsetX:null!=(l=null==(c=this.animationState.current)?void 0:c.scaleOffsetX)?l:0,scaleOffsetY:null!=(u=null==(d=this.animationState.current)?void 0:d.scaleOffsetY)?u:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+o/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(p=null==(h=this.animationState.target)?void 0:h.scaleRatio)?p:1,scaleOffsetX:null!=(_=null==(m=this.animationState.target)?void 0:m.scaleOffsetX)?_:0,scaleOffsetY:null!=(g=null==(f=this.animationState.target)?void 0:f.scaleOffsetY)?g:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(n*o/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(E)}set aspectRatio(e){this.originalAspect=e}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}},mJ=class extends dH{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log}),Ub(this,"_bgTexture"),Ub(this,"_waterMarkTexture"),Ub(this,"_lastMaskTexture"),Ub(this,"_lastMaskFbo"),Ub(this,"_textureValid",!1),Ub(this,"_selfieTextureValid",!1),Ub(this,"_selfieSegmentationHash"),Ub(this,"wasm"),Ub(this,"predictReady"),Ub(this,"_color"),Ub(this,"_prePrograme"),Ub(this,"_segmentationMask"),Ub(this,"_weixin",!1),Ub(this,"_centerFace"),Ub(this,"_textureMatrixLocation"),Ub(this,"_offsetMatrixLocation"),Ub(this,"_colorLocation"),Ub(this,"_enableFaceCentering",!1),Ub(this,"_enableEffectOptimization",!1),Ub(this,"_mat4"),Ub(this,"_postProcessing"),Ub(this,"_onAbort"),Ub(this,"_visionTaskRegistry"),Ub(this,"resolvePreditReady"),this.init(t).catch((t=>{e.log.error(t),e.destroy(new ek({code:Zb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return Bb(this,null,(function*(){var t,i,r;this.predictReady=new Promise((e=>{this.resolvePreditReady=e}));let n=e.Wasm,o=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)&&i,this.wasm=new n.AllIn1(o),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"color"===e.bg?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:t,brightness:i,ruddy:r}=e.beautyParams;this.wasm.setBeauty(t,i,r,null==e?void 0:e.width,null==e?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=o.getUniformLocation(this.program,"u_textureMatrix"),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=o.getUniformLocation(this.program,"u_offsetMatrix"),o.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=o.getUniformLocation(this.program,"u_color"),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(o.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),t=this.context.createShader(o.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(t,e),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||2!==this.wasm.vbMode&&3!==this.wasm.vbMode?this._postProcessing=void 0:vM()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(r=this._postProcessing)||r.init(o,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)}))}initVisionTasks(e){return Bb(this,null,(function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new pJ(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(_D){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}}))}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let i=this.getMaskTexture(e);if(!i)return;let r=i;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,r=this._postProcessing.postProcessing(i)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),3===this.wasm.vbMode&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),mN(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:i}=this;this.tryVideoFrameCallback();let{videoWidth:r,videoHeight:n}=i;if(mN(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,n]=[n,r]),0===r||0===n||!this.available)return!1;i.width=r,i.height=n;let o=!1;if(this.totalFrames)this.useTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),o=this._textureValid,this._textureValid=!0}if(this.width===r&&this.height===n&&o?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i)),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let e=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,e||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,r,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let e=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);1===this.totalFrames&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(e)}}catch(XM){this._onAbort&&this._onAbort(XM)}return 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)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:i}=this._centerFace;if(t&&(1===this.wasm.vbMode&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),i&&2===this.wasm.vbMode)){if(!this._mat4)return;let r=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:o=0,scaleOffsetY:s=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+o,s,0]),this._mat4.scale(r,r,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){let n=this.context.ctx;if(!this._mat4)return;let{width:o,height:s}=n.canvas,a=this._mat4.create();this._mat4.fromTranslation(a,[e/o,1-(t+r)/s,0]),this._mat4.scale(a,a,[i/o,r/s,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,a)}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),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),null==(e=this.wasm)||e.close()}},_J=class extends tH{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:"\n precision highp float;\n uniform sampler2D ySampler;\n uniform sampler2D uSampler;\n uniform sampler2D vSampler;\n varying highp vec2 textureCoord;\n const mat4 YUV2RGB = mat4(\n 1.1643828125, 0, 1.59602734375, -.87078515625,\n 1.1643828125, -.39176171875, -.81296875, .52959375,\n 1.1643828125, 2.017234375, 0, -1.081390625,\n 0, 0, 0, 1);\n void main() {\n vec3 yuv;\n yuv.r = texture2D(ySampler, textureCoord).r;\n yuv.g = texture2D(uSampler, textureCoord).r;\n yuv.b = texture2D(vSampler, textureCoord).r;\n gl_FragColor = vec4(yuv,1) * YUV2RGB;\n }\n ",vertexShaderSource:"\n attribute vec4 vertexPos;\n attribute vec2 texturePos;\n varying vec2 textureCoord;\n void main() {\n gl_Position = vertexPos;\n textureCoord = texturePos;\n }"}),Ub(this,"yTextureRef"),Ub(this,"uTextureRef"),Ub(this,"vTextureRef"),Ub(this,"Y"),Ub(this,"U"),Ub(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let i=this.context.ctx,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_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.bindTexture(i.TEXTURE_2D,null),i.uniform1i(i.getUniformLocation(this.program,e),t),r}render(e){let t=this.context.ctx,i=this.width,r=this.height;return this.useProgram(),t.viewport(0,0,i,r),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i,r,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let i=this.context.ctx;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.yTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e,t,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,this.uTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.vTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null)}},fJ=(e,t)=>{switch(e){case"webCodecs":return"videoFrame"===t?514705:514706;case"wasm":return"webgl"===t?514707:"videoFrame"===t?514708:514709}throw new Error("decoder type not supported")};var gJ=0,EJ=class{constructor(e){Ub(this,"id",gJ++),Ub(this,"trackDoneOB"),Ub(this,"startOB"),Ub(this,"stopOB"),Ub(this,"decoder"),Ub(this,"videoContext"),Ub(this,"gop",0),Ub(this,"gop_helper",0),Ub(this,"waitFirstKeyFrame",!0),Ub(this,"startTimestamp",0),Ub(this,"startTime",0),Ub(this,"startPerformanceTime",0),Ub(this,"inputFrameCount",0),Ub(this,"decodedFrameCount",0),Ub(this,"decodeFrameCount",0),Ub(this,"downgradeLevel",0),Ub(this,"lastDowngradeTime",0),Ub(this,"lastFrameDiff",0),Ub(this,"lastDecodeFrameTimestamp",0),Ub(this,"config"),Ub(this,"gop_before_configure",[]),Ub(this,"videoElement"),Ub(this,"type","wasm"),Ub(this,"goodType"),Ub(this,"renderer","2d"),Ub(this,"wasmOption"),Ub(this,"createDecoder"),Ub(this,"_decodeSink"),Ub(this,"isReported",!1),Ub(this,"track"),Ub(this,"stateChangeOB"),Ub(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=iF(),this.track=t,this.createDecoder=i,this.wasmOption={yuvMode:"webgl"===e.renderer,wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=_F(t.availableState,Cx.OFF),this.stopOB=iF(),"auto"===e.type){switch(e.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode="webgl"===this.renderer}else this.type=e.type;this.changeRenderer(this.renderer),LU(this.stateChangeOB,oB(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),VF(this.stopOB),UB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=LU(this.pipe(this.track),VF(this.stopOB),GU());LU(t,UB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),lL.addFailedEvent({key:fJ(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),lL.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.start(e+1)}}),(()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),lL.addSuccessEvent({key:fJ(this.type,this.renderer)}),lL.addSuccessEvent({key:514704})}))),LU(t,xF(1),UB((()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.start()}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,"videoFrame"===this.renderer&&!EL()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;if(this.failedReason)return;this.inputFrameCount++;let n=new Uint8Array(e.data);if(0!==(o=n)[0]||0!==o[1]||0!==o[2]||1!==o[3]||n.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(n.subarray(0,5))),e;var o;let s=!1;switch(31&n[4]){case 5:case 7:s=!0}if("configured"!==(null==(i=this.decoder)?void 0:i.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach((e=>this.decode(e,!0))),this.gop_before_configure=[]);let{timestamp:a}=e;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!s)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=a,this.startTime=Date.now(),this.startPerformanceTime=Gw()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(a," ").concat(null==(r=e.getMetadata)?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=a,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}checkDowngradeByFrameDiff(){let e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(e){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(e){return t=>Bb(this,null,(function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer((()=>{var t;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),null==i||i.close(),null==(t=this.videoContext)||t.destroy(),delete this._decodeSink}));let{renderer:n,type:o}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(o){case"wasm":i=this.createDecoder(o,this.wasmOption);break;case"webCodecs":i=this.createDecoder(o);break;default:throw new Error("not supported yet")}let r=0;if(i.on("videoFrame",(i=>{this.decodedFrameCount++,r++,(r<=10||r%500==0)&&e.log.debug("frame ".concat(r," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(i.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&("webCodecs"===this.type?this.checkDowngradeByFrameDiff():"wasm"===this.type&&this.checkDowngradeByTimestampDiff(i.timestamp)),t.next(i)})),i.on("error",(i=>{e.log.error(i),t.error("webCodecs"===o?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===o&&"webgl"===n){this.videoContext=new _H({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(_H.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new _J(this.videoContext);i.on("videoCodecInfo",(e=>r.resize(e.width,e.height))),i.on("videoFrame",(e=>{({y:r.Y,u:r.U,v:r.V}=e),1===this.downgradeLevel?this.decodedFrameCount%2==0&&r.render(this.decodedFrameCount):r.render(this.decodedFrameCount)})),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}else if("videoFrame"===n){e.player.setCanvas();let t=new MediaStreamTrackGenerator({kind:"video"}),r=t.writable.getWriter();e.setInputMediaStreamTrack(t),i.on("videoFrame",(e=>r.write(e)))}else{this.videoContext=new fH({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let r=this.videoContext.createVideoImageSource();i.on("videoFrame",(i=>{try{r.image=i,r.update()}catch(n){delete this.goodType,e.log.error(n),t.error(11)}}));let n=new nH(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(n),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(KM){e.log.error(KM),t.error("webCodecs"===o?2:6)}}))}},TJ=Promise.resolve(),vJ=class extends hJ.EventEmitter{constructor(e){super(),this.room=e,Ub(this,"videoContext"),Ub(this,"_glVideoContext"),Ub(this,"_2dVideoContext"),Ub(this,"destination"),Ub(this,"smallVideoContext"),Ub(this,"smallDestination"),Ub(this,"smallTrackSource"),Ub(this,"smallImageSource"),Ub(this,"_isMirror",!1),Ub(this,"_rotation",0),Ub(this,"cameraTrack"),Ub(this,"cameraNode"),Ub(this,"transformNode"),Ub(this,"mixNode"),Ub(this,"screenTrack"),Ub(this,"screenNode"),Ub(this,"selfModel",!1),Ub(this,"blurRadius",3),Ub(this,"arTrack"),Ub(this,"_enableFaceCentering",!1),Ub(this,"_enableEffectOptimization",!1),Ub(this,"onAbort"),Ub(this,"_color"),Ub(this,"Wasm"),Ub(this,"waterMarkNode"),Ub(this,"_waterMarkOption"),Ub(this,"watermarkImageList",[]),Ub(this,"_beautyParams"),Ub(this,"isUsingArTrack",!1),Ub(this,"mixTrack"),Ub(this,"_isMixScreen",!1),Ub(this,"_virtualBackground"),Ub(this,"_virtualBackgroundAbortCallback"),Ub(this,"virtualBackgroundInstance"),Ub(this,"_bgAssetPath"),Ub(this,"log",UM.createLogger({id:"vm"})),Ub(this,"_mat4"),Ub(this,"_postProcessing"),Ub(this,"_checkId",0),Ub(this,"_use2d",!1),Ub(this,"_autoSwitchRenderMode",!0),Ub(this,"encodePipeline",[]),Ub(this,"decodePipeline",[]),Ub(this,"updated",TJ),Ub(this,"_updateFlag",!1),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new fH({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return(null==(e=this.room)?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return 0!==this._rotation}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var e;let{width:t,height:i}=(null==(e=this.cameraTrack)?void 0:e.settings)||{};return mN(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new fH({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new _H({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(iM<=22),this._glVideoContext.on(_H.UNAVAILABLE,(e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),null==(t=this._virtualBackgroundAbortCallback)||t.call(this,e),this.update().catch((e=>{this.log.error(e)}))}))}catch(pk){this.emit("error",pk)}}initVirtualBackground(e,t,i){this.onAbort=e,this._mat4=t,this._postProcessing=i}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=Ox.run("interval",(()=>{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(),Ox.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(nM||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&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?lL.addFailedEvent({key:t,error:e}):lL.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new _H({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),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}setSmallVideo(e,t){if("api"!==this.smallMode)if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new aH(this.smallVideoContext,e,this.log),this.smallVideoContext.on(_H.UNAVAILABLE,(e=>{this.log.warn("small video context lost",e)}))}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:e,height:t}=this.cameraTrack.settings;this.smallTrackSource.resize(e,t),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,player:n}=i;nM&&n.setCanvas(e);let o=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),o=this.arTrack),this.log.info("set main output ".concat(o?o.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(o)}catch(zM){this.log.error("set main output failed",zM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return Bb(this,null,(function*(){var t;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tH.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===dM?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof dH?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof dH?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new sH(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(tH.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)})));let{width:e,height:t}=this.cameraResolution,i=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.cameraNode=new mJ(this.videoContext,{input:this.initialTrack,width:e,height:t,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let e=this.cameraNode;if(e.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new yH(this.videoContext,this.log,this._isMirror,this._rotation),e=e.connect(this.transformNode),e.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new TH(this.videoContext,this.log),e.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:e,height:t}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(e,t),e&&t&&this.waterMarkNode.resize(e,t)}null==(t=this.waterMarkNode)||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),e=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}e.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)}))}clearLastFrame(){var e;this.destination&&(null==(e=this.destination.ctx2d)||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,i,r,n,o;if(e instanceof RH)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof XB)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof PH){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}if(e instanceof SH)return this.log.info("change mix input",null==(n=e.outMediaTrack)?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",null==(o=e.mediaTrack)?void 0:o.label)}removeInput(e){var t;e instanceof RH?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof XB?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof PH?e.source&&e.source.context.destroy():e instanceof SH&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return Bb(this,null,(function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}))}getWatermarkImage(e,t){return Bb(this,null,(function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new ek({code:Zb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),sN(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))}setBeautyParams(e){return Bb(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return Bb(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return Bb(this,null,(function*(){let t;try{t=yield sN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new ek({code:Zb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.watermarkImageList.some((e=>e.type===s))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==s)),this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return Bb(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t))),yield this.freshWatermark()}))}freshWatermark(){return Bb(this,null,(function*(){var e;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:i}=this.cameraResolution,r=yield this.getWatermarkImage(t,i);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return Bb(this,null,(function*(){var t,i,r;if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield sN(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=null!=(t=e.enableFaceCentering)?t:this._enableFaceCentering,this._enableEffectOptimization=null!=(i=e.enableEffectOptimization)?i:this._enableEffectOptimization,this._color=null!=(r=e.color)?r:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new ek({code:Zb.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})}))}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._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return Bb(this,null,(function*(){var e;null!=(e=this.cameraTrack)&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))}))}disableAr(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new EJ(e)}clear(){var e,t;null==(e=this.videoContext)||e.disconnect(),null==(t=this.destination)||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,null==(r=this.room)||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};Vb([pU((function(e){this.log.error("update failed",e)})),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Bb(this,null,(function*(){this._updateFlag||(this._updateFlag=!0,yield TJ,this.updated=new Promise(((t,r)=>{e.apply(this,i).then(t,r),setTimeout(r,5e3,new ek({code:Zb.API_CALL_TIMEOUT,message:"update timeout"}))})),this._updateFlag=!1,yield this.updated)}))}))],vJ.prototype,"update",1);var yJ=0,SJ=class extends Cx{constructor(e){super("room"),Ub(this,"seq",++yJ),Ub(this,"sdkAppId"),Ub(this,"userId"),Ub(this,"userSig"),Ub(this,"privateMapKey"),Ub(this,"latencyLevel"),Ub(this,"tinyId"),Ub(this,"scene"),Ub(this,"roomId"),Ub(this,"useStringRoomId"),Ub(this,"role","anchor"),Ub(this,"joinParams",null),Ub(this,"localPublishFlag",0),Ub(this,"localTracks",new Set),Ub(this,"enableAutoPlayDialog",!0),Ub(this,"autoReceiveAudio",!0),Ub(this,"autoReceiveVideo",!0),Ub(this,"proxy_ws"),Ub(this,"proxy_wt"),Ub(this,"proxy_unified"),Ub(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Ub(this,"keyPointManager"),Ub(this,"audioManager"),Ub(this,"videoManager"),Ub(this,"callDurationCalculator"),Ub(this,"badCaseDetector"),Ub(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Ub(this,"videoDecodeFallbackType"),Ub(this,"smallMode","canvas"),Ub(this,"enableChorus",!1),Ub(this,"_isUsingCachedSchedule",!1),Ub(this,"_log",UM.createLogger({id:"r".concat(this.seq)})),Ub(this,"_joinedTimestamp",0),Ub(this,"_sdkType"),Ub(this,"heartbeatReport"),Ub(this,"quality"),Ub(this,"enableSEI"),Ub(this,"isDestroyed",!1),this.useStringRoomId=!!e.useStringRoomId,Ow(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Ow(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Ow(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new aJ({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new lJ({room:this}),this.badCaseDetector=new uJ({room:this}),this.audioManager=new DH(this),this.videoManager=new vJ(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}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}get localMainAudioTrack(){for(let e of this.localTracks)if(1&e.mediaType)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach((t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0}})),e}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)}}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 Bb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return Bb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return Bb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ww(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Aw(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(OW([o,o]),Tk("https://".concat(o))):(r&&Tk(r),n&&OW(n))}MM.once(LM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:NW.main,sched_back_domain:NW.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return Bb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return Bb(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 Bb(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 r="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=r.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(YP.INVALID_DESTROY),new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.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,MM.emit(LM.ROOM_DESTROY,{room:this})}schedule(e,t){return Bb(this,null,(function*(){var i,r,n,o;let s=Gw();try{let{isCached:a,result:c,detailCost:l}=yield wW({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:uk,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info("schedule cache:".concat(+a," ").concat(iN(c,{keysToExclude:["username","credential"]}))),a&&MM.once(LM.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=Ob(Ob({},this.scheduleResult),c),Nw(null==(i=c.config)?void 0:i.retryCount)&&pD(c.config.retryCount),ww(null==(r=c.config)?void 0:r.loggerDomain)&&Tk(c.config.loggerDomain),this.videoDecodeFallbackType=(null==(n=c.config)?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(o=c.config)?void 0:o.smallMode)||this.smallMode,MM.emit(LM.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:l}),lL.addSuccessEvent({key:521700,cost:Gw()-s})}catch(jM){throw lL.addFailedEvent({key:521700,error:jM}),jM}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}},IJ=xb(Hb()),AJ=xb(Yb());function RJ(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[r].payload))[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpfb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[r].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return i}var CJ=(e,t)=>Bb(void 0,null,(function*(){var i;let r=jj(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));for(let e of o.rtp){if("opus"!==e.codec)continue;let t=o.fmtp.find((t=>t.payload===e.payload));if(!t)continue;let r={codec:e.codec,fmtp:t.config,payload:t.payload,rate:e.rate,channels:e.encoding,rtcpfb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===r.payload){let e={id:i,params:[]};n&&e.params.push(n),r.rtcpfb.push(e)}})),n.audio.codecs.push(r);break}let a=["h264","vp8","h265"];return t&&a.shift(),n.video.codecs=[...RJ(s)].filter((e=>a.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return Bb(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=RJ(jj(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8","h265"].includes(e.codec.toLocaleLowerCase()))),n})),bJ=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=jj(r),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:Hk.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:Hk.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(kJ({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),Jj(s)},kJ=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink: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:Hk.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:n.media[0].port,protocol:n.media[0].protocol,type:Hk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o){let e=i.video.decoders;(!e||0===e.length)&&(e=i.video.codecs),(!e||0===e.length)&&(e=r.video.decoders),e.forEach((e=>{DJ(s,e)}))}else{let e;e=i.useH265?i.video.codecs.findIndex((e=>"h265"===e.codec.toLowerCase())):i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));let t=i.video.codecs[e]||r.video.codecs[0];DJ(s,t)}return s},DJ=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.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 wJ=(e,t,i)=>{let r=AJ.default.parse(e);return r.media.forEach(((e,n)=>{var o;if((e.type===Hk.AUDIO||e.type===Hk.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Hk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Hk.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),e.type===Hk.VIDEO))if(n<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>DJ(e,t)));else if(i){e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[];let r=i.video.decoders;(!r||0===r.length)&&(r=i.video.codecs),(!r||0===r.length)&&(r=t.video.decoders),r.forEach((t=>DJ(e,t)))}null!=(o=e.payloads)&&o.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),AJ.default.write(r)},NJ=xb(Hb()),OJ=class extends NJ.EventEmitter{constructor(e){super(),this.room=e,Ub(this,"mainFpsHealth",1),Ub(this,"mainBitrateHealth",1),Ub(this,"badMainBitrateHealthCount",0),Ub(this,"lastEmitBadHealthTime",0),Ub(this,"log"),!zN&&QO&&MM.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:i,isHWCodec:r,codec:n}=e;if(!t&&7!==i&&"h264"===n){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let t=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(this.mainFpsHealth=t)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){let{localMainVideoTrack:t}=this.room;t&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/t.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){MM.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Ub(OJ,"EVENT_BAD_HEALTH","bad_health");var MJ=OJ;function PJ(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:n}=e;return new TransformStream({transform(e,o){let s=e;i?audioEncodePipeline.forEach((e=>{s=e({frame:s,ntp:r()})})):videoEncodePipeline.forEach((e=>{s=e({frame:s,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:"",streamType:n?"main":"auxiliary"})}})})),o.enqueue(s)}})}function LJ(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(e,n){let o=e;r?(audioDecodePipeline.forEach((e=>{o=e({frame:o,onAudioFrameNTPTime:e=>{self.postMessage({type:"audio-ntp",data:e,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:o.data,userId:t,streamType:i})}})})),n.enqueue(o)):videoDecodePipeline.forEach((e=>{o=e({frame:o,onSEI:e=>{e.forEach((e=>{self.postMessage({type:"sei",seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t,streamType:i})}))}})})),n.enqueue(o)}})}var xJ=(e=>(e.TRACK="track",e.DATA_CHANNEL_MESSAGE="data_channel_msg",e[e.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",e[e.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",e.RECONNECTED="spc-reconnected",e.RECONNECT_FAILED="spc-reconnect-failed",e.ERROR="error",e.SEI_MESSAGE="sei-message",e.DUMP="dump",e))(xJ||{}),VJ=0,UJ=!1,FJ=new Set,BJ=1,HJ=class extends IJ.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),Ub(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Ub(this,"currentState","DISCONNECTED"),Ub(this,"_room"),Ub(this,"_signalChannel"),Ub(this,"_peerConnection",null),Ub(this,"_datachannel",null),Ub(this,"_enableCustomMessage"),Ub(this,"_log"),Ub(this,"_downlinkMIDMap",new Map),Ub(this,"_downlinkMIDUserIDMap",new Map),Ub(this,"_reconnectionTimer",-1),Ub(this,"reconnectionCount",0),Ub(this,"clientAbility"),Ub(this,"_serverAbility",null),Ub(this,"addDownlinkQueue",new Set),Ub(this,"removeDownlinkQueue",new Set),Ub(this,"_parsedAnswer",null),Ub(this,"_updateSDPPromise",null),Ub(this,"_waitForPCConnectedPromise"),Ub(this,"clearWaitForConnectedPromise"),Ub(this,"clearConnectTimeout"),Ub(this,"_isSDPLogged",!1),Ub(this,"enableInsertableStreams",!1),Ub(this,"insertableStreamsAbortMap",new Map),Ub(this,"receiverRemoteTrackMap",new WeakMap),Ub(this,"scriptTransformWorker"),Ub(this,"_isRelayTried",!1),Ub(this,"_rttOverCount",0),Ub(this,"originOffer",null),Ub(this,"autoSubscribedSsrcGroups",new Map),Ub(this,"autoSubscribedUserMap",new Map),Ub(this,"_h265DecodeFailed",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=UM.createLogger({id:"spc".concat(BJ++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(QL?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}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}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h265"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t,i;let r=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8","h265"].includes(e.codec.toLowerCase())));return r?r.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useH265?"h265":null!=(i=this._serverAbility)&&i.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,i;return null!=(e=this._serverAbility)&&e.useH265&&null!=(t=this._serverAbility)&&t.video.decoders.find((e=>"h265"===e.codec.toLowerCase()))&&!this._h265DecodeFailed?"h265":null!=(i=this._serverAbility)&&i.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get isUsingH265(){return"h265"===this.videoCodec}get isUsingVP8(){return"vp8"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=jj(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 r;if(e.ssrcs&&!Dw(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){ZL&&(this.scriptTransformWorker=function(e){let t=[KB],i=[_G,pG,mG,hG,PJ,LJ,vN,TN],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[],r=0;self.onmessage=n=>{switch(n.data.type){case"sei":n.data.isMain?(e.push(n.data.data),n.data.small&&i.push(n.data.data)):t.push(n.data.data);break;case"ntp-offset":r=n.data.data}},self.onrtctransform=n=>{let{options:o}=n.transformer,s=o.isReceiver?LJ({userId:o.userId,streamType:o.streamType,isAudio:o.isAudio}):PJ({getNtpTime:()=>Date.now()+r,isAudio:o.isAudio,isMain:o.isMain,seiMessageList:o.isMain?o.small?i:e:t});n.transformer.readable.pipeThrough(s).pipeTo(n.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type?this.emit("sei-message",e.data):e.data.type,"dump"===e.data.type&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}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}getPeerConnectionConfig(e){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return NN(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return Bb(this,null,(function*(){var t;let i;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),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._signalChannel.clearBakRelayIps(),lL.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&lL.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var e;let t=(null==(e=this._peerConnection)?void 0:e.signalingState)||"";this._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},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 GJ(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Hk.AUDIO,{direction:Hk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield CJ(i.sdp,(null==(t=this._room.scheduleResult.config)?void 0:t.remove264FromSDP)||!1),this.originOffer=i,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()))}),lL.addSuccessEvent({key:521707}),this.clientAbility}catch(QM){throw lL.addFailedEvent({key:521707,error:QM}),this._log.error("initialize failed ".concat(QM," \noffer: ").concat(null==i?void 0:i.sdp)),QM}}))}setIceServers(e){return Bb(this,null,(function*(){var t;if(this._peerConnection&&0!==e.length)try{if(this._log.info("setIceServers",JSON.stringify(e,((e,t)=>"username"===e||"credential"===e?"hided":t))),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),null!=(t=this._peerConnection)&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(zM){this._log.warn("setIceServers error ",zM)}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(_D){this._log.warn("setPriority error ",_D)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Bb(this,null,(function*(){var i,r,n;try{if("CONNECTED"===this.currentState)return;(null==(i=this._peerConnection)||!i.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let o=Gw(),s={type:"answer",sdp:bJ({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(s),yield this.waitForPeerConnectionConnected();let a=(null==(r=this._room.scheduleResult.config)?void 0:r.priority)||(null==(n=this._room.joinParams)?void 0:n.priority)||new URLSearchParams(location.search).get("priority");a&&this.setPriority(a),t||lL.addSuccessEvent({key:521703,cost:Gw()-o})}catch(KM){let i=KM instanceof ek&&KM.code===Zb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(KM),e),this.reset(),!i&&!this.isReconnecting&&(lL.addFailedEvent({key:521703,error:KM}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),KM}}))}reconnect(){return Bb(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(zG,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(null!=e&&e.iceServer?[e.iceServer]:[])),i=Ob({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:Rj,responseCommand:tj.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(0!==r.data.code)throw new ek({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),lL.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),MM.emit(LM.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(pk){if(!this.isReconnecting)return;if(null!=pk&&pk.message.includes("timeout")){let e=Cw(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield lN(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==pk?void 0:pk.code," ").concat(pk)),lL.addFailedEvent({key:521704,error:pk}),this.reconnectionCount>=mD()&&this._log.warn("SDK has tried reconnect for ".concat(mD()," 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 Bb(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(zG,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===uD.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(i," DTLS: ").concat(r)),e.target.connectionState===uD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===uD.FAILED||e.target.connectionState===uD.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===uD.CONNECTED||e.target.connectionState===uD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),MM.emit(LM.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 dD;let e=null;return FL()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,UL()&&0!==this._peerConnection.getReceivers().length&&e?e.state:dD):dD}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(xJ.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return Bb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(DL(i)){let t=e.get(i.localCandidateId),r=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&&_w(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{MM.off(LM.LEAVE_SUCCESS,r,this),this.off(xJ.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new ek({code:Zb.API_CALL_TIMEOUT,message:"connection timeout"});var i;VJ+=1,i=this._signalChannel.isConnected,VJ>2&&!UJ&&0===FJ.size&&i&&(this._log.warn("firewall restriction"),UJ=!0,this.emit(xJ.FIREWALL_RESTRICTION)),t(e)}),DD);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new ek({code:Zb.API_CALL_TIMEOUT,message:"connection timeout"}))},MM.on(LM.LEAVE_SUCCESS,r,this),this.on(xJ.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return Bb(this,null,(function*(){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(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(_D){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(_D)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Hk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=jj(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Hk.AUDIO,{direction:Hk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Hk.VIDEO,{direction:Hk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=kJ({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:jj(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Hk.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Hk.MAIN," ").concat(l,"-audio")}],s.direction=Hk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Hk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Hk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Hk.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Hk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Hk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Hk.VIDEO)}],a.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,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return Bb(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=jj(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return Bb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(qL()){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&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(KM){this._log.error("failed to set bandwidth: ".concat(KM))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=jj(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.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:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=jj(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=jj(this._peerConnection.remoteDescription.sdp));let s=ZN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:ZN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:ZN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:ZN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:ZN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:ZN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:ZN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:ZN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:ZN?1e3*n:n}]);let a={type:"offer",sdp:Jj(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(Dw(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}setDegradationPreference(e,t,i){if(QO&&eM<83||KN&&cM(aM,"12.1")||ZN&&eO<138)return;let r=e.getParameters(),n="balanced";if("motion"===t?n="maintain-framerate":"detail"===t&&(n="maintain-resolution"),r.degradationPreference===n)return;let o="setDegradationPreference ".concat(i," ").concat(n);return this._log.info(o),r.degradationPreference=n,e.setParameters(r).catch((e=>this._log.warn("".concat(o," failed: ").concat(e))))}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=Jj(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>Bb(this,null,(function*(){var n,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(XM){this._log.error(XM),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.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("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(XM)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return Bb(this,null,(function*(){if(!ZN||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Wk.INACTIVE&&t===Wk.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Wk.SENDONLY&&t===Wk.INACTIVE&&(this._parsedAnswer.media[r].direction=Wk.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return jj(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){this._log.info("setting offer");let t=wJ(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return Bb(this,null,(function*(){if("h265"===e&&!this._parsedAnswer&&(this._parsedAnswer=jj(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Hk.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(r=i.payloads)||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],DJ(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return Bb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];Dw(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Hk.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],DJ(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}setProfileLevelId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"42e01f",t=arguments.length>1?arguments[1]:void 0;return Bb(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];Dw(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Hk.VIDEO){let n;e&&(n=this.clientAbility.video.codecs.find((t=>t.fmtp.includes(e)))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],DJ(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e)),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>DN(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return Bb(this,null,(function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let t=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),lL.addSuccessEvent({key:r,cost:Date.now()-t})}catch(mk){this._log.warn("switchRelay ".concat(i," failed"),mk),lL.addFailedEvent({key:r,error:mk}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,i)=>{let r=setTimeout((()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,i).finally((()=>clearTimeout(r)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Aj,data:{videoDecCodec:"h264"},responseCommand:tj.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)}))}};Vb([yU("reconnect")],HJ.prototype,"startReconnection",1),Vb([SU((e=>e.userId))],HJ.prototype,"addDownlink",1),Vb([SU((e=>e))],HJ.prototype,"removeDownlink",1),Vb([vU(!0)],HJ.prototype,"updateSDP",1),Vb([IU(521712,!1)],HJ.prototype,"setOffer",1),Vb([IU(521713,!1)],HJ.prototype,"setAnswer",1);var WJ=class{constructor(e){Ub(this,"tag"),Ub(this,"len"),Ub(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}},GJ=class{constructor(e){Ub(this,"tinyId"),Ub(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new WJ(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},jJ=new Set;function JJ(){let e=Math.floor(4294967296*Math.random());return jJ.has(e)?JJ():(jJ.add(e),e)}var qJ=xb(Hb()),KJ=class extends qJ.default{constructor(e){super(),Ub(this,"userId"),Ub(this,"tinyId"),Ub(this,"_sdpSemantics"),Ub(this,"_isUplink"),Ub(this,"_room"),Ub(this,"_log"),Ub(this,"_currentState","DISCONNECTED"),Ub(this,"_prevTime",-1),Ub(this,"_blackSmallVideoDetectionId"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=UM.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(MM.emit(LM.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"))}},zJ=new class{constructor(){Ub(this,"worker"),Ub(this,"callbacks",new Map),Ub(this,"_log"),Ub(this,"sleep",{}),Ub(this,"heartbeatListenerCleaner",new Map),Ub(this,"userIdMap",new Map),this._log=UM.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let e=new Blob(['\n const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};\n '],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=e=>this._log.warn("worker error:",e.message,e.filename||"unknown",e.lineno||"unknown"),this.worker.onmessage=e=>{var t;let{type:i,trackId:r,message:n,count:o}=e.data;if("black"===i)null==(t=this.callbacks.get(r))||t();else if("log"===i)this._log.warn(n);else if("blackCount"===i){let e=this.userIdMap.get(r);this._log.warn("".concat(e||r," black count: ").concat(o))}}}return this.worker}start(e){let{track:t,isUplink:i,room:r,userId:n,onBlack:o}=e;if(this._log.debug("start detect black video",t.id),!EL()||!o||!t||"undefined"==typeof Worker)return void this._log.warn("black video detector not supported");let s=e=>{var r,o,s,a;let c;if(i)c=null==(o=null==(r=e.msg_up_stream_info)?void 0:r.msg_video_status)?void 0:o.filter((e=>3===e.uint32_video_stream_type))[0];else{let t=null==(s=e.msg_down_stream_info)?void 0:s.filter((e=>{var t;return(null==(t=e.msg_user_info)?void 0:t.str_identifier)===n}))[0];c=null==(a=null==t?void 0:t.msg_video_status)?void 0:a.filter((e=>3===e.uint32_video_stream_type))[0]}if(c){let e=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);e>0&&e<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",e,"start check"),this.checkOnce(t,3e4))}};return r.on("heartbeat-report",s),this.heartbeatListenerCleaner.set(t.id,(()=>r.off("heartbeat-report",s))),this.callbacks.set(t.id,o),this.userIdMap.set(t.id,n),t.id}checkOnce(e,t){try{let i=this.getWorker();if(!i)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:e});i.postMessage({type:"addTrack",trackId:e.id,timeout:t,readable:r.readable},[r.readable])}catch(_D){this._log.warn("check error:",_D),this.stop(e.id)}}stop(e){if(e){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e),delete this.sleep[e];let t=this.heartbeatListenerCleaner.get(e);t&&t(),this.heartbeatListenerCleaner.delete(e),this.userIdMap.delete(e)}}destroy(){this.callbacks.forEach(((e,t)=>this.stop(t))),this.worker&&(this.worker.terminate(),this.worker=null)}},YJ=class extends KJ{constructor(e){super(Mb(Ob({},e),{isUplink:!0})),Ub(this,"localMainAudioTrack",null),Ub(this,"localMainVideoTrack",null),Ub(this,"localAuxAudioTrack",null),Ub(this,"localAuxVideoTrack",null),Ub(this,"_isPublishingAux",!1),Ub(this,"_publishingLocalAudioTrack"),Ub(this,"_publishingLocalVideoTrack"),Ub(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Ub(this,"_flag",0),Ub(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}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:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:i}=this._room,r=Object.keys(i).filter((e=>{if(i[e]!==t[e]&&i[e])switch(e){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1}));if(r.length>0){if(!e)return void(this._checkPublishStateTimeoutId=Ox.run("timeout",(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));lL.addCount({key:521e3}),r.forEach((e=>{this._log.warn("".concat(e," publish failed during call ").concat(wM()," ").concat(AM())),lL.addEnum({key:521719,value:XJ[e]})})),Ox.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(_D){this._log.warn("checkPublishState failed",_D)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&zk),bigVideo:!!(this.flag&Jk),smallVideo:!!(this.flag&qk),auxVideo:!!(this.flag&Kk)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;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==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){return Bb(this,null,(function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:i}=this;if(!i)return;let r={h265:{supported:i.isH264EncodeSupported,target:"h264",log:"h265 encoder not working, switch to h264"},h264:{supported:i.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working, switch to vp8"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if("vp9"===t||"av1"===t)return;let n=r[t];this._log.warn(n.log),null!=n&&n.supported&&(yield i.switchVideoEncoder(n.target))}))}publish(e){return Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;if(t.installEvents(),t.installTrackMuteEvents(i,r),r&&(r.retryEncodeFailed=t.onVideoEncodeFailed.bind(t)),yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new ek({code:Zb.NOT_SUPPORTED_H264,message:ZP({key:zP.NOT_SUPPORTED_H264ENCODE})});t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported&&(t._log.warn("h264 encoder not supported"),yield t.singlePC.switchVideoEncoder("vp8")),zN&&115===YO()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Uk))),r.setProfile(Uk),yield r.applyProfile()),t._publishingLocalVideoTrack=r}let u;if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack),t._log.warn("muteState",t._room.muteState),yield t._signalChannel.sendWaitForResponseWithRetry({command:bj,responseCommand:tj.SPC_PUBLISH_RESULT,data:Mb(Ob({},t.singlePC.uplinkSSRC),{state:t._room.publishState,muteState:t._room.muteState}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r,yield t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[n?3:1],r.contentHint,r.streamType);let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,n?7:2);let h=new URLSearchParams(location.search).get("profileLevelId");h&&t.singlePC.setProfileLevelId(h)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!HL())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=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),this.initSenderTransform(a[t].sender,e),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),null!=i&&i.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,i));let u=this.singlePC.setTransceiverDirection(Wk.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r,n;let o=this.getTrackByMediaType(t);if(!o)return i.enqueue(e);o.isAudio?i.enqueue(o.enableEncodeFrame?o.encodeFrame(e):e):i.enqueue(null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265?o.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&ZL))return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return Bb(this,null,(function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()}))}publishSmall(e){return Bb(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){var r;if(!t.singlePC)return;if("canvas"===e&&!PL())return void t._log.warn("canvas mode small stream is not supported");let n=t._peerConnection.getTransceivers(),{sender:o}=n[2],s=yield t.doPublishSmall(e,i),a="canvas"===e?524700:524701;lL.addSuccessEvent({key:a}),s?(null!=(r=t.singlePC)&&r.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),yield t.singlePC.setTransceiverDirection(Wk.SENDONLY,[2]),t.updateMediaSettings(),yield t.doPublishChange(),o.track&&(t._blackSmallVideoDetectionId=zJ.start({track:o.track,room:t._room,isUplink:!0,userId:t.userId,onBlack:()=>{t._log.warn("small video is black");let i="canvas"===e?524700:524701;lL.addFailedEvent({key:i,error:10002}),zJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0}}))):lL.addFailedEvent({key:a,error:10001})}()}))}doPublishSmall(e){return Bb(this,arguments,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return function*(){if(!t.singlePC)return null;t._log.info("publish small",e);let r=t._peerConnection.getTransceivers(),{sender:n}=r[2];if("canvas"===e&&t._room.videoManager.smallTrack)return yield n.replaceTrack(t._room.videoManager.smallTrack),"canvas";if("api"===e&&null!=i&&i.outMediaTrack&&null!=i&&i.small){yield n.replaceTrack(null==i?void 0:i.outMediaTrack);let e=n.getParameters(),r=pN(null==i?void 0:i.profile,null==i?void 0:i.small);return t._log.info("small scaleResolutionDownBy",r),e.encodings[0].scaleResolutionDownBy=r,n.setParameters(e),"api"}return t._log.warn("small track can not be enabled, smallMode: ".concat(t._room.videoManager.smallMode,", smallTrack: ").concat(!!t._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(null==i||!i.outMediaTrack))),null}()}))}unpublishSmall(){return Bb(this,null,(function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Wk.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),zJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}))}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 Bb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){var e;yield null==(e=t.singlePC)?void 0:e.waitForPeerConnectionConnected();let n=r&&r===t.localAuxVideoTrack||i&&i===t.localAuxAudioTrack,o=null==r?void 0:r.outMediaTrack,s=t._peerConnection.getSenders(),a=[];i&&(n?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield s[0].replaceTrack(null),a.push(0))),o&&(n?(yield s[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=Mb(Ob({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),a.push(3)):(yield s[1].replaceTrack(null),yield s[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=Mb(Ob({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),a.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Wk.INACTIVE,a),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Bb(this,null,(function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:cj,data:t,responseCommand:tj.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});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:lj,commandDesc:"unpublish",responseCommand:tj.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Zb.API_CALL_TIMEOUT||e.getCode()===Zb.API_CALL_ABORTED)return Promise.resolve();throw e}))}updateMediaSettings(){var e,t;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264",this._mediaSettings.videoDecCodec=(null==(t=this.singlePC)?void 0:t.downlinkVideoCodec)||"h264";let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),zL){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(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=r;this._mediaSettings.videoWidth=(e.width||0)/t||0,this._mediaSettings.videoHeight=(e.height||0)/t||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings(),{scaleResolutionDownBy:t}=n;this._mediaSettings.auxVideoWidth=(e.width||0)/t||0,this._mediaSettings.auxVideoHeight=(e.height||0)/t||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.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),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Aj,data:this._mediaSettings,responseCommand:tj.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return Bb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Hk.AUXILIARY:Hk.MAIN," stream")),BL()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return Bb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Hk.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&null!=(i=this.localMainVideoTrack)&&i.small&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Wk.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Wk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return Bb(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?Hk.AUXILIARY:Hk.MAIN," stream")),BL()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return Bb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Hk.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.singlePC.setTransceiverDirection(Wk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return Bb(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=2===e.mediaType||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?Hk.AUXILIARY:Hk.MAIN," stream")),r.kind===Hk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Hk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return Bb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Hk.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?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._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:sj,responseCommand:tj.MUTE_RESULT,data:this._room.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&MM.emit(LM.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Hk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Hk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Hk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Hk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Hk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===ID?(this._log.error(YP.NOT_SUPPORTED_H264ENCODE),new ek({code:Zb.NOT_SUPPORTED_H264,message:ZP({key:zP.NOT_SUPPORTED_H264ENCODE})})):new ek({code:Zb.UNKNOWN,message:ZP({key:zP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:tj.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return Bb(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}))}))}};Vb([hU((e=>{let{localVideoTrack:t}=e;null==t||delete t.retryEncodeFailed}))],YJ.prototype,"unpublish",1);var XJ=(e=>(e[e.audio=1]="audio",e[e.bigVideo=2]="bigVideo",e[e.smallVideo=3]="smallVideo",e[e.auxVideo=4]="auxVideo",e))(XJ||{}),QJ=YJ;function ZJ(e){return Object.keys(e).filter((t=>e[t]))}var $J=class extends KJ{constructor(e){super(Mb(Ob({},e),{isUplink:!1})),Ub(this,"_flag",0),Ub(this,"isRobot",!1),Ub(this,"role","anchor"),Ub(this,"remoteAudioTrack"),Ub(this,"remoteVideoTrack"),Ub(this,"remoteAuxiliaryTrack"),Ub(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Ub(this,"jitterBufferTimeoutId",-1),Ub(this,"_videoCodec"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new MH(this._room,this),this.remoteVideoTrack=new PH(this._room,this),this.remoteAuxiliaryTrack=new LH(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}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 zw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.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===Hk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),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),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t,i;let r=e.streams[0],{track:n,receiver:o}=e;if(!r.id.includes(this.tinyId))return;let s=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(s," ").concat(n.kind));let a=Hk.AUDIO;n.kind===Hk.VIDEO&&(a=s===Hk.MAIN?Hk.VIDEO:Hk.AUXILIARY);let c=this.remoteAudioTrack;a===Hk.VIDEO?c=this.remoteVideoTrack:a===Hk.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(o,c),null!=(i=this.singlePC)&&i.scriptTransformWorker&&this.initReceiverTransform(o,s,n.kind===Hk.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),c.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:t=>{var i,r,n;let o=null==(i=this.singlePC)?void 0:i.receiverRemoteTrackMap.get(e);return o&&("video"!==o.kind||null!=(r=this.singlePC)&&r.isUsingH264||null!=(n=this.singlePC)&&n.isUsingH265)?o.decodeFrame(t):t}};t.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=r.enqueue(e);i&&t.enqueue(i)}})).pipeTo(t.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(e,i)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return Bb(this,null,(function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(ZJ(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else{if(yield this._room.switchRoomSubedReq,null!=(i=this.singlePC)&&i.autoSubscribedUserMap.size){let e=this.singlePC.autoSubscribedUserMap.get(this.userId);if(e){this.singlePC.autoSubscribedUserMap.delete(this.userId);let t=null==(r=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))?void 0:r[e.groupIndex];t&&(this.ssrc={audio:t.audioSsrc,video:t.bigVideoSsrc,videoRtx:t.bigVideoRtxSsrc,auxiliary:t.auxVideoSsrc,auxiliaryRtx:t.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:o,mediaTrack:s}=this.remoteVideoTrack;e.smallVideo&&s?(lL.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=zJ.start({track:s,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,o),lL.addFailedEvent({key:524702}),zJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(zJ.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(mk){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(mk.message," ").concat(JSON.stringify(this.muteState))),new ek({code:Zb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):mk}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readyState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),QO&&eM<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return Bb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=Ob({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(ZJ(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"main"===r&&(zJ.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0),"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},r=uj,n=tj.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=hj,n=tj.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new ek({code:i.code,message:ZP({key:zP.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(){return Bb(this,null,(function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())}))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return Bb(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){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:JJ(),bigVideoSsrc:JJ(),bigVideoRtxSsrc:JJ(),auxVideoSsrc:JJ(),auxVideoRtxSsrc:JJ()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,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 r=yield e._signalChannel.sendWaitForResponseWithRetry({command:kj,responseCommand:tj.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!==r.data.code&&-10036!==r.data.code)throw new ek({code:r.data.code,message:r.data.message})}catch(r){throw yield e.removeDownlink(),r}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{if(!dx)return;let{main:t,aux:i}=e._room.jitterBufferDelay||{},{jitterDelay:r=t,jitterDelayAux:n=i}=e._room.scheduleResult.config||{};(Nw(r)||Nw(n))&&e.setJitterBufferDelay({mainDelay:r,auxDelay:n})}}}()}))}removeDownlink(){return Bb(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(null!=e&&e.jitterDelay||null!=e&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!dx||!this.singlePC||!this._peerConnection||wN(t)&&wN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return Nw(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),Nw(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,wN(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||wN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&wN(i)||!n&&wN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(mk){this._log.warn("set jitterBuffer delay error: ".concat(mk)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){"h265"===this._room.downlinkVideoCodec&&this._room.requestRemoteFallbackToH264()}};Vb([vU(),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this.off("closed",n),r(new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],$J.prototype,"subscribe",1),Vb([vU()],$J.prototype,"unsubscribe",1),Vb([SU((()=>"jitter"))],$J.prototype,"setJitterBufferDelay",1);var eq=$J;var tq=xb(Hb());var iq=class e extends tq.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,Ub(this,"log"),Ub(this,"cmdIdSeqMap",new Map),Ub(this,"messageMap",new Map),this.log=UM.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(tj.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(Nj,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(t){let{data:i}=t.data,r=this.room.tinyIdToUserIdMap.get(i.srcTinyId);if(r){let t={userId:r,cmdId:i.cmdId,seq:i.streamSeq,data:Uint8Array.from(atob(i.msg),(e=>e.charCodeAt(0))).buffer};if(i.ordered){let i="".concat(r,"_").concat(t.cmdId),n=this.messageMap.get(i);if(n&&0!==n.lastSeq)if(Math.abs(n.lastSeq-t.seq)>e.SEQ_INTERVAL)this.messageMap.set(i,{lastSeq:t.seq,cachedMessageMap:new Map}),this.emitMessage(t);else if(t.seq>n.lastSeq){if(t.seq===n.lastSeq+1)this.emitMessage(t);else if(!n.cachedMessageMap.has(t.seq)){let e=setTimeout((()=>this.emitMessage(t,!0)),5e3);n.cachedMessageMap.set(t.seq,{message:t,timeoutId:e})}}else this.log.debug("drop message ".concat(t.userId,"-").concat(t.cmdId,"-").concat(t.seq));else n||(n={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(i,n),setTimeout((()=>this.emitMessage(t,!0)),100)),n.cachedMessageMap.set(t.seq,{message:t})}else this.emit("message",t)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(i.srcTinyId));let e=r=>{r.tinyId===i.srcTinyId&&(this.room.off("peer-join",e),this.onReceiveMsg(t))};this.room.on("peer-join",e),lN(2e3).then((()=>this.room.off("peer-join",e)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}};Ub(iq,"SEQ_INTERVAL",300);var rq=iq,{isString:nq,isUndefined:oq,getNetworkType:sq,isEmpty:aq}=ck,cq=class extends SJ{constructor(e){super(e),Ub(this,"_businessInfo"),Ub(this,"userManager"),Ub(this,"_version"),Ub(this,"_heartbeat",-1),Ub(this,"_lastHeartBeatTime",-1),Ub(this,"_stats"),Ub(this,"_joinTimeout",-1),Ub(this,"_firstPublishedList",null),Ub(this,"_joinReject",null),Ub(this,"_isRelayChanged",!1),Ub(this,"sdpSemantics"),Ub(this,"signalChannel",null),Ub(this,"uplinkConnection",null),Ub(this,"singlePC",null),Ub(this,"enableSPC",WL),Ub(this,"_changeBigSmallRecords",new Map),Ub(this,"networkQuality"),Ub(this,"_iceTransportPolicy"),Ub(this,"forceRelay",!1),Ub(this,"_turnServers",[]),Ub(this,"_iceServersFromJoin"),Ub(this,"_syncUserListInterval",-1),Ub(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Ub(this,"enableSEI",!1),Ub(this,"_enableAudioVolumeEvaluation",!1),Ub(this,"_audioVolumeIntervalId",0),Ub(this,"_enableMultiAuxStream",!1),Ub(this,"_pureAudioPushMode",!1),Ub(this,"_customMessageManager"),Ub(this,"preferHW",!1),Ub(this,"healthDetector"),Ub(this,"playoutDelay"),Ub(this,"jitterBufferDelay"),Ub(this,"_updateAudioLevelTaskId",-1),Ub(this,"switchRoomSubedReq"),Ub(this,"resolveSwitchRoomSubedReq"),Ub(this,"enableVolumeControlInIOS"),this._stats=new Zj(this,this._log),this.userManager=new HH(this.userId,this._log),this._version=uk,this.sdpSemantics=SD,oq(e.sdpSemantics)?HM.isUnifiedPlanDefault()&&(this.sdpSemantics=yD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(sq())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!oq(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&WL,!oq(e.enableSPC)&&WL&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new MJ(this)}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.userMap.values()].map((e=>[e.tinyId,e.userId])))}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,i){return Bb(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 r in e)bb.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&Rb)for(var r of Rb(e))t.indexOf(r)<0&&kb.call(e,r)&&(i[r]=e[r]);return i})(e,[]);MM.emit(LM.REMOTE_PUBLISH_STATE_CHANGED,Ob({room:this},t)),this.emit("remote-publish-state-changed",Ob({},t))})),this.joinParams=e,new Promise(((t,i)=>Bb(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof ek&&o.code===Zb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=Gw();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),lL.addSuccessEvent({key:521708,cost:Gw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(jM){lL.addFailedEvent({key:521708,error:jM}),i(jM)}this._joinReject=null}))))}))}initSinglePC(){return Bb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new HJ({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.on("dump",(e=>this.emit("dump",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(pk){throw this.fallbackToMPC(),new ek({code:Zb.SPC_INITIALIZED_FAILED,message:null==pk?void 0:pk.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>Bb(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(XG,(e=>{this.clearJoinTimeout(),MM.emit(LM.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),Ow(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&WL&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:NM(),netType:fw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&mL()};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new ek({code:Zb.JOIN_ROOM_FAILED,message:ZP({key:zP.JOIN_ROOM_TIMEOUT})}))}),c),MM.emit(LM.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Cj:rj,a),this.signalChannel.once(tj.JOIN_ROOM_RESULT,(t=>Bb(this,null,(function*(){this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;MM.emit(LM.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this._iceServersFromJoin=s.iceServer?[s.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then((()=>{var t;null==(t=this.singlePC)||t.connect(Mb(Ob({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8,useH265:s.ability.useH265||!!e.useH265})).catch((()=>{}))})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new ek({code:Zb.JOIN_ROOM_FAILED,extraCode:n,message:ZP({key:zP.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))))}))))}reJoin(){return Bb(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then((t=>(e=t,t))))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(Mb(Ob({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),Ux.logSuccessEvent({userId:this.userId,eventType:gD.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(xJ.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof QJ&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(xJ.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Qj&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(pk){this._log.warn("reJoin fail ".concat(pk)),this.reset(),Ux.logFailedEvent({userId:this.userId,eventType:gD.REJOIN,error:pk}),this.emit("error",new ek({code:Zb.JOIN_ROOM_FAILED,message:ZP({key:zP.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return Bb(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...Pj.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new xj({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new rq(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new iJ({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(iJ.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),xx(this,this.signalChannel).add(KG,(e=>{MM.emit(LM.SIGNAL_CONNECTION_STATE_CHANGED,Ob({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(YG,(e=>{this.reset(),this.emit("error",e)})).add(tj.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(tj.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(tj.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(tj.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(Ux.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})})).add(tj.SEND_SWITCH_ROOM_SUBED_REQ,(e=>{if(!this.singlePC)return;let{subList:t}=e.data.data;this._log.info("auto subscribe ".concat(iN(t,{keysToInclude:["userId"]}))),t.forEach((e=>{this.singlePC.autoSubscribedUserMap.set(e.userId,e)})),this.resolveSwitchRoomSubedReq()})).add(tj.FALLBACK_CODEC,(e=>Bb(this,null,(function*(){var t,i,r,n,o;let s=e.data.data;this._log.warn("fallback codec enableH265Enc: ".concat(null==(t=s.videoControlInfo)?void 0:t.enableH265Enc)),0===(null==(i=s.videoControlInfo)?void 0:i.enableH265Enc)&&"h265"===(null==(r=this.singlePC)?void 0:r.videoCodec)&&(lL.addCount({key:513e3}),yield null==(n=this.singlePC)?void 0:n.switchVideoEncoder("h264"),yield null==(o=this.uplinkConnection)?void 0:o.sendMediaSettings())})))),this.signalChannel.once(qG,(e=>{this.tinyId=e.signalInfo.tinyId,MM.emit(LM.JOIN_SIGNAL_CONNECTION_END,{room:this})})),MM.emit(LM.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&MM.emit(LM.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||Vx(this)}leave(){return Bb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(_D){}this._log.info("leave() => leaving room"),MM.emit(LM.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(nj),this.switchRoomSubedReq=void 0}))}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=Ox.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),Ox.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return Bb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(xH.has(e)){let t=xH.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType})));return xH.delete(e),t}return[]}(this.userId):[],n=Mb(Ob({str_sdk_version:dk,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:Ob({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:fw()},i.msg_device_info)});if(this.heartbeatReport=n,MM.emit(LM.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(oj,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",Mb(Ob({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==Zk)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=r),this.localPublishFlag!==r&&(this.localPublishFlag=r,this.emit("local-publish-flag-changed",r)));let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),MM.emit(LM.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find((e=>e.userId===this.userId))||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),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().catch((()=>{})),this.uplinkConnection.close(e),this.uplinkConnection instanceof Qj&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?eq:zj)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}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!==Zb.ICE_TRANSPORT_ERROR&&(i===Zb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",Mb(Ob({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=Ox.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){Ox.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:Sj,responseCommand:tj.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw ZP({key:zP.SIGNAL_RESPONSE_FAILED,data:{signalResponse:tj.USER_LIST_RES,code:i,message:r}})})):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||!Hj)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)===uD.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof Wj&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===uD.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return Bb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),Ux.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new Qj({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),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})),e.close()}for(let t of[...this.remotePublishedUserMap.values()]){let e=new zj({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.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 ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),Ox.clearTask(this._audioVolumeIntervalId))}switchRole(e){return Bb(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:Ij,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:tj.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:r}=t.data;if(0!==i)throw new ek({code:Zb.SWITCH_ROLE_FAILED,message:ZP({key:zP.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof ek&&e.getCode()===Zb.API_CALL_TIMEOUT&&(e=new ek({code:Zb.SWITCH_ROLE_FAILED,message:ZP({key:zP.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new QJ({userId:this.userId,tinyId:this.tinyId,room:this}):new Qj({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",Mb(Ob({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Zb.ICE_TRANSPORT_ERROR&&(t===Zb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))}))}publish(e){return Bb(this,null,(function*(){this.uplinkConnection||this._initUplinkConnection(),this._log.info("publish() => ".concat(e.streamType," ").concat(e.kind)),yield this.uplinkConnection.publish({localAudioTrack:e instanceof qB?e:null,localVideoTrack:e instanceof XB?e:null,isAuxiliary:"auxiliary"===e.streamType}),this._log.info("".concat(e.streamType," is published"))}))}unpublish(e){return Bb(this,null,(function*(){if(("live"!==this.scene||"anchor"===this.role)&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{this._log.info("unpublish() => ".concat(e.streamType," ").concat(e.kind)),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof qB?e:null,localVideoTrack:e instanceof XB?e:null})}catch(_D){}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?(e.unpublish(),this.uplinkConnection.removeTrack(e)):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&JL()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&MM.emit(LM.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return Bb(this,null,(function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return Bb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Hk.VIDEO,videoType:Hk.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 Bb(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 r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=Ob({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),MM.emit(LM.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(qj(n),"] prev: [").concat(qj(i.subscribeState),"]")),yield i.subscribe(n,r),this._log.info("subscribe ".concat(e," ").concat(r," done"));for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());MM.emit(LM.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(mk){let i=mk instanceof ek?mk.getCode():Zb.UNKNOWN,n=mk;throw mk instanceof ek?i===Zb.REMOTE_STREAM_NOT_EXIST&&(n=new ek({code:Zb.API_CALL_ABORTED,message:ZP({key:zP.API_CALL_ABORTED,data:{message:mk.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new ek({code:i,message:ZP({key:zP.SUBSCRIBE_FAILED,data:{message:mk.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return Bb(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(mk){this._log.warn("unsubscribe() => failed ".concat(mk))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),MM.emit(LM.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,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 Ox.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),MM.emit(LM.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Ox.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Ox.run("intervalInWorker",(()=>{var i;UV.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!UV.isRunning&&e.muteState.audioAvailable&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t,floatVolume:e.remoteAudioTrack.getInternalAudioLevel()})}})),this.emit("audio-volume",r)}),{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return Bb(this,null,(function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let r=null==(i=this.uplinkConnection.getPeerConnection())?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=Ox.run("intervalInWorker",(()=>Bb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let e=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:t}=this.uplinkConnection;e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(t.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Ox.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!KL||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;Nw(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then((t=>{t.forEach((t=>{"inbound-rtp"===t.type&&Nw(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}getLocalAudioStats(){return Bb(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return Bb(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return Bb(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 Bb(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return Bb(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(ck.getTurnServer(e)))):ck.isPlainObject(e)&&i.push(ck.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:gj,data:e,timeout:5e3,responseCommand:tj.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Ej,data:e,timeout:5e3,responseCommand:tj.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?pj:_j,data:e,timeout:5e3,responseCommand:t?tj.START_PUBLISH_TENCENT_CDN_RES:tj.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?mj:fj,data:e,timeout:5e3,responseCommand:t?tj.STOP_PUBLISH_TENCENT_CDN_RES:tj.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Tj,data:e,timeout:5e3,responseCommand:tj.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:vj,data:e,timeout:5e3,responseCommand:tj.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:yj,data:e,timeout:5e3,responseCommand:tj.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e}))}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:Dj,data:e,timeout:5e3,responseCommand:tj.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(e){var t,i;return this._turnServers.length>0?this._turnServers:null!=(t=this.scheduleResult.iceServers)&&t.length?this.scheduleResult.iceServers:null!=e&&e.length?e:null!=(i=this._iceServersFromJoin)&&i.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=ck.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):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),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.localPublishFlag=0,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 Bb(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!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&&r)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(!r&&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(FD-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=FD}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(FD-o.reSubscribeCount,". reason: ").concat(l)),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:FD};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(nq(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!oq(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.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(!oq(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!oq(e.userDefinePushArgs)){if(!(nq(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new ek({code:Zb.INVALID_PARAMETER,message:ZP({key:zP.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}aq(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){return Bb(this,null,(function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&QL)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()}))}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new ek({code:Zb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}switchRoom(e){return Bb(this,null,(function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:i,strRoomId:r,userSig:n,privateMapKey:o}=e,s=(null==(t=this.scheduleResult.config)?void 0:t.autoSubscribeCount)||(null==e?void 0:e.autoSubscribeCount)||1,a=String(this.useStringRoomId?r:i),c=[];for(let e=0;e<s;e++)c.push({audioSsrc:JJ(),bigVideoSsrc:JJ(),bigVideoRtxSsrc:JJ(),auxVideoSsrc:JJ(),auxVideoRtxSsrc:JJ()});let l={currRoomId:this.roomId,targetRoomId:a,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:n,privateMapKey:null!=o?o:this.privateMapKey,subscribe:c};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(a,c);let d,u=this.roomId;this.roomId=this.useStringRoomId?r:String(i),this.switchRoomSubedReq=new Promise((e=>{this.resolveSwitchRoomSubedReq=e,lN(5e3).then(e)})),MM.emit(LM.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),d=yield this.signalChannel.sendWaitForResponse({command:Oj,responseCommand:tj.SEND_SWITCH_ROOM_RES,data:l});let{code:e,message:t}=d.data;if(0!==e){this._log.error("switch room failed. result: ".concat(e," error: ").concat(t));let i=new ek({code:Zb.SWITCH_ROOM_FAILED,extraCode:e,message:t});throw MM.emit(LM.SWITCH_ROOM_FAILED,{room:this,error:i}),i}this.userSig=n,oq(o)||(this.privateMapKey=o),MM.emit(LM.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:u,targetRoomId:a})}catch(h){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=u,this.resolveSwitchRoomSubedReq(),h}}))}isSwitchRoomSupported(){var e;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return!0!==(null==(e=this.scheduleResult.config)?void 0:e.switchRoom)?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):"live"!==this.scene?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):"audience"!==this.role?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var e;null==(e=this.singlePC)||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then((e=>{var t;let i=e[0].offset,r=e[0].offset;e.forEach((e=>{i=Math.min(e.offset,i),r=Math.max(e.offset,r)}));let n=Math.floor(e.reduce(((e,t)=>e+t.rtt),0)/e.length),o=Math.floor(e.reduce(((e,t)=>e+t.offset),0)/e.length);(r-i>30||n>50)&&setTimeout((()=>this.startUpdateNTPTime()),5e3),rk(o),null==(t=this.scriptTransformWorker)||t.postMessage({type:"ntp-offset",data:o}),this._log.debug("ntp updated offset: ".concat(o)),this.emit("ntp-time-updated")})).catch((e=>{this._log.warn("ntp updated failed: ".concat(e))}))}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Mj,responseCommand:tj.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then((t=>{let i=Number(t.data.data.serverSendTime),r=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now();return{rtt:n-e-(r-i),offset:(r-e+(i-n))/2}}))}};return Vb([Ix(["left",Cx.INIT],"joined"),Bx({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),DW(!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(),t())}}),mU((e=>{let t=new GG;return function(i,r,n){return Bb(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=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new ek({code:Zb.INVALID_OPERATION,message:ZP({key:zP.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)),MM.emit(LM.JOIN_START,{room:this,roomId:o,params:i});let s=ck.getEnv();s||(s=wk.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Gk.OLD_CLOUD_LADDER)?s=wk.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Gk.WEBRTC)&&(s=wk.WEBRTC))),Ux.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),HM.checkSystemRequirementsInternal(n).then((e=>{this.checkSystemResult=e,jG.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!ck.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=ck.performanceNow(),MM.emit(LM.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&Ux.uploadEvent({log:"stat-conv-".concat(Number(_M),"-").concat(location.hostname),userId:this.userId}),t}catch(KM){throw t.delete({room:this,roomId:o}),MM.emit(LM.JOIN_FAILED,{room:this,error:KM}),KM}}))}}))],cq.prototype,"join",1),Vb([Ix("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Bb(this,null,(function*(){MM.emit(LM.LEAVE_START,{room:this}),yield e.call(this,...i),MM.emit(LM.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),yU("leave room"),Hx({fnName:"publish",validateArgs:!1}),Hx({fnName:"unsubscribe",validateArgs:!1})],cq.prototype,"leave",1),Vb([SU((e=>e.mediaType)),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return Bb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;MM.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map((e=>e.publish(this,t))))}))})),Bx({settings:{retries:mD,timeout:e=>Cw(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),MM.emit(LM.PUBLISH_FAILED,{room:this}))}})],cq.prototype,"publish",1),Vb([Hx({fnName:"publish"}),SU((e=>e.mediaType)),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>e.unpublish())),n})),hU((function(){var e,t;0===this.localTracks.size&&FL()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],cq.prototype,"unpublish",1),Vb([pU((e=>{if(e.code!==Zb.API_CALL_ABORTED)throw e})),SU((e=>e.userId))],cq.prototype,"replaceTrack",1),Vb([SU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),wH(),mU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(n))),n})),Bx({settings:{retries:mD,timeout:e=>Cw(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),MM.emit(LM.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],cq.prototype,"subscribe",1),Vb([Hx({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")}))}}),SU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],cq.prototype,"unsubscribe",1),WG.create=WG._create.bind(WG,cq),cx(30),WG}));