trtc-sdk-v5 5.15.0-wasm.1 → 5.15.0-wasm.2
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/assets/worker.js +1 -1
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/lebplayer/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/face-detection/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +3 -3
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){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},i=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")(),r={},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,l=Function.prototype.call,c=s?l.bind(l):function(){return l.apply(l,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,P=function(e){if(O(e))throw new M("Can't call method on "+e);return e},L=N,x=P,U=function(e){return L(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=i,G=F,j=function(e,t){return arguments.length<2?(i=W[e],G(i)?i:void 0):W[e]&&W[e][t];var i},z=T({}.isPrototypeOf),K=i.navigator,q=K&&K.userAgent,Y=q?String(q):"",J=i,X=Y,Q=J.process,$=J.Deno,Z=Q&&Q.versions||$&&$.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,ie=te,re=o,oe=i.String,ne=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol("symbol detection");return!oe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),ae=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,se=j,le=F,ce=z,de=Object,ue=ae?function(e){return"symbol"==typeof e}:function(e){var t=se("Symbol");return le(t)&&ce(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 i=e[t];return ve(i)?void 0:Ee(i)},Te=c,Ie=F,Ae=H,Se=TypeError,Re={exports:{}},be=i,we=Object.defineProperty,Ce=function(e,t){try{we(be,e,{value:t,configurable:!0,writable:!0})}catch(i){be[e]=t}return t},De=i,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,Pe=Me,Le=function(e,t){return Pe[e]||(Pe[e]=t||{})},xe=P,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,Ge=0,je=Math.random(),ze=We(1..toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ze(++Ge+je,36)},qe=Le,Ye=He,Je=Ke,Xe=ne,Qe=ae,$e=i.Symbol,Ze=qe("wks"),et=Qe?$e.for||$e:$e&&$e.withoutSetter||Je,tt=function(e){return Ye(Ze,e)||(Ze[e]=Xe&&Ye($e,e)?$e[e]:et("Symbol."+e)),Ze[e]},it=c,rt=H,ot=ue,nt=ye,at=function(e,t){var i,r;if("string"===t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;if(Ie(i=e.valueOf)&&!Ae(r=Te(i,e)))return r;if("string"!==t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;throw new Se("Can't convert object to primitive value")},st=TypeError,lt=tt("toPrimitive"),ct=function(e,t){if(!rt(e)||ot(e))return e;var i,r=nt(e,lt);if(r){if(void 0===t&&(t="default"),i=it(r,e,t),!rt(i)||ot(i))return i;throw new st("Can't convert object to primitive value")}return void 0===t&&(t="number"),at(e,t)},dt=ct,ut=ue,ht=function(e){var t=dt(e,"string");return ut(t)?t:t+""},pt=H,mt=i.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=c,Tt=d,It=_,At=U,St=ht,Rt=He,bt=Et,wt=Object.getOwnPropertyDescriptor;r.f=vt?wt:function(e,t){if(e=At(e),t=St(t),bt)try{return wt(e,t)}catch(i){}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")},Pt=n,Lt=Et,xt=Dt,Ut=Mt,Vt=ht,Ft=TypeError,Bt=Object.defineProperty,Ht=Object.getOwnPropertyDescriptor,Wt="enumerable",Gt="configurable",jt="writable";Ct.f=Pt?xt?function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),"function"==typeof e&&"prototype"===t&&"value"in i&&jt in i&&!i[jt]){var r=Ht(e,t);r&&r[jt]&&(e[t]=i.value,i={configurable:Gt in i?i[Gt]:r[Gt],enumerable:Wt in i?i[Wt]:r[Wt],writable:!1})}return Bt(e,t,i)}:Bt:function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),Lt)try{return Bt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ft("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var zt=Ct,Kt=_,qt=n?function(e,t,i){return zt.f(e,t,Kt(1,i))}:function(e,t,i){return e[t]=i,e},Yt={exports:{}},Jt=n,Xt=He,Qt=Function.prototype,$t=Jt&&Object.getOwnPropertyDescriptor,Zt=Xt(Qt,"name"),ei={EXISTS:Zt,PROPER:Zt&&"something"===function(){}.name,CONFIGURABLE:Zt&&(!Jt||Jt&&$t(Qt,"name").configurable)},ti=F,ii=Me,ri=T(Function.toString);ti(ii.inspectSource)||(ii.inspectSource=function(e){return ri(e)});var oi,ni,ai,si=ii.inspectSource,li=F,ci=i.WeakMap,di=li(ci)&&/native code/.test(String(ci)),ui=Ke,hi=Le("keys"),pi=function(e){return hi[e]||(hi[e]=ui(e))},mi={},fi=di,_i=i,gi=H,Ei=qt,vi=He,yi=Me,Ti=pi,Ii=mi,Ai="Object already initialized",Si=_i.TypeError,Ri=_i.WeakMap;if(fi||yi.state){var bi=yi.state||(yi.state=new Ri);bi.get=bi.get,bi.has=bi.has,bi.set=bi.set,oi=function(e,t){if(bi.has(e))throw new Si(Ai);return t.facade=e,bi.set(e,t),t},ni=function(e){return bi.get(e)||{}},ai=function(e){return bi.has(e)}}else{var wi=Ti("state");Ii[wi]=!0,oi=function(e,t){if(vi(e,wi))throw new Si(Ai);return t.facade=e,Ei(e,wi,t),t},ni=function(e){return vi(e,wi)?e[wi]:{}},ai=function(e){return vi(e,wi)}}var Ci={set:oi,get:ni,has:ai,enforce:function(e){return ai(e)?ni(e):oi(e,{})},getterFor:function(e){return function(t){var i;if(!gi(t)||(i=ni(t)).type!==e)throw new Si("Incompatible receiver, "+e+" required");return i}}},Di=T,Ni=o,ki=F,Oi=He,Mi=n,Pi=ei.CONFIGURABLE,Li=si,xi=Ci.enforce,Ui=Ci.get,Vi=String,Fi=Object.defineProperty,Bi=Di("".slice),Hi=Di("".replace),Wi=Di([].join),Gi=Mi&&!Ni((function(){return 8!==Fi((function(){}),"length",{value:8}).length})),ji=String(String).split("String"),zi=Yt.exports=function(e,t,i){"Symbol("===Bi(Vi(t),0,7)&&(t="["+Hi(Vi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Oi(e,"name")||Pi&&e.name!==t)&&(Mi?Fi(e,"name",{value:t,configurable:!0}):e.name=t),Gi&&i&&Oi(i,"arity")&&e.length!==i.arity&&Fi(e,"length",{value:i.arity});try{i&&Oi(i,"constructor")&&i.constructor?Mi&&Fi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(o){}var r=xi(e);return Oi(r,"source")||(r.source=Wi(ji,"string"==typeof t?t:"")),e};Function.prototype.toString=zi((function(){return ki(this)&&Ui(this).source||Li(this)}),"toString");var Ki=Yt.exports,qi=F,Yi=Ct,Ji=Ki,Xi=Ce,Qi=function(e,t,i,r){r||(r={});var o=r.enumerable,n=void 0!==r.name?r.name:t;if(qi(i)&&Ji(i,n,r),r.global)o?e[t]=i:Xi(t,i);else{try{r.unsafe?e[t]&&(o=!0):delete e[t]}catch(a){}o?e[t]=i:Yi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},$i={},Zi=Math.ceil,er=Math.floor,tr=Math.trunc||function(e){var t=+e;return(t>0?er:Zi)(t)},ir=tr,rr=function(e){var t=+e;return t!=t||0===t?0:ir(t)},or=rr,nr=Math.max,ar=Math.min,sr=function(e,t){var i=or(e);return i<0?nr(i+t,0):ar(i,t)},lr=rr,cr=Math.min,dr=function(e){var t=lr(e);return t>0?cr(t,9007199254740991):0},ur=dr,hr=function(e){return ur(e.length)},pr=U,mr=sr,fr=hr,_r=function(e){return function(t,i,r){var o=pr(t),n=fr(o);if(0===n)return!e&&-1;var a,s=mr(r,n);if(e&&i!=i){for(;n>s;)if((a=o[s++])!=a)return!0}else for(;n>s;s++)if((e||s in o)&&o[s]===i)return e||s||0;return!e&&-1}},gr={includes:_r(!0),indexOf:_r(!1)},Er=He,vr=U,yr=gr.indexOf,Tr=mi,Ir=T([].push),Ar=function(e,t){var i,r=vr(e),o=0,n=[];for(i in r)!Er(Tr,i)&&Er(r,i)&&Ir(n,i);for(;t.length>o;)Er(r,i=t[o++])&&(~yr(n,i)||Ir(n,i));return n},Sr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rr=Ar,br=Sr.concat("length","prototype");$i.f=Object.getOwnPropertyNames||function(e){return Rr(e,br)};var wr={};wr.f=Object.getOwnPropertySymbols;var Cr=j,Dr=$i,Nr=wr,kr=Mt,Or=T([].concat),Mr=Cr("Reflect","ownKeys")||function(e){var t=Dr.f(kr(e)),i=Nr.f;return i?Or(t,i(e)):t},Pr=He,Lr=Mr,xr=r,Ur=Ct,Vr=function(e,t,i){for(var r=Lr(t),o=Ur.f,n=xr.f,a=0;a<r.length;a++){var s=r[a];Pr(e,s)||i&&Pr(i,s)||o(e,s,n(t,s))}},Fr=o,Br=F,Hr=/#|\.prototype\./,Wr=function(e,t){var i=jr[Gr(e)];return i===Kr||i!==zr&&(Br(t)?Fr(t):!!t)},Gr=Wr.normalize=function(e){return String(e).replace(Hr,".").toLowerCase()},jr=Wr.data={},zr=Wr.NATIVE="N",Kr=Wr.POLYFILL="P",qr=Wr,Yr=i,Jr=r.f,Xr=qt,Qr=Qi,$r=Ce,Zr=Vr,eo=qr,to=function(e,t){var i,r,o,n,a,s=e.target,l=e.global,c=e.stat;if(i=l?Yr:c?Yr[s]||$r(s,{}):Yr[s]&&Yr[s].prototype)for(r in t){if(n=t[r],o=e.dontCallGetSet?(a=Jr(i,r))&&a.value:i[r],!eo(l?r:s+(c?".":"#")+r,e.forced)&&void 0!==o){if(typeof n==typeof o)continue;Zr(n,o)}(e.sham||o&&o.sham)&&Xr(n,"sham",!0),Qr(i,r,n,e)}},io={};io[tt("toStringTag")]="z";var ro="[object z]"===String(io),oo=F,no=R,ao=tt("toStringTag"),so=Object,lo="Arguments"===no(function(){return arguments}()),co=ro?no: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=so(e),ao))?i:lo?no(t):"Object"===(r=no(t))&&oo(t.callee)?"Arguments":r},uo=co,ho=String,po=function(e){if("Symbol"===uo(e))throw new TypeError("Cannot convert a Symbol value to a string");return ho(e)},mo=Ki,fo=Ct,_o=function(e,t,i){return i.get&&mo(i.get,t,{getter:!0}),i.set&&mo(i.set,t,{setter:!0}),fo.f(e,t,i)},go=to,Eo=n,vo=T,yo=He,To=F,Io=z,Ao=po,So=_o,Ro=Vr,bo=i.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\((.*)\)[^)]+$/,Po=vo("".replace),Lo=vo("".slice);So(wo,"description",{configurable:!0,get:function(){var e=ko(this);if(yo(Co,e))return"";var t=Oo(e),i=No?Lo(t,7,-1):Po(t,Mo,"$1");return""===i?void 0:i}}),go({global:!0,constructor:!0,forced:!0},{Symbol:Do})}var xo=i,Uo={},Vo=tt;Uo.f=Vo;var Fo=xo,Bo=He,Ho=Uo,Wo=Ct.f,Go=function(e){var t=Fo.Symbol||(Fo.Symbol={});Bo(t,e)||Wo(t,e,{value:Ho.f(e)})};Go("asyncIterator");var jo=R,zo=Array.isArray||function(e){return"Array"===jo(e)},Ko=TypeError,qo=R,Yo=T,Jo=function(e){if("Function"===qo(e))return Yo(e)},Xo=ge,Qo=a,$o=Jo(Jo.bind),Zo=function(e,t){return Xo(e),void 0===t?e:Qo?$o(e,t):function(){return e.apply(t,arguments)}},en=zo,tn=hr,rn=function(e){if(e>9007199254740991)throw Ko("Maximum allowed index exceeded");return e},on=Zo,nn=function(e,t,i,r,o,n,a,s){for(var l,c,d=o,u=0,h=!!a&&on(a,s);u<r;)u in i&&(l=h?h(i[u],u,t):i[u],n>0&&en(l)?(c=tn(l),d=nn(e,t,l,c,d,n-1)-1):(rn(d+1),e[d]=l),d++),u++;return d},an=nn,sn=T,ln=o,cn=F,dn=co,un=si,hn=function(){},pn=j("Reflect","construct"),mn=/^\s*(?:class|function)\b/,fn=sn(mn.exec),_n=!mn.test(hn),gn=function(e){if(!cn(e))return!1;try{return pn(hn,[],e),!0}catch(t){return!1}},En=function(e){if(!cn(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||ln((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=hr,Nn=rr,kn=bn;to({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,t=Cn(this),i=Dn(t),r=kn(t,0);return r.length=wn(r,t,t,i,0,void 0===e?1:Nn(e)),r}});var On={},Mn=Ar,Pn=Sr,Ln=Object.keys||function(e){return Mn(e,Pn)},xn=n,Un=Dt,Vn=Ct,Fn=Mt,Bn=U,Hn=Ln;On.f=xn&&!Un?Object.defineProperties:function(e,t){Fn(e);for(var i,r=Bn(t),o=Hn(t),n=o.length,a=0;n>a;)Vn.f(e,i=o[a++],r[i]);return e};var Wn,Gn=j("document","documentElement"),jn=Mt,zn=On,Kn=Sr,qn=mi,Yn=Gn,Jn=_t,Xn="prototype",Qn="script",$n=pi("IE_PROTO"),Zn=function(){},ea=function(e){return"<"+Qn+">"+e+"</"+Qn+">"},ta=function(e){e.write(ea("")),e.close();var t=e.parentWindow.Object;return e=null,t},ia=function(){try{Wn=new ActiveXObject("htmlfile")}catch(t){}ia="undefined"!=typeof document?document.domain&&Wn?ta(Wn):function(){var e,t=Jn("iframe"),i="java"+Qn+":";return t.style.display="none",Yn.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(ea("document.F=Object")),e.close(),e.F}():ta(Wn);for(var e=Kn.length;e--;)delete ia[Xn][Kn[e]];return ia()};qn[$n]=!0;var ra=Object.create||function(e,t){var i;return null!==e?(Zn[Xn]=jn(e),i=new Zn,Zn[Xn]=null,i[$n]=e):i=ia(),void 0===t?i:zn.f(i,t)},oa=tt,na=ra,aa=Ct.f,sa=oa("unscopables"),la=Array.prototype;void 0===la[sa]&&aa(la,sa,{configurable:!0,value:na(null)});var ca=function(e){la[sa][e]=!0},da=gr.includes,ua=ca;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=pi("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 i=t.constructor;return Ea(i)&&t instanceof i?i.prototype:t instanceof Ia?Aa:null},Ra=o,ba=F,wa=H,Ca=Sa,Da=Qi,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},Pa=Ct.f,La=He,xa=tt("toStringTag"),Ua=function(e,t,i){e&&!i&&(e=e.prototype),e&&!La(e,xa)&&Pa(e,xa,{configurable:!0,value:t})},Va=Ma.IteratorPrototype,Fa=ra,Ba=_,Ha=Ua,Wa=fa,Ga=function(){return this},ja=function(e,t,i,r){var o=t+" Iterator";return e.prototype=Fa(Va,{next:Ba(+!r,i)}),Ha(e,o,!1),Wa[o]=Ga,e},za=T,Ka=ge,qa=H,Ya=function(e){return qa(e)||null===e},Ja=String,Xa=TypeError,Qa=function(e,t,i){try{return za(Ka(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},$a=H,Za=P,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,i={};try{(e=Qa(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return Za(i),es(r),$a(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),is=to,rs=c,os=F,ns=ja,as=Sa,ss=ts,ls=Ua,cs=qt,ds=Qi,us=fa,hs=ei.PROPER,ps=ei.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,i,r,o,n,a){ns(i,t,r);var s,l,c,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 i(this,e)}}return function(){return new i(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)),ls(s,u,!0)),hs&&o===Es&&m&&m.name!==Es&&(ps?cs(p,"name",Es):(h=!0,f=function(){return rs(m,this)})),o)if(l={values:d(Es),keys:n?f:d(gs),entries:d(vs)},a)for(c in l)(fs||h||!(c in p))&&ds(p,c,l[c]);else is({target:t,proto:!0,forced:fs||h},l);return p[_s]!==f&&ds(p,_s,f,{name:o}),us[t]=f,l},Is=function(e,t){return{value:e,done:t}},As=U,Ss=ca,Rs=fa,bs=Ci,ws=Ct.f,Cs=Ts,Ds=Is,Ns=n,ks="Array Iterator",Os=bs.set,Ms=bs.getterFor(ks),Ps=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,i=e.index++;if(!t||i>=t.length)return e.target=null,Ds(void 0,!0);switch(e.kind){case"keys":return Ds(i,!1);case"values":return Ds(t[i],!1)}return Ds([i,t[i]],!1)}),"values"),Ls=Rs.Arguments=Rs.Array;if(Ss("keys"),Ss("values"),Ss("entries"),Ns&&"values"!==Ls.name)try{ws(Ls,"name",{value:"values"})}catch(QK){}var xs=ge,Us=Ve,Vs=N,Fs=hr,Bs=TypeError,Hs="Reduce of empty array with no initial value",Ws=function(e){return function(t,i,r,o){var n=Us(t),a=Vs(n),s=Fs(n);if(xs(i),0===s&&r<2)throw new Bs(Hs);var l=e?s-1:0,c=e?-1:1;if(r<2)for(;;){if(l in a){o=a[l],l+=c;break}if(l+=c,e?l<0:s<=l)throw new Bs(Hs)}for(;e?l>=0:s>l;l+=c)l in a&&(o=i(o,a[l],l,n));return o}},Gs={left:Ws(!1),right:Ws(!0)},js=o,zs=function(e,t){var i=[][e];return!!i&&js((function(){i.call(null,t||function(){return 1},1)}))},Ks=i,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",Qs="NODE"===Xs,$s=Gs.left;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduce")},{reduce:function(e){var t=arguments.length;return $s(this,e,t,t>1?arguments[1]:void 0)}});var Zs=Gs.right;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduceRight")},{reduceRight:function(e){return Zs(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var el=to,tl=zo,il=T([].reverse),rl=[1,2];el({target:"Array",proto:!0,forced:String(rl)===String(rl.reverse())},{reverse:function(){return tl(this)&&(this.length=this.length),il(this)}});var ol=pe,nl=TypeError,al=T([].slice),sl=al,ll=Math.floor,cl=function(e,t){var i=e.length;if(i<8)for(var r,o,n=1;n<i;){for(o=n,r=e[n];o&&t(e[o-1],r)>0;)e[o]=e[--o];o!==n++&&(e[o]=r)}else for(var a=ll(i/2),s=cl(sl(e,0,a),t),l=cl(sl(e,a),t),c=s.length,d=l.length,u=0,h=0;u<c||h<d;)e[u+h]=u<c&&h<d?t(s[u],l[h])<=0?s[u++]:l[h++]:u<c?s[u++]:l[h++];return e},dl=cl,ul=Y.match(/firefox\/(\d+)/i),hl=!!ul&&+ul[1],pl=/MSIE|Trident/.test(Y),ml=Y.match(/AppleWebKit\/(\d+)\./),fl=!!ml&&+ml[1],_l=to,gl=T,El=ge,vl=Ve,yl=hr,Tl=function(e,t){if(!delete e[t])throw new nl("Cannot delete property "+ol(t)+" of "+ol(e))},Il=po,Al=o,Sl=dl,Rl=zs,bl=hl,wl=pl,Cl=te,Dl=fl,Nl=[],kl=gl(Nl.sort),Ol=gl(Nl.push),Ml=Al((function(){Nl.sort(void 0)})),Pl=Al((function(){Nl.sort(null)})),Ll=Rl("sort"),xl=!Al((function(){if(Cl)return Cl<70;if(!(bl&&bl>3)){if(wl)return!0;if(Dl)return Dl<603;var e,t,i,r,o="";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++)Nl.push({k:t+r,v:i})}for(Nl.sort((function(e,t){return t.v-e.v})),r=0;r<Nl.length;r++)t=Nl[r].k.charAt(0),o.charAt(o.length-1)!==t&&(o+=t);return"DGBEFHACIJK"!==o}}));_l({target:"Array",proto:!0,forced:Ml||!Pl||!Ll||!xl},{sort:function(e){void 0!==e&&El(e);var t=vl(this);if(xl)return void 0===e?kl(t):kl(t,e);var i,r,o=[],n=yl(t);for(r=0;r<n;r++)r in t&&Ol(o,t[r]);for(Sl(o,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Il(t)>Il(i)?1:-1}}(e)),i=yl(o),r=0;r<i;)t[r]=o[r++];for(;r<n;)Tl(t,r++);return t}}),ca("flat");var Ul="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Vl=Qi,Fl=function(e,t,i){for(var r in t)Vl(e,r,t[r],i);return e},Bl=z,Hl=TypeError,Wl=function(e,t){if(Bl(t,e))return e;throw new Hl("Incorrect invocation")},Gl=rr,jl=dr,zl=RangeError,Kl=function(e){if(void 0===e)return 0;var t=Gl(e),i=jl(t);if(t!==i)throw new zl("Wrong length or index");return i},ql=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},Yl=4503599627370496,Jl=ql,Xl=function(e){return e+Yl-Yl},Ql=Math.abs,$l=function(e,t,i,r){var o=+e,n=Ql(o),a=Jl(o);if(n<r)return a*Xl(n/r/t)*r*t;var s=(1+t/2220446049250313e-31)*n,l=s-(s-n);return l>i||l!=l?Infinity*a:a*l},Zl=Math.fround||function(e){return $l(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},ec=Array,tc=Math.abs,ic=Math.pow,rc=Math.floor,oc=Math.log,nc=Math.LN2,ac={pack:function(e,t,i){var r,o,n,a=ec(i),s=8*i-t-1,l=(1<<s)-1,c=l>>1,d=23===t?ic(2,-24)-ic(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tc(e))!=e||Infinity===e?(o=e!=e?1:0,r=l):(r=rc(oc(e)/nc),e*(n=ic(2,-r))<1&&(r--,n*=2),(e+=r+c>=1?d/n:d*ic(2,1-c))*n>=2&&(r++,n/=2),r+c>=l?(o=0,r=l):r+c>=1?(o=(e*n-1)*ic(2,t),r+=c):(o=e*ic(2,c-1)*ic(2,t),r=0));t>=8;)a[h++]=255&o,o/=256,t-=8;for(r=r<<t|o,s+=t;s>0;)a[h++]=255&r,r/=256,s-=8;return a[h-1]|=128*u,a},unpack:function(e,t){var i,r=e.length,o=8*r-t-1,n=(1<<o)-1,a=n>>1,s=o-7,l=r-1,c=e[l--],d=127&c;for(c>>=7;s>0;)d=256*d+e[l--],s-=8;for(i=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)i=256*i+e[l--],s-=8;if(0===d)d=1-a;else{if(d===n)return i?NaN:c?-Infinity:Infinity;i+=ic(2,t),d-=a}return(c?-1:1)*i*ic(2,d-t)}},sc=Ve,lc=sr,cc=hr,dc=function(e){for(var t=sc(this),i=cc(t),r=arguments.length,o=lc(r>1?arguments[1]:void 0,i),n=r>2?arguments[2]:void 0,a=void 0===n?i:lc(n,i);a>o;)t[o++]=e;return t},uc=F,hc=H,pc=ts,mc=function(e,t,i){var r,o;return pc&&uc(r=t.constructor)&&r!==i&&hc(o=r.prototype)&&o!==i.prototype&&pc(e,o),e},fc=i,_c=T,gc=n,Ec=Ul,vc=qt,yc=_o,Tc=Fl,Ic=o,Ac=Wl,Sc=rr,Rc=dr,bc=Kl,wc=Zl,Cc=ac,Dc=Sa,Nc=ts,kc=dc,Oc=al,Mc=mc,Pc=Vr,Lc=Ua,xc=Ci,Uc=ei.PROPER,Vc=ei.CONFIGURABLE,Fc="ArrayBuffer",Bc="DataView",Hc="prototype",Wc="Wrong index",Gc=xc.getterFor(Fc),jc=xc.getterFor(Bc),zc=xc.set,Kc=fc[Fc],qc=Kc,Yc=qc&&qc[Hc],Jc=fc[Bc],Xc=Jc&&Jc[Hc],Qc=Object.prototype,$c=fc.Array,Zc=fc.RangeError,ed=_c(kc),td=_c([].reverse),id=Cc.pack,rd=Cc.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]},ld=function(e){return id(wc(e),23,4)},cd=function(e){return id(e,52,8)},dd=function(e,t,i){yc(e[Hc],t,{configurable:!0,get:function(){return i(this)[t]}})},ud=function(e,t,i,r){var o=jc(e),n=bc(i),a=!!r;if(n+t>o.byteLength)throw new Zc(Wc);var s=o.bytes,l=n+o.byteOffset,c=Oc(s,l,l+t);return a?c:td(c)},hd=function(e,t,i,r,o,n){var a=jc(e),s=bc(i),l=r(+o),c=!!n;if(s+t>a.byteLength)throw new Zc(Wc);for(var d=a.bytes,u=s+a.byteOffset,h=0;h<t;h++)d[u+h]=l[c?h:t-h-1]};if(Ec){var pd=Uc&&Kc.name!==Fc;Ic((function(){Kc(1)}))&&Ic((function(){new Kc(-1)}))&&!Ic((function(){return new Kc,new Kc(1.5),new Kc(NaN),1!==Kc.length||pd&&!Vc}))?pd&&Vc&&vc(Kc,"name",Fc):((qc=function(e){return Ac(this,Yc),Mc(new Kc(bc(e)),this,qc)})[Hc]=Yc,Yc.constructor=qc,Pc(qc,Kc)),Nc&&Dc(Xc)!==Qc&&Nc(Xc,Qc);var md=new Jc(new qc(2)),fd=_c(Xc.setInt8);md.setInt8(0,2147483648),md.setInt8(1,2147483649),!md.getInt8(0)&&md.getInt8(1)||Tc(Xc,{setInt8:function(e,t){fd(this,e,t<<24>>24)},setUint8:function(e,t){fd(this,e,t<<24>>24)}},{unsafe:!0})}else Yc=(qc=function(e){Ac(this,Yc);var t=bc(e);zc(this,{type:Fc,bytes:ed($c(t),0),byteLength:t}),gc||(this.byteLength=t,this.detached=!1)})[Hc],Xc=(Jc=function(e,t,i){Ac(this,Xc),Ac(e,Yc);var r=Gc(e),o=r.byteLength,n=Sc(t);if(n<0||n>o)throw new Zc("Wrong offset");if(n+(i=void 0===i?o-n:Rc(i))>o)throw new Zc("Wrong length");zc(this,{type:Bc,buffer:e,byteLength:i,byteOffset:n,bytes:r.bytes}),gc||(this.buffer=e,this.byteLength=i,this.byteOffset=n)})[Hc],gc&&(dd(qc,"byteLength",Gc),dd(Jc,"buffer",jc),dd(Jc,"byteLength",jc),dd(Jc,"byteOffset",jc)),Tc(Xc,{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 rd(ud(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return rd(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,ld,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){hd(this,8,e,cd,t,arguments.length>2&&arguments[2])}});Lc(qc,Fc),Lc(Jc,Bc);var _d={ArrayBuffer:qc,DataView:Jc},gd=j,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:i[Ad]!==Sd},{ArrayBuffer:Sd}),Id(Ad);var Rd=to,bd=Jo,wd=o,Cd=Mt,Dd=sr,Nd=dr,kd=_d.ArrayBuffer,Od=_d.DataView,Md=Od.prototype,Pd=bd(kd.prototype.slice),Ld=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(Pd&&void 0===t)return Pd(Cd(this),e);for(var i=Cd(this).byteLength,r=Dd(e,i),o=Dd(void 0===t?i:t,i),n=new kd(Nd(o-r)),a=new Od(this),s=new Od(n),l=0;r<o;)xd(s,l++,Ld(a,r++));return n}});var Ud,Vd,Fd,Bd,Hd=vn,Wd=pe,Gd=TypeError,jd=function(e){if(Hd(e))return e;throw new Gd(Wd(e)+" is not a constructor")},zd=Mt,Kd=jd,qd=k,Yd=tt("species"),Jd=function(e,t){var i,r=zd(e).constructor;return void 0===r||qd(i=zd(r)[Yd])?t:Kd(i)},Xd=a,Qd=Function.prototype,$d=Qd.apply,Zd=Qd.call,eu="object"==typeof Reflect&&Reflect.apply||(Xd?Zd.bind($d):function(){return Zd.apply($d,arguments)}),tu=TypeError,iu=function(e,t){if(e<t)throw new tu("Not enough arguments");return e},ru=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ou=i,nu=eu,au=Zo,su=F,lu=He,cu=o,du=Gn,uu=al,hu=_t,pu=iu,mu=ru,fu=Qs,_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";cu((function(){Ud=ou.location}));var bu=function(e){if(lu(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),i=uu(arguments,1);return Su[++Au]=function(){nu(t,void 0,i)},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&&!cu(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=i,Ou=n,Mu=Object.getOwnPropertyDescriptor,Pu=function(e){if(!Ou)return ku[e];var t=Mu(ku,e);return t&&t.value},Lu=function(){this.head=null,this.tail=null};Lu.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 xu,Uu,Vu,Fu,Bu,Hu=Lu,Wu=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,Gu=/web0s(?!.*chrome)/i.test(Y),ju=i,zu=Pu,Ku=Zo,qu=Nu.set,Yu=Hu,Ju=ru,Xu=Wu,Qu=Gu,$u=Qs,Zu=ju.MutationObserver||ju.WebKitMutationObserver,eh=ju.document,th=ju.process,ih=ju.Promise,rh=zu("queueMicrotask");if(!rh){var oh=new Yu,nh=function(){var e,t;for($u&&(e=th.domain)&&e.exit();t=oh.get();)try{t()}catch(QK){throw oh.head&&xu(),QK}e&&e.enter()};Ju||$u||Qu||!Zu||!eh?!Xu&&ih&&ih.resolve?((Fu=ih.resolve(void 0)).constructor=ih,Bu=Ku(Fu.then,Fu),xu=function(){Bu(nh)}):$u?xu=function(){th.nextTick(nh)}:(qu=Ku(qu,ju),xu=function(){qu(nh)}):(Uu=!0,Vu=eh.createTextNode(""),new Zu(nh).observe(Vu,{characterData:!0}),xu=function(){Vu.data=Uu=!Uu}),rh=function(e){oh.head||xu(),oh.add(e)}}var ah=rh,sh=function(e){try{return{error:!1,value:e()}}catch(QK){return{error:!0,value:QK}}},lh=i.Promise,ch=i,dh=lh,uh=F,hh=qr,ph=si,mh=tt,fh=Xs,_h=te;dh&&dh.prototype;var gh=mh("species"),Eh=!1,vh=uh(ch.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 i=new dh((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[gh]=r,!(Eh=i.then((function(){}))instanceof r))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,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new Sh("Bad Promise constructor");t=e,i=r})),this.resolve=Ah(t),this.reject=Ah(i)};Ih.f=function(e){return new Rh(e)};var bh,wh,Ch,Dh=to,Nh=Qs,kh=i,Oh=c,Mh=Qi,Ph=ts,Lh=Ua,xh=Td,Uh=ge,Vh=F,Fh=H,Bh=Wl,Hh=Jd,Wh=Nu.set,Gh=ah,jh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(QK){}},zh=sh,Kh=Hu,qh=Ci,Yh=lh,Jh=Ih,Xh="Promise",Qh=Th.CONSTRUCTOR,$h=Th.REJECTION_EVENT,Zh=Th.SUBCLASSING,ep=qh.getterFor(Xh),tp=qh.set,ip=Yh&&Yh.prototype,rp=Yh,op=ip,np=kh.TypeError,ap=kh.document,sp=kh.process,lp=Jh.f,cp=lp,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 i,r,o,n=t.value,a=1===t.state,s=a?e.ok:e.fail,l=e.resolve,c=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&Ep(t),t.rejection=1),!0===s?i=n:(d&&d.enter(),i=s(n),d&&(d.exit(),o=!0)),i===e.promise?c(new np("Promise-chain cycle")):(r=hp(i))?Oh(r,i,l,c):l(i)):c(n)}catch(QK){d&&!o&&d.exit(),c(QK)}},mp=function(e,t){e.notified||(e.notified=!0,Gh((function(){for(var i,r=e.reactions;i=r.get();)pp(i,e);e.notified=!1,t&&!e.rejection&&_p(e)})))},fp=function(e,t,i){var r,o;dp?((r=ap.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),kh.dispatchEvent(r)):r={promise:t,reason:i},!$h&&(o=kh["on"+e])?o(r):e===up&&jh("Unhandled promise rejection",i)},_p=function(e){Oh(Wh,kh,(function(){var t,i=e.facade,r=e.value;if(gp(e)&&(t=zh((function(){Nh?sp.emit("unhandledRejection",r,i):fp(up,i,r)})),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,i){return function(r){e(t,r,i)}},yp=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,mp(e,!0))},Tp=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new np("Promise can't be resolved itself");var r=hp(t);r?Gh((function(){var i={done:!1};try{Oh(r,t,vp(Tp,i,e),vp(yp,i,e))}catch(QK){yp(i,QK,e)}})):(e.value=t,e.state=1,mp(e,!1))}catch(QK){yp({done:!1},QK,e)}}};if(Qh&&(op=(rp=function(e){Bh(this,op),Uh(e),Oh(bh,this);var t=ep(this);try{e(vp(Tp,t),vp(yp,t))}catch(QK){yp(t,QK)}}).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 i=ep(this),r=lp(Hh(this,rp));return i.parent=!0,r.ok=!Vh(e)||e,r.fail=Vh(t)&&t,r.domain=Nh?sp.domain:void 0,0===i.state?i.reactions.add(r):Gh((function(){pp(r,i)})),r.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=lp=function(e){return e===rp||undefined===e?new wh(e):cp(e)},Vh(Yh)&&ip!==Object.prototype)){Ch=ip.then,Zh||Mh(ip,"then",(function(e,t){var i=this;return new rp((function(e,t){Oh(Ch,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete ip.constructor}catch(QK){}Ph&&Ph(ip,op)}Dh({global:!0,constructor:!0,wrap:!0,forced:Qh},{Promise:rp}),Lh(rp,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=co,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=c,Mp=ge,Pp=Mt,Lp=pe,xp=kp,Up=TypeError,Vp=function(e,t){var i=arguments.length<2?xp(e):t;if(Mp(i))return Pp(Op(i,e));throw new Up(Lp(e)+" is not iterable")},Fp=c,Bp=Mt,Hp=ye,Wp=function(e,t,i){var r,o;Bp(e);try{if(!(r=Hp(e,"return"))){if("throw"===t)throw i;return i}r=Fp(r,e)}catch(QK){o=!0,r=QK}if("throw"===t)throw i;if(o)throw r;return Bp(r),i},Gp=Zo,jp=c,zp=Mt,Kp=pe,qp=Rp,Yp=hr,Jp=z,Xp=Vp,Qp=kp,$p=Wp,Zp=TypeError,em=function(e,t){this.stopped=e,this.result=t},tm=em.prototype,im=function(e,t,i){var r,o,n,a,s,l,c,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Gp(t,d),_=function(e){return r&&$p(r,"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)r=e.iterator;else if(p)r=e;else{if(!(o=Qp(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)}r=Xp(e,o)}for(l=h?e.next:r.next;!(c=jp(l,r)).done;){try{s=g(c.value)}catch(QK){$p(r,"throw",QK)}if("object"==typeof s&&s&&Jp(tm,s))return s}return new em(!1)},rm=tt("iterator"),om=!1;try{var nm=0,am={next:function(){return{done:!!nm++}},return:function(){om=!0}};am[rm]=function(){return this},Array.from(am,(function(){throw 2}))}catch(QK){}var sm=function(e,t){try{if(!t&&!om)return!1}catch(QK){return!1}var i=!1;try{var r={};r[rm]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(QK){}return i},lm=lh,cm=Th.CONSTRUCTOR||!sm((function(e){lm.all(e).then(void 0,(function(){}))})),dm=c,um=ge,hm=Ih,pm=sh,mm=im;to({target:"Promise",stat:!0,forced:cm},{all:function(e){var t=this,i=hm.f(t),r=i.resolve,o=i.reject,n=pm((function(){var i=um(t.resolve),n=[],a=0,s=1;mm(e,(function(e){var l=a++,c=!1;s++,dm(i,t,e).then((function(e){c||(c=!0,n[l]=e,--s||r(n))}),o)})),--s||r(n)}));return n.error&&o(n.value),i.promise}});var fm=to,_m=Th.CONSTRUCTOR,gm=lh,Em=j,vm=F,ym=Qi,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=c,Sm=ge,Rm=Ih,bm=sh,wm=im;to({target:"Promise",stat:!0,forced:cm},{race:function(e){var t=this,i=Rm.f(t),r=i.reject,o=bm((function(){var o=Sm(t.resolve);wm(e,(function(e){Am(o,t,e).then(i.resolve,r)}))}));return o.error&&r(o.value),i.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 i=km.f(e);return(0,i.resolve)(t),i.promise},Mm=to,Pm=Th.CONSTRUCTOR,Lm=Om;j("Promise"),Mm({target:"Promise",stat:!0,forced:Pm},{resolve:function(e){return Lm(this,e)}});var xm=to,Um=lh,Vm=o,Fm=j,Bm=F,Hm=Jd,Wm=Om,Gm=Qi,jm=Um&&Um.prototype;if(xm({target:"Promise",proto:!0,real:!0,forced:!!Um&&Vm((function(){jm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Hm(this,Fm("Promise")),i=Bm(e);return this.then(i?function(i){return Wm(t,e()).then((function(){return i}))}:e,i?function(i){return Wm(t,e()).then((function(){throw i}))}:e)}}),Bm(Um)){var zm=Fm("Promise").prototype.finally;jm.finally!==zm&&Gm(jm,"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,Qm=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},$m=c,Zm=He,ef=z,tf=Qm,rf=RegExp.prototype,of=function(e){var t=e.flags;return void 0!==t||"flags"in rf||Zm(e,"flags")||!ef(rf,e)?t:$m(tf,e)},nf=o,af=i.RegExp,sf=nf((function(){var e=af("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),lf=sf||nf((function(){return!af("a","y").sticky})),cf=sf||nf((function(){var e=af("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),df={BROKEN_CARET:cf,MISSED_STICKY:lf,UNSUPPORTED_Y:sf},uf=Ct.f,hf=o,pf=i.RegExp,mf=hf((function(){var e=pf(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),ff=o,_f=i.RegExp,gf=ff((function(){var e=_f("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Ef=n,vf=i,yf=T,Tf=qr,If=mc,Af=qt,Sf=ra,Rf=$i.f,bf=z,wf=Jm,Cf=po,Df=of,Nf=df,kf=function(e,t,i){i in e||uf(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Of=Qi,Mf=o,Pf=He,Lf=Ci.enforce,xf=Td,Uf=mf,Vf=gf,Ff=tt("match"),Bf=vf.RegExp,Hf=Bf.prototype,Wf=vf.SyntaxError,Gf=yf(Hf.exec),jf=yf("".charAt),zf=yf("".replace),Kf=yf("".indexOf),qf=yf("".slice),Yf=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Jf=/a/g,Xf=/a/g,Qf=new Bf(Jf)!==Jf,$f=Nf.MISSED_STICKY,Zf=Nf.UNSUPPORTED_Y,e_=Ef&&(!Qf||$f||Uf||Vf||Mf((function(){return Xf[Ff]=!1,Bf(Jf)!==Jf||Bf(Xf)===Xf||"/a/i"!==String(Bf(Jf,"i"))})));if(Tf("RegExp",e_)){for(var t_=function(e,t){var i,r,o,n,a,s,l=bf(Hf,this),c=wf(e),d=void 0===t,u=[],h=e;if(!l&&c&&d&&e.constructor===t_)return e;if((c||bf(Hf,e))&&(e=e.source,d&&(t=Df(h))),e=void 0===e?"":Cf(e),t=void 0===t?"":Cf(t),h=e,Uf&&"dotAll"in Jf&&(r=!!t&&Kf(t,"s")>-1)&&(t=zf(t,/s/g,"")),i=t,$f&&"sticky"in Jf&&(o=!!t&&Kf(t,"y")>-1)&&Zf&&(t=zf(t,/y/g,"")),Vf&&(n=function(e){for(var t,i=e.length,r=0,o="",n=[],a=Sf(null),s=!1,l=!1,c=0,d="";r<=i;r++){if("\\"===(t=jf(e,r)))t+=jf(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:if(o+=t,"?:"===qf(e,r+1,r+3))continue;Gf(Yf,qf(e,r+1))&&(r+=2,l=!0),c++;continue;case">"===t&&l:if(""===d||Pf(a,d))throw new Wf("Invalid capture group name");a[d]=!0,n[n.length]=[d,c],l=!1,d="";continue}l?d+=t:o+=t}return[o,n]}(e),e=n[0],u=n[1]),a=If(Bf(e,t),l?this:Hf,t_),(r||o||u.length)&&(s=Lf(a),r&&(s.dotAll=!0,s.raw=t_(function(e){for(var t,i=e.length,r=0,o="",n=!1;r<=i;r++)"\\"!==(t=jf(e,r))?n||"."!==t?("["===t?n=!0:"]"===t&&(n=!1),o+=t):o+="[\\s\\S]":o+=t+jf(e,++r);return o}(e),i)),o&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{Af(a,"source",""===h?"(?:)":h)}catch(QK){}return a},i_=Rf(Bf),r_=0;i_.length>r_;)kf(t_,Bf,i_[r_++]);Hf.constructor=t_,t_.prototype=Hf,Of(vf,"RegExp",t_,{constructor:!0})}xf("RegExp");var o_=c,n_=T,a_=po,s_=Qm,l_=df,c_=ra,d_=Ci.get,u_=mf,h_=gf,p_=Le("native-string-replace",String.prototype.replace),m_=RegExp.prototype.exec,f_=m_,__=n_("".charAt),g_=n_("".indexOf),E_=n_("".replace),v_=n_("".slice),y_=function(){var e=/a/,t=/b*/g;return o_(m_,e,"a"),o_(m_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),T_=l_.BROKEN_CARET,I_=void 0!==/()??/.exec("")[1];(y_||I_||T_||u_||h_)&&(f_=function(e){var t,i,r,o,n,a,s,l=this,c=d_(l),d=a_(e),u=c.raw;if(u)return u.lastIndex=l.lastIndex,t=o_(f_,u,d),l.lastIndex=u.lastIndex,t;var h=c.groups,p=T_&&l.sticky,m=o_(s_,l),f=l.source,_=0,g=d;if(p&&(m=E_(m,"y",""),-1===g_(m,"g")&&(m+="g"),g=v_(d,l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&"\n"!==__(d,l.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),i=new RegExp("^(?:"+f+")",m)),I_&&(i=new RegExp("^"+f+"$(?!\\s)",m)),y_&&(r=l.lastIndex),o=o_(m_,p?i:l,g),p?o?(o.input=v_(o.input,_),o[0]=v_(o[0],_),o.index=l.lastIndex,l.lastIndex+=o[0].length):l.lastIndex=0:y_&&o&&(l.lastIndex=l.global?o.index+o[0].length:r),I_&&o&&o.length>1&&o_(p_,o[0],i,(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 A_=f_;to({target:"RegExp",proto:!0,forced:/./.exec!==A_},{exec:A_});var S_=n,R_=_o,b_=Qm,w_=o,C_=i.RegExp,D_=C_.prototype,N_=S_&&w_((function(){var e=!0;try{C_(".","d")}catch(QK){e=!1}var t={},i="",r=e?"dgimsy":"gimsy",o=function(e,r){Object.defineProperty(t,e,{get:function(){return i+=r,!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(D_,"flags").get.call(t)!==r||i!==r}));N_&&R_(D_,"flags",{configurable:!0,get:b_});var k_=rr,O_=po,M_=P,P_=RangeError,L_=T,x_=dr,U_=po,V_=function(e){var t=O_(M_(this)),i="",r=k_(e);if(r<0||Infinity===r)throw new P_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},F_=P,B_=L_(V_),H_=L_("".slice),W_=Math.ceil,G_=function(e){return function(t,i,r){var o,n,a=U_(F_(t)),s=x_(i),l=a.length,c=void 0===r?" ":U_(r);return s<=l||""===c?a:((n=B_(c,W_((o=s-l)/c.length))).length>o&&(n=H_(n,0,o)),e?a+n:n+a)}},j_={start:G_(!1),end:G_(!0)},z_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),K_=j_.start;to({target:"String",proto:!0,forced:z_},{padStart:function(e){return K_(this,e,arguments.length>1?arguments[1]:void 0)}});var q_=c,Y_=Qi,J_=A_,X_=o,Q_=tt,$_=qt,Z_=Q_("species"),eg=RegExp.prototype,tg=T,ig=rr,rg=po,og=P,ng=tg("".charAt),ag=tg("".charCodeAt),sg=tg("".slice),lg=function(e){return function(t,i){var r,o,n=rg(og(t)),a=ig(i),s=n.length;return a<0||a>=s?e?"":void 0:(r=ag(n,a))<55296||r>56319||a+1===s||(o=ag(n,a+1))<56320||o>57343?e?ng(n,a):r:e?sg(n,a,a+2):o-56320+(r-55296<<10)+65536}},cg={codeAt:lg(!1),charAt:lg(!0)},dg=cg.charAt,ug=T,hg=Ve,pg=Math.floor,mg=ug("".charAt),fg=ug("".replace),_g=ug("".slice),gg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Eg=/\$([$&'`]|\d{1,2})/g,vg=function(e,t,i,r,o,n){var a=i+e.length,s=r.length,l=Eg;return void 0!==o&&(o=hg(o),l=gg),fg(n,l,(function(n,l){var c;switch(mg(l,0)){case"$":return"$";case"&":return e;case"`":return _g(t,0,i);case"'":return _g(t,a);case"<":c=o[_g(l,1,-1)];break;default:var d=+l;if(0===d)return n;if(d>s){var u=pg(d/10);return 0===u?n:u<=s?void 0===r[u-1]?mg(l,1):r[u-1]+mg(l,1):n}c=r[d-1]}return void 0===c?"":c}))},yg=c,Tg=Mt,Ig=F,Ag=R,Sg=A_,Rg=TypeError,bg=eu,wg=c,Cg=T,Dg=function(e,t,i,r){var o=Q_(e),n=!X_((function(){var t={};return t[o]=function(){return 7},7!==""[e](t)})),a=n&&!X_((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Z_]=function(){return i},i.flags="",i[o]=/./[o]),i.exec=function(){return t=!0,null},i[o](""),!t}));if(!n||!a||i){var s=/./[o],l=t(o,""[e],(function(e,t,i,r,o){var a=t.exec;return a===J_||a===eg.exec?n&&!o?{done:!0,value:q_(s,t,i,r)}:{done:!0,value:q_(e,i,t,r)}:{done:!1}}));Y_(String.prototype,e,l[0]),Y_(eg,o,l[1])}r&&$_(eg[o],"sham",!0)},Ng=o,kg=Mt,Og=F,Mg=k,Pg=rr,Lg=dr,xg=po,Ug=P,Vg=function(e,t,i){return t+(i?dg(e,t).length:1)},Fg=ye,Bg=vg,Hg=function(e,t){var i=e.exec;if(Ig(i)){var r=yg(i,e,t);return null!==r&&Tg(r),r}if("RegExp"===Ag(e))return yg(Sg,e,t);throw new Rg("RegExp#exec called on incompatible receiver")},Wg=tt("replace"),Gg=Math.max,jg=Math.min,zg=Cg([].concat),Kg=Cg([].push),qg=Cg("".indexOf),Yg=Cg("".slice),Jg="$0"==="a".replace(/./,"$0"),Xg=!!/./[Wg]&&""===/./[Wg]("a","$0"),Qg=!Ng((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Dg("replace",(function(e,t,i){var r=Xg?"$":"$0";return[function(e,i){var r=Ug(this),o=Mg(e)?void 0:Fg(e,Wg);return o?wg(o,e,r,i):wg(t,xg(r),e,i)},function(e,o){var n=kg(this),a=xg(e);if("string"==typeof o&&-1===qg(o,r)&&-1===qg(o,"$<")){var s=i(t,n,a,o);if(s.done)return s.value}var l=Og(o);l||(o=xg(o));var c,d=n.global;d&&(c=n.unicode,n.lastIndex=0);for(var u,h=[];null!==(u=Hg(n,a))&&(Kg(h,u),d);){""===xg(u[0])&&(n.lastIndex=Vg(a,Lg(n.lastIndex),c))}for(var p,m="",f=0,_=0;_<h.length;_++){for(var g,E=xg((u=h[_])[0]),v=Gg(jg(Pg(u.index),a.length),0),y=[],T=1;T<u.length;T++)Kg(y,void 0===(p=u[T])?p:String(p));var I=u.groups;if(l){var A=zg([E],y,v,a);void 0!==I&&Kg(A,I),g=xg(bg(o,void 0,A))}else g=Bg(E,a,v,y,I,o);v>=f&&(m+=Yg(a,f,v)+g,f=v+E.length)}return m+Yg(a,f)}]}),!Qg||!Jg||Xg);var $g="\t\n\v\f\r \u2028\u2029\ufeff",Zg=P,eE=po,tE=$g,iE=T("".replace),rE=RegExp("^["+tE+"]+"),oE=RegExp("(^|[^"+tE+"])["+tE+"]+$"),nE=function(e){return function(t){var i=eE(Zg(t));return 1&e&&(i=iE(i,rE,"")),2&e&&(i=iE(i,oE,"$1")),i}},aE={start:nE(1),end:nE(2),trim:nE(3)},sE=ei.PROPER,lE=o,cE=$g,dE=aE.trim;to({target:"String",proto:!0,forced:function(e){return lE((function(){return!!cE[e]()||"
"!=="
"[e]()||sE&&cE[e].name!==e}))}("trim")},{trim:function(){return dE(this)}});var uE,hE,pE,mE={exports:{}},fE=Ul,_E=n,gE=i,EE=F,vE=H,yE=He,TE=co,IE=pe,AE=qt,SE=Qi,RE=_o,bE=z,wE=Sa,CE=ts,DE=tt,NE=Ke,kE=Ci.enforce,OE=Ci.get,ME=gE.Int8Array,PE=ME&&ME.prototype,LE=gE.Uint8ClampedArray,xE=LE&&LE.prototype,UE=ME&&wE(ME),VE=PE&&wE(PE),FE=Object.prototype,BE=gE.TypeError,HE=DE("toStringTag"),WE=NE("TYPED_ARRAY_TAG"),GE="TypedArrayConstructor",jE=fE&&!!CE&&"Opera"!==TE(gE.opera),zE=!1,KE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},qE={BigInt64Array:8,BigUint64Array:8},YE=function(e){var t=wE(e);if(vE(t)){var i=OE(t);return i&&yE(i,GE)?i[GE]:YE(t)}},JE=function(e){if(!vE(e))return!1;var t=TE(e);return yE(KE,t)||yE(qE,t)};for(uE in KE)(pE=(hE=gE[uE])&&hE.prototype)?kE(pE)[GE]=hE:jE=!1;for(uE in qE)(pE=(hE=gE[uE])&&hE.prototype)&&(kE(pE)[GE]=hE);if((!jE||!EE(UE)||UE===Function.prototype)&&(UE=function(){throw new BE("Incorrect invocation")},jE))for(uE in KE)gE[uE]&&CE(gE[uE],UE);if((!jE||!VE||VE===FE)&&(VE=UE.prototype,jE))for(uE in KE)gE[uE]&&CE(gE[uE].prototype,VE);if(jE&&wE(xE)!==VE&&CE(xE,VE),_E&&!yE(VE,HE))for(uE in zE=!0,RE(VE,HE,{configurable:!0,get:function(){return vE(this)?this[WE]:void 0}}),KE)gE[uE]&&AE(gE[uE],WE,uE);var XE={NATIVE_ARRAY_BUFFER_VIEWS:jE,TYPED_ARRAY_TAG:zE&&WE,aTypedArray:function(e){if(JE(e))return e;throw new BE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(EE(e)&&(!CE||bE(UE,e)))return e;throw new BE(IE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(_E){if(i)for(var o in KE){var n=gE[o];if(n&&yE(n.prototype,e))try{delete n.prototype[e]}catch(QK){try{n.prototype[e]=t}catch(a){}}}VE[e]&&!i||SE(VE,e,i?t:jE&&PE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,o;if(_E){if(CE){if(i)for(r in KE)if((o=gE[r])&&yE(o,e))try{delete o[e]}catch(QK){}if(UE[e]&&!i)return;try{return SE(UE,e,i?t:jE&&UE[e]||t)}catch(QK){}}for(r in KE)!(o=gE[r])||o[e]&&!i||SE(o,e,t)}},getTypedArrayConstructor:YE,isView:function(e){if(!vE(e))return!1;var t=TE(e);return"DataView"===t||yE(KE,t)||yE(qE,t)},isTypedArray:JE,TypedArray:UE,TypedArrayPrototype:VE},QE=i,$E=o,ZE=sm,ev=XE.NATIVE_ARRAY_BUFFER_VIEWS,tv=QE.ArrayBuffer,iv=QE.Int8Array,rv=!ev||!$E((function(){iv(1)}))||!$E((function(){new iv(-1)}))||!ZE((function(e){new iv,new iv(null),new iv(1.5),new iv(e)}),!0)||$E((function(){return 1!==new iv(new tv(2),1,void 0).length})),ov=H,nv=Math.floor,av=Number.isInteger||function(e){return!ov(e)&&isFinite(e)&&nv(e)===e},sv=rr,lv=RangeError,cv=function(e){var t=sv(e);if(t<0)throw new lv("The argument can't be less than 0");return t},dv=RangeError,uv=function(e,t){var i=cv(e);if(i%t)throw new dv("Wrong offset");return i},hv=Math.round,pv=co,mv=ct,fv=TypeError,_v=function(e){var t=mv(e,"number");if("number"==typeof t)throw new fv("Can't convert number to bigint");return BigInt(t)},gv=Zo,Ev=c,vv=jd,yv=Ve,Tv=hr,Iv=Vp,Av=kp,Sv=Rp,Rv=function(e){var t=pv(e);return"BigInt64Array"===t||"BigUint64Array"===t},bv=XE.aTypedArrayConstructor,wv=_v,Cv=Zo,Dv=N,Nv=Ve,kv=hr,Ov=bn,Mv=T([].push),Pv=function(e){var t=1===e,i=2===e,r=3===e,o=4===e,n=6===e,a=7===e,s=5===e||n;return function(l,c,d,u){for(var h,p,m=Nv(l),f=Dv(m),_=kv(f),g=Cv(c,d),E=0,v=u||Ov,y=t?v(l,_):i||a?v(l,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:Mv(y,h)}else switch(e){case 4:return!1;case 7:Mv(y,h)}return n?-1:r||o?o:y}},Lv={forEach:Pv(0),map:Pv(1),filter:Pv(2),some:Pv(3),every:Pv(4),find:Pv(5),findIndex:Pv(6),filterReject:Pv(7)},xv=hr,Uv=to,Vv=i,Fv=c,Bv=n,Hv=rv,Wv=XE,Gv=_d,jv=Wl,zv=_,Kv=qt,qv=av,Yv=dr,Jv=Kl,Xv=uv,Qv=function(e){var t=hv(e);return t<0?0:t>255?255:255&t},$v=ht,Zv=He,ey=co,ty=H,iy=ue,ry=ra,oy=z,ny=ts,ay=$i.f,sy=function(e){var t,i,r,o,n,a,s,l,c=vv(this),d=yv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Av(d);if(m&&!Sv(m))for(l=(s=Iv(d,m)).next,d=[];!(a=Ev(l,s)).done;)d.push(a.value);for(p&&u>2&&(h=gv(h,arguments[2])),i=Tv(d),r=new(bv(c))(i),o=Rv(r),t=0;i>t;t++)n=p?h(d[t],t):d[t],r[t]=o?wv(n):+n;return r},ly=Lv.forEach,cy=Td,dy=_o,uy=Ct,hy=r,py=function(e,t,i){for(var r=0,o=arguments.length>2?i:xv(t),n=new e(o);o>r;)n[r]=t[r++];return n},my=mc,fy=Ci.get,_y=Ci.set,gy=Ci.enforce,Ey=uy.f,vy=hy.f,yy=Vv.RangeError,Ty=Gv.ArrayBuffer,Iy=Ty.prototype,Ay=Gv.DataView,Sy=Wv.NATIVE_ARRAY_BUFFER_VIEWS,Ry=Wv.TYPED_ARRAY_TAG,by=Wv.TypedArray,wy=Wv.TypedArrayPrototype,Cy=Wv.isTypedArray,Dy="BYTES_PER_ELEMENT",Ny="Wrong length",ky=function(e,t){dy(e,t,{configurable:!0,get:function(){return fy(this)[t]}})},Oy=function(e){var t;return oy(Iy,e)||"ArrayBuffer"===(t=ey(e))||"SharedArrayBuffer"===t},My=function(e,t){return Cy(e)&&!iy(t)&&t in e&&qv(+t)&&t>=0},Py=function(e,t){return t=$v(t),My(e,t)?zv(2,e[t]):vy(e,t)},Ly=function(e,t,i){return t=$v(t),!(My(e,t)&&ty(i)&&Zv(i,"value"))||Zv(i,"get")||Zv(i,"set")||i.configurable||Zv(i,"writable")&&!i.writable||Zv(i,"enumerable")&&!i.enumerable?Ey(e,t,i):(e[t]=i.value,e)};Bv?(Sy||(hy.f=Py,uy.f=Ly,ky(wy,"buffer"),ky(wy,"byteOffset"),ky(wy,"byteLength"),ky(wy,"length")),Uv({target:"Object",stat:!0,forced:!Sy},{getOwnPropertyDescriptor:Py,defineProperty:Ly}),mE.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,o=e+(i?"Clamped":"")+"Array",n="get"+e,a="set"+e,s=Vv[o],l=s,c=l&&l.prototype,d={},u=function(e,t){Ey(e,t,{get:function(){return function(e,t){var i=fy(e);return i.view[n](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,o){var n=fy(e);n.view[a](t*r+n.byteOffset,i?Qv(o):o,!0)}(this,t,e)},enumerable:!0})};Sy?Hv&&(l=t((function(e,t,i,o){return jv(e,c),my(ty(t)?Oy(t)?void 0!==o?new s(t,Xv(i,r),o):void 0!==i?new s(t,Xv(i,r)):new s(t):Cy(t)?py(l,t):Fv(sy,l,t):new s(Jv(t)),e,l)})),ny&&ny(l,by),ly(ay(s),(function(e){e in l||Kv(l,e,s[e])})),l.prototype=c):(l=t((function(e,t,i,o){jv(e,c);var n,a,s,d=0,h=0;if(ty(t)){if(!Oy(t))return Cy(t)?py(l,t):Fv(sy,l,t);n=t,h=Xv(i,r);var p=t.byteLength;if(void 0===o){if(p%r)throw new yy(Ny);if((a=p-h)<0)throw new yy(Ny)}else if((a=Yv(o)*r)+h>p)throw new yy(Ny);s=a/r}else s=Jv(t),n=new Ty(a=s*r);for(_y(e,{buffer:n,byteOffset:h,byteLength:a,length:s,view:new Ay(n)});d<s;)u(e,d++)})),ny&&ny(l,by),c=l.prototype=ry(wy)),c.constructor!==l&&Kv(c,"constructor",l),gy(c).TypedArrayConstructor=l,Ry&&Kv(c,Ry,o);var h=l!==s;d[o]=l,Uv({global:!0,constructor:!0,forced:h,sham:!Sy},d),Dy in l||Kv(l,Dy,r),Dy in c||Kv(c,Dy,r),cy(o)}):mE.exports=function(){};var xy=mE.exports;xy("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Float64",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int8",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int16",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}),!0),xy("Uint16",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var Uy=dc,Vy=_v,Fy=co,By=c,Hy=o,Wy=XE.aTypedArray,Gy=XE.exportTypedArrayMethod,jy=T("".slice);Gy("fill",(function(e){var t=arguments.length;Wy(this);var i="Big"===jy(Fy(this),0,3)?Vy(e):+e;return By(Uy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),Hy((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var zy=i,Ky=c,qy=XE,Yy=hr,Jy=uv,Xy=Ve,Qy=o,$y=zy.RangeError,Zy=zy.Int8Array,eT=Zy&&Zy.prototype,tT=eT&&eT.set,iT=qy.aTypedArray,rT=qy.exportTypedArrayMethod,oT=!Qy((function(){var e=new Uint8ClampedArray(2);return Ky(tT,e,{length:1,0:3},1),3!==e[1]})),nT=oT&&qy.NATIVE_ARRAY_BUFFER_VIEWS&&Qy((function(){var e=new Zy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));rT("set",(function(e){iT(this);var t=Jy(arguments.length>1?arguments[1]:void 0,1),i=Xy(e);if(oT)return Ky(tT,this,i,t);var r=this.length,o=Yy(i),n=0;if(o+t>r)throw new $y("Wrong length");for(;n<o;)this[t+n]=i[n++]}),!oT||nT);var aT=Jo,sT=o,lT=ge,cT=dl,dT=hl,uT=pl,hT=te,pT=fl,mT=XE.aTypedArray,fT=XE.exportTypedArrayMethod,_T=i.Uint16Array,gT=_T&&aT(_T.prototype.sort),ET=!(!gT||sT((function(){gT(new _T(2),null)}))&&sT((function(){gT(new _T(2),{})}))),vT=!!gT&&!sT((function(){if(hT)return hT<74;if(dT)return dT<67;if(uT)return!0;if(pT)return pT<602;var e,t,i=new _T(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(gT(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));fT("sort",(function(e){return void 0!==e&&lT(e),vT?gT(this,e):cT(mT(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))}),!vT||ET);var yT=to,TT=c,IT=T,AT=P,ST=F,RT=k,bT=Jm,wT=po,CT=ye,DT=of,NT=vg,kT=tt("replace"),OT=TypeError,MT=IT("".indexOf);IT("".replace);var PT=IT("".slice),LT=Math.max;yT({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,o,n,a,s,l,c,d,u=AT(this),h=0,p="";if(!RT(e)){if(bT(e)&&(i=wT(AT(DT(e))),!~MT(i,"g")))throw new OT("`.replaceAll` does not allow non-global regexes");if(r=CT(e,kT))return TT(r,e,u,t)}for(o=wT(u),n=wT(e),(a=ST(t))||(t=wT(t)),s=n.length,l=LT(1,s),c=MT(o,n);-1!==c;)d=a?wT(t(n,c,o)):NT(n,o,c,[],void 0,t),p+=PT(o,h,c)+d,h=c+s,c=c+l>o.length?-1:MT(o,n,c+l);return h<o.length&&(p+=PT(o,h)),p}});var xT={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},UT=_t("span").classList,VT=UT&&UT.constructor&&UT.constructor.prototype,FT=VT===Object.prototype?void 0:VT,BT=Lv.forEach,HT=zs("forEach")?[].forEach:function(e){return BT(this,e,arguments.length>1?arguments[1]:void 0)},WT=i,GT=xT,jT=FT,zT=HT,KT=qt,qT=function(e){if(e&&e.forEach!==zT)try{KT(e,"forEach",zT)}catch(QK){e.forEach=zT}};for(var YT in GT)GT[YT]&&qT(WT[YT]&&WT[YT].prototype);qT(jT);var JT=i,XT=xT,QT=FT,$T=Ps,ZT=qt,eI=Ua,tI=tt("iterator"),iI=$T.values,rI=function(e,t){if(e){if(e[tI]!==iI)try{ZT(e,tI,iI)}catch(QK){e[tI]=iI}if(eI(e,t,!0),XT[t])for(var i in $T)if(e[i]!==$T[i])try{ZT(e,i,$T[i])}catch(QK){e[i]=$T[i]}}};for(var oI in XT)rI(JT[oI]&&JT[oI].prototype,oI);rI(QT,"DOMTokenList");var nI=Nu.clear;to({global:!0,bind:!0,enumerable:!0,forced:i.clearImmediate!==nI},{clearImmediate:nI});var aI=i,sI=eu,lI=F,cI=Xs,dI=Y,uI=al,hI=iu,pI=aI.Function,mI=/MSIE .\./.test(dI)||"BUN"===cI&&function(){var e=aI.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),fI=to,_I=i,gI=Nu.set,EI=function(e,t){var i=t?2:1;return mI?function(r,o){var n=hI(arguments.length,1)>i,a=lI(r)?r:pI(r),s=n?uI(arguments,i):[],l=n?function(){sI(a,this,s)}:a;return t?e(l,o):e(l)}:e},vI=_I.setImmediate?EI(gI,!1):gI;fI({global:!0,bind:!0,enumerable:!0,forced:_I.setImmediate!==vI},{setImmediate:vI});var yI=cg.charAt,TI=po,II=Ci,AI=Ts,SI=Is,RI="String Iterator",bI=II.set,wI=II.getterFor(RI);AI(String,"String",(function(e){bI(this,{type:RI,string:TI(e),index:0})}),(function(){var e,t=wI(this),i=t.string,r=t.index;return r>=i.length?SI(void 0,!0):(e=yI(i,r),t.index+=e.length,SI(e,!1))}));var CI=o,DI=n,NI=tt("iterator"),kI=!CI((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&&!DI||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[NI]||"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})),OI=n,MI=T,PI=c,LI=o,xI=Ln,UI=wr,VI=d,FI=Ve,BI=N,HI=Object.assign,WI=Object.defineProperty,GI=MI([].concat),jI=!HI||LI((function(){if(OI&&1!==HI({b:1},HI(WI({},"a",{enumerable:!0,get:function(){WI(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!==HI({},e)[i]||xI(HI({},t)).join("")!==r}))?function(e,t){for(var i=FI(e),r=arguments.length,o=1,n=UI.f,a=VI.f;r>o;)for(var s,l=BI(arguments[o++]),c=n?GI(xI(l),n(l)):xI(l),d=c.length,u=0;d>u;)s=c[u++],OI&&!PI(a,l,s)||(i[s]=l[s]);return i}:HI,zI=Mt,KI=Wp,qI=n,YI=Ct,JI=_,XI=Zo,QI=c,$I=Ve,ZI=function(e,t,i,r){try{return r?t(zI(i)[0],i[1]):t(i)}catch(QK){KI(e,"throw",QK)}},eA=Rp,tA=vn,iA=hr,rA=function(e,t,i){qI?YI.f(e,t,JI(0,i)):e[t]=i},oA=Vp,nA=kp,aA=Array,sA=T,lA=2147483647,cA=/[^\0-\u007E]/,dA=/[.\u3002\uFF0E\uFF61]/g,uA="Overflow: input needs wider integers to process",hA=RangeError,pA=sA(dA.exec),mA=Math.floor,fA=String.fromCharCode,_A=sA("".charCodeAt),gA=sA([].join),EA=sA([].push),vA=sA("".replace),yA=sA("".split),TA=sA("".toLowerCase),IA=function(e){return e+22+75*(e<26)},AA=function(e,t,i){var r=0;for(e=i?mA(e/700):e>>1,e+=mA(e/t);e>455;)e=mA(e/35),r+=36;return mA(r+36*e/(e+38))},SA=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var o=_A(e,i++);if(o>=55296&&o<=56319&&i<r){var n=_A(e,i++);56320==(64512&n)?EA(t,((1023&o)<<10)+(1023&n)+65536):(EA(t,o),i--)}else EA(t,o)}return t}(e);var i,r,o=e.length,n=128,a=0,s=72;for(i=0;i<e.length;i++)(r=e[i])<128&&EA(t,fA(r));var l=t.length,c=l;for(l&&EA(t,"-");c<o;){var d=lA;for(i=0;i<e.length;i++)(r=e[i])>=n&&r<d&&(d=r);var u=c+1;if(d-n>mA((lA-a)/u))throw new hA(uA);for(a+=(d-n)*u,n=d,i=0;i<e.length;i++){if((r=e[i])<n&&++a>lA)throw new hA(uA);if(r===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;EA(t,fA(IA(m+f%_))),h=mA(f/_),p+=36}EA(t,fA(IA(h))),s=AA(a,u,c===l),a=0,c++}}a++,n++}return gA(t,"")},RA=to,bA=T,wA=sr,CA=RangeError,DA=String.fromCharCode,NA=String.fromCodePoint,kA=bA([].join);RA({target:"String",stat:!0,arity:1,forced:!!NA&&1!==NA.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,o=0;r>o;){if(t=+arguments[o++],wA(t,1114111)!==t)throw new CA(t+" is not a valid code point");i[o]=t<65536?DA(t):DA(55296+((t-=65536)>>10),t%1024+56320)}return kA(i,"")}});var OA=to,MA=i,PA=Pu,LA=j,xA=c,UA=T,VA=n,FA=kI,BA=Qi,HA=_o,WA=Fl,GA=Ua,jA=ja,zA=Ci,KA=Wl,qA=F,YA=He,JA=Zo,XA=co,QA=Mt,$A=H,ZA=po,eS=ra,tS=_,iS=Vp,rS=kp,oS=Is,nS=iu,aS=dl,sS=tt("iterator"),lS="URLSearchParams",cS=lS+"Iterator",dS=zA.set,uS=zA.getterFor(lS),hS=zA.getterFor(cS),pS=PA("fetch"),mS=PA("Request"),fS=PA("Headers"),_S=mS&&mS.prototype,gS=fS&&fS.prototype,ES=MA.TypeError,vS=MA.encodeURIComponent,yS=String.fromCharCode,TS=LA("String","fromCodePoint"),IS=parseInt,AS=UA("".charAt),SS=UA([].join),RS=UA([].push),bS=UA("".replace),wS=UA([].shift),CS=UA([].splice),DS=UA("".split),NS=UA("".slice),kS=UA(/./.exec),OS=/\+/g,MS=/^[0-9a-f]+$/i,PS=function(e,t){var i=NS(e,t,t+2);return kS(MS,i)?IS(i,16):NaN},LS=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},xS=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},US=function(e){for(var t=(e=bS(e,OS," ")).length,i="",r=0;r<t;){var o=AS(e,r);if("%"===o){if("%"===AS(e,r+1)||r+3>t){i+="%",r++;continue}var n=PS(e,r+1);if(n!=n){i+=o,r++;continue}r+=2;var a=LS(n);if(0===a)o=yS(n);else{if(1===a||a>4){i+="�",r++;continue}for(var s=[n],l=1;l<a&&!(++r+3>t||"%"!==AS(e,r));){var c=PS(e,r+1);if(c!=c){r+=3;break}if(c>191||c<128)break;RS(s,c),r+=2,l++}if(s.length!==a){i+="�";continue}var d=xS(s);null===d?i+="�":o=TS(d)}}i+=o,r++}return i},VS=/[!'()~]|%20/g,FS={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},BS=function(e){return FS[e]},HS=function(e){return bS(vS(e),VS,BS)},WS=jA((function(e,t){dS(this,{type:cS,target:uS(e).entries,index:0,kind:t})}),lS,(function(){var e=hS(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,oS(void 0,!0);var r=t[i];switch(e.kind){case"keys":return oS(r.key,!1);case"values":return oS(r.value,!1)}return oS([r.key,r.value],!1)}),!0),GS=function(e){this.entries=[],this.url=null,void 0!==e&&($A(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===AS(e,0)?NS(e,1):e:ZA(e)))};GS.prototype={type:lS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,o,n,a,s,l=this.entries,c=rS(e);if(c)for(i=(t=iS(e,c)).next;!(r=xA(i,t)).done;){if(n=(o=iS(QA(r.value))).next,(a=xA(n,o)).done||(s=xA(n,o)).done||!xA(n,o).done)throw new ES("Expected sequence with length 2");RS(l,{key:ZA(a.value),value:ZA(s.value)})}else for(var d in e)YA(e,d)&&RS(l,{key:d,value:ZA(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,o=DS(e,"&"),n=0;n<o.length;)(t=o[n++]).length&&(i=DS(t,"="),RS(r,{key:US(wS(i)),value:US(SS(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],RS(i,HS(e.key)+"="+HS(e.value));return SS(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var jS=function(){KA(this,zS);var e=dS(this,new GS(arguments.length>0?arguments[0]:void 0));VA||(this.size=e.entries.length)},zS=jS.prototype;if(WA(zS,{append:function(e,t){var i=uS(this);nS(arguments.length,2),RS(i.entries,{key:ZA(e),value:ZA(t)}),VA||this.length++,i.updateURL()},delete:function(e){for(var t=uS(this),i=nS(arguments.length,1),r=t.entries,o=ZA(e),n=i<2?void 0:arguments[1],a=void 0===n?n:ZA(n),s=0;s<r.length;){var l=r[s];if(l.key!==o||void 0!==a&&l.value!==a)s++;else if(CS(r,s,1),void 0!==a)break}VA||(this.size=r.length),t.updateURL()},get:function(e){var t=uS(this).entries;nS(arguments.length,1);for(var i=ZA(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=uS(this).entries;nS(arguments.length,1);for(var i=ZA(e),r=[],o=0;o<t.length;o++)t[o].key===i&&RS(r,t[o].value);return r},has:function(e){for(var t=uS(this).entries,i=nS(arguments.length,1),r=ZA(e),o=i<2?void 0:arguments[1],n=void 0===o?o:ZA(o),a=0;a<t.length;){var s=t[a++];if(s.key===r&&(void 0===n||s.value===n))return!0}return!1},set:function(e,t){var i=uS(this);nS(arguments.length,1);for(var r,o=i.entries,n=!1,a=ZA(e),s=ZA(t),l=0;l<o.length;l++)(r=o[l]).key===a&&(n?CS(o,l--,1):(n=!0,r.value=s));n||RS(o,{key:a,value:s}),VA||(this.size=o.length),i.updateURL()},sort:function(){var e=uS(this);aS(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=uS(this).entries,r=JA(e,arguments.length>1?arguments[1]:void 0),o=0;o<i.length;)r((t=i[o++]).value,t.key,this)},keys:function(){return new WS(this,"keys")},values:function(){return new WS(this,"values")},entries:function(){return new WS(this,"entries")}},{enumerable:!0}),BA(zS,sS,zS.entries,{name:"entries"}),BA(zS,"toString",(function(){return uS(this).serialize()}),{enumerable:!0}),VA&&HA(zS,"size",{get:function(){return uS(this).entries.length},configurable:!0,enumerable:!0}),GA(jS,lS),OA({global:!0,constructor:!0,forced:!FA},{URLSearchParams:jS}),!FA&&qA(fS)){var KS=UA(gS.has),qS=UA(gS.set),YS=function(e){if($A(e)){var t,i=e.body;if(XA(i)===lS)return t=e.headers?new fS(e.headers):new fS,KS(t,"content-type")||qS(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),eS(e,{body:tS(0,ZA(i)),headers:tS(0,t)})}return e};if(qA(pS)&&OA({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return pS(e,arguments.length>1?YS(arguments[1]):{})}}),qA(mS)){var JS=function(e){return KA(this,_S),new mS(e,arguments.length>1?YS(arguments[1]):{})};_S.constructor=JS,JS.prototype=_S,OA({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:JS})}}var XS,QS=to,$S=n,ZS=kI,eR=i,tR=Zo,iR=T,rR=Qi,oR=_o,nR=Wl,aR=He,sR=jI,lR=function(e){var t=$I(e),i=tA(this),r=arguments.length,o=r>1?arguments[1]:void 0,n=void 0!==o;n&&(o=XI(o,r>2?arguments[2]:void 0));var a,s,l,c,d,u,h=nA(t),p=0;if(!h||this===aA&&eA(h))for(a=iA(t),s=i?new this(a):aA(a);a>p;p++)u=n?o(t[p],p):t[p],rA(s,p,u);else for(s=i?new this:[],d=(c=oA(t,h)).next;!(l=QI(d,c)).done;p++)u=n?ZI(c,o,[l.value,p],!0):l.value,rA(s,p,u);return s.length=p,s},cR=al,dR=cg.codeAt,uR=function(e){var t,i,r=[],o=yA(vA(TA(e),dA,"."),".");for(t=0;t<o.length;t++)i=o[t],EA(r,pA(cA,i)?"xn--"+SA(i):i);return gA(r,".")},hR=po,pR=Ua,mR=iu,fR={URLSearchParams:jS,getState:uS},_R=Ci,gR=_R.set,ER=_R.getterFor("URL"),vR=fR.URLSearchParams,yR=fR.getState,TR=eR.URL,IR=eR.TypeError,AR=eR.parseInt,SR=Math.floor,RR=Math.pow,bR=iR("".charAt),wR=iR(/./.exec),CR=iR([].join),DR=iR(1..toString),NR=iR([].pop),kR=iR([].push),OR=iR("".replace),MR=iR([].shift),PR=iR("".split),LR=iR("".slice),xR=iR("".toLowerCase),UR=iR([].unshift),VR="Invalid scheme",FR="Invalid host",BR="Invalid port",HR=/[a-z]/i,WR=/[\d+-.a-z]/i,GR=/\d/,jR=/^0x/i,zR=/^[0-7]+$/,KR=/^\d+$/,qR=/^[\da-f]+$/i,YR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,JR=/[\0\t\n\r #/:<>?@[\\\]^|]/,XR=/^[\u0000-\u0020]+/,QR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,$R=/[\t\n\r]/g,ZR=function(e){var t,i,r,o;if("number"==typeof e){for(t=[],i=0;i<4;i++)UR(t,e%256),e=SR(e/256);return CR(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,o=0,n=0;n<8;n++)0!==e[n]?(o>i&&(t=r,i=o),r=null,o=0):(null===r&&(r=n),++o);return o>i?r:t}(e),i=0;i<8;i++)o&&0===e[i]||(o&&(o=!1),r===i?(t+=i?":":"::",o=!0):(t+=DR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},eb={},tb=sR({},eb,{" ":1,'"':1,"<":1,">":1,"`":1}),ib=sR({},tb,{"#":1,"?":1,"{":1,"}":1}),rb=sR({},ib,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ob=function(e,t){var i=dR(e,0);return i>32&&i<127&&!aR(t,e)?e:encodeURIComponent(e)},nb={ftp:21,file:null,http:80,https:443,ws:80,wss:443},ab=function(e,t){var i;return 2===e.length&&wR(HR,bR(e,0))&&(":"===(i=bR(e,1))||!t&&"|"===i)},sb=function(e){var t;return e.length>1&&ab(LR(e,0,2))&&(2===e.length||"/"===(t=bR(e,2))||"\\"===t||"?"===t||"#"===t)},lb=function(e){return"."===e||"%2e"===xR(e)},cb={},db={},ub={},hb={},pb={},mb={},fb={},_b={},gb={},Eb={},vb={},yb={},Tb={},Ib={},Ab={},Sb={},Rb={},bb={},wb={},Cb={},Db={},Nb=function(e,t,i){var r,o,n,a=hR(e);if(t){if(o=this.parse(a))throw new IR(o);this.searchParams=null}else{if(void 0!==i&&(r=new Nb(i,!0)),o=this.parse(a,null,r))throw new IR(o);(n=yR(new vR)).bindURL(this),this.searchParams=n}};Nb.prototype={type:"URL",parse:function(e,t,i){var r,o,n,a,s,l=this,c=t||cb,d=0,u="",h=!1,p=!1,m=!1;for(e=hR(e),t||(l.scheme="",l.username="",l.password="",l.host=null,l.port=null,l.path=[],l.query=null,l.fragment=null,l.cannotBeABaseURL=!1,e=OR(e,XR,""),e=OR(e,QR,"$1")),e=OR(e,$R,""),r=lR(e);d<=r.length;){switch(o=r[d],c){case cb:if(!o||!wR(HR,o)){if(t)return VR;c=ub;continue}u+=xR(o),c=db;break;case db:if(o&&(wR(WR,o)||"+"===o||"-"===o||"."===o))u+=xR(o);else{if(":"!==o){if(t)return VR;u="",c=ub,d=0;continue}if(t&&(l.isSpecial()!==aR(nb,u)||"file"===u&&(l.includesCredentials()||null!==l.port)||"file"===l.scheme&&!l.host))return;if(l.scheme=u,t)return void(l.isSpecial()&&nb[l.scheme]===l.port&&(l.port=null));u="","file"===l.scheme?c=Ib:l.isSpecial()&&i&&i.scheme===l.scheme?c=hb:l.isSpecial()?c=_b:"/"===r[d+1]?(c=pb,d++):(l.cannotBeABaseURL=!0,kR(l.path,""),c=wb)}break;case ub:if(!i||i.cannotBeABaseURL&&"#"!==o)return VR;if(i.cannotBeABaseURL&&"#"===o){l.scheme=i.scheme,l.path=cR(i.path),l.query=i.query,l.fragment="",l.cannotBeABaseURL=!0,c=Db;break}c="file"===i.scheme?Ib:mb;continue;case hb:if("/"!==o||"/"!==r[d+1]){c=mb;continue}c=gb,d++;break;case pb:if("/"===o){c=Eb;break}c=bb;continue;case mb:if(l.scheme=i.scheme,o===XS)l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query=i.query;else if("/"===o||"\\"===o&&l.isSpecial())c=fb;else if("?"===o)l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query="",c=Cb;else{if("#"!==o){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.path.length--,c=bb;continue}l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query=i.query,l.fragment="",c=Db}break;case fb:if(!l.isSpecial()||"/"!==o&&"\\"!==o){if("/"!==o){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,c=bb;continue}c=Eb}else c=gb;break;case _b:if(c=gb,"/"!==o||"/"!==bR(u,d+1))continue;d++;break;case gb:if("/"!==o&&"\\"!==o){c=Eb;continue}break;case Eb:if("@"===o){h&&(u="%40"+u),h=!0,n=lR(u);for(var f=0;f<n.length;f++){var _=n[f];if(":"!==_||m){var g=ob(_,rb);m?l.password+=g:l.username+=g}else m=!0}u=""}else if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()){if(h&&""===u)return"Invalid authority";d-=lR(u).length+1,u="",c=vb}else u+=o;break;case vb:case yb:if(t&&"file"===l.scheme){c=Sb;continue}if(":"!==o||p){if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()){if(l.isSpecial()&&""===u)return FR;if(t&&""===u&&(l.includesCredentials()||null!==l.port))return;if(a=l.parseHost(u))return a;if(u="",c=Rb,t)return;continue}"["===o?p=!0:"]"===o&&(p=!1),u+=o}else{if(""===u)return FR;if(a=l.parseHost(u))return a;if(u="",c=Tb,t===yb)return}break;case Tb:if(!wR(GR,o)){if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()||t){if(""!==u){var E=AR(u,10);if(E>65535)return BR;l.port=l.isSpecial()&&E===nb[l.scheme]?null:E,u=""}if(t)return;c=Rb;continue}return BR}u+=o;break;case Ib:if(l.scheme="file","/"===o||"\\"===o)c=Ab;else{if(!i||"file"!==i.scheme){c=bb;continue}switch(o){case XS:l.host=i.host,l.path=cR(i.path),l.query=i.query;break;case"?":l.host=i.host,l.path=cR(i.path),l.query="",c=Cb;break;case"#":l.host=i.host,l.path=cR(i.path),l.query=i.query,l.fragment="",c=Db;break;default:sb(CR(cR(r,d),""))||(l.host=i.host,l.path=cR(i.path),l.shortenPath()),c=bb;continue}}break;case Ab:if("/"===o||"\\"===o){c=Sb;break}i&&"file"===i.scheme&&!sb(CR(cR(r,d),""))&&(ab(i.path[0],!0)?kR(l.path,i.path[0]):l.host=i.host),c=bb;continue;case Sb:if(o===XS||"/"===o||"\\"===o||"?"===o||"#"===o){if(!t&&ab(u))c=bb;else if(""===u){if(l.host="",t)return;c=Rb}else{if(a=l.parseHost(u))return a;if("localhost"===l.host&&(l.host=""),t)return;u="",c=Rb}continue}u+=o;break;case Rb:if(l.isSpecial()){if(c=bb,"/"!==o&&"\\"!==o)continue}else if(t||"?"!==o)if(t||"#"!==o){if(o!==XS&&(c=bb,"/"!==o))continue}else l.fragment="",c=Db;else l.query="",c=Cb;break;case bb:if(o===XS||"/"===o||"\\"===o&&l.isSpecial()||!t&&("?"===o||"#"===o)){if(".."===(s=xR(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(l.shortenPath(),"/"===o||"\\"===o&&l.isSpecial()||kR(l.path,"")):lb(u)?"/"===o||"\\"===o&&l.isSpecial()||kR(l.path,""):("file"===l.scheme&&!l.path.length&&ab(u)&&(l.host&&(l.host=""),u=bR(u,0)+":"),kR(l.path,u)),u="","file"===l.scheme&&(o===XS||"?"===o||"#"===o))for(;l.path.length>1&&""===l.path[0];)MR(l.path);"?"===o?(l.query="",c=Cb):"#"===o&&(l.fragment="",c=Db)}else u+=ob(o,ib);break;case wb:"?"===o?(l.query="",c=Cb):"#"===o?(l.fragment="",c=Db):o!==XS&&(l.path[0]+=ob(o,eb));break;case Cb:t||"#"!==o?o!==XS&&("'"===o&&l.isSpecial()?l.query+="%27":l.query+="#"===o?"%23":ob(o,eb)):(l.fragment="",c=Db);break;case Db:o!==XS&&(l.fragment+=ob(o,tb))}d++}},parseHost:function(e){var t,i,r;if("["===bR(e,0)){if("]"!==bR(e,e.length-1))return FR;if(t=function(e){var t,i,r,o,n,a,s,l=[0,0,0,0,0,0,0,0],c=0,d=null,u=0,h=function(){return bR(e,u)};if(":"===h()){if(":"!==bR(e,1))return;u+=2,d=++c}for(;h();){if(8===c)return;if(":"!==h()){for(t=i=0;i<4&&wR(qR,h());)t=16*t+AR(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,c>6)return;for(r=0;h();){if(o=null,r>0){if(!("."===h()&&r<4))return;u++}if(!wR(GR,h()))return;for(;wR(GR,h());){if(n=AR(h(),10),null===o)o=n;else{if(0===o)return;o=10*o+n}if(o>255)return;u++}l[c]=256*l[c]+o,2!=++r&&4!==r||c++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;l[c++]=t}else{if(null!==d)return;u++,d=++c}}if(null!==d)for(a=c-d,c=7;0!==c&&a>0;)s=l[c],l[c--]=l[d+a-1],l[d+--a]=s;else if(8!==c)return;return l}(LR(e,1,-1)),!t)return FR;this.host=t}else if(this.isSpecial()){if(e=uR(e),wR(YR,e))return FR;if(t=function(e){var t,i,r,o,n,a,s,l=PR(e,".");if(l.length&&""===l[l.length-1]&&l.length--,(t=l.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(o=l[r]))return e;if(n=10,o.length>1&&"0"===bR(o,0)&&(n=wR(jR,o)?16:8,o=LR(o,8===n?1:2)),""===o)a=0;else{if(!wR(10===n?KR:8===n?zR:qR,o))return e;a=AR(o,n)}kR(i,a)}for(r=0;r<t;r++)if(a=i[r],r===t-1){if(a>=RR(256,5-t))return null}else if(a>255)return null;for(s=NR(i),r=0;r<i.length;r++)s+=i[r]*RR(256,3-r);return s}(e),null===t)return FR;this.host=t}else{if(wR(JR,e))return FR;for(t="",i=lR(e),r=0;r<i.length;r++)t+=ob(i[r],eb);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return aR(nb,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&ab(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,o=e.host,n=e.port,a=e.path,s=e.query,l=e.fragment,c=t+":";return null!==o?(c+="//",e.includesCredentials()&&(c+=i+(r?":"+r:"")+"@"),c+=ZR(o),null!==n&&(c+=":"+n)):"file"===t&&(c+="//"),c+=e.cannotBeABaseURL?a[0]:a.length?"/"+CR(a,"/"):"",null!==s&&(c+="?"+s),null!==l&&(c+="#"+l),c},setHref:function(e){var t=this.parse(e);if(t)throw new IR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new kb(e.path[0]).origin}catch(QK){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+ZR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(hR(e)+":",cb)},getUsername:function(){return this.username},setUsername:function(e){var t=lR(hR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ob(t[i],rb)}},getPassword:function(){return this.password},setPassword:function(e){var t=lR(hR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ob(t[i],rb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?ZR(e):ZR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,vb)},getHostname:function(){var e=this.host;return null===e?"":ZR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,yb)},getPort:function(){var e=this.port;return null===e?"":hR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=hR(e))?this.port=null:this.parse(e,Tb))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+CR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Rb))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=hR(e))?this.query=null:("?"===bR(e,0)&&(e=LR(e,1)),this.query="",this.parse(e,Cb)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=hR(e))?("#"===bR(e,0)&&(e=LR(e,1)),this.fragment="",this.parse(e,Db)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var kb=function(e){var t=nR(this,Ob),i=mR(arguments.length,1)>1?arguments[1]:void 0,r=gR(t,new Nb(e,!1,i));$S||(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())},Ob=kb.prototype,Mb=function(e,t){return{get:function(){return ER(this)[e]()},set:t&&function(e){return ER(this)[t](e)},configurable:!0,enumerable:!0}};if($S&&(oR(Ob,"href",Mb("serialize","setHref")),oR(Ob,"origin",Mb("getOrigin")),oR(Ob,"protocol",Mb("getProtocol","setProtocol")),oR(Ob,"username",Mb("getUsername","setUsername")),oR(Ob,"password",Mb("getPassword","setPassword")),oR(Ob,"host",Mb("getHost","setHost")),oR(Ob,"hostname",Mb("getHostname","setHostname")),oR(Ob,"port",Mb("getPort","setPort")),oR(Ob,"pathname",Mb("getPathname","setPathname")),oR(Ob,"search",Mb("getSearch","setSearch")),oR(Ob,"searchParams",Mb("getSearchParams")),oR(Ob,"hash",Mb("getHash","setHash"))),rR(Ob,"toJSON",(function(){return ER(this).serialize()}),{enumerable:!0}),rR(Ob,"toString",(function(){return ER(this).serialize()}),{enumerable:!0}),TR){var Pb=TR.createObjectURL,Lb=TR.revokeObjectURL;Pb&&rR(kb,"createObjectURL",tR(Pb,TR)),Lb&&rR(kb,"revokeObjectURL",tR(Lb,TR))}pR(kb,"URL"),QS({global:!0,constructor:!0,forced:!ZS,sham:!$S},{URL:kb});var xb=c;to({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return xb(URL.prototype.toString,this)}});var Ub,Vb=Object.create,Fb=Object.defineProperty,Bb=Object.defineProperties,Hb=Object.getOwnPropertyDescriptor,Wb=Object.getOwnPropertyDescriptors,Gb=Object.getOwnPropertyNames,jb=Object.getOwnPropertySymbols,zb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty,qb=Object.prototype.propertyIsEnumerable,Yb=Reflect.get,Jb=Math.pow,Xb=(e,t,i)=>t in e?Fb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Qb=(e,t)=>{for(var i in t||(t={}))Kb.call(t,i)&&Xb(e,i,t[i]);if(jb)for(var i of jb(t))qb.call(t,i)&&Xb(e,i,t[i]);return e},$b=(e,t)=>Bb(e,Wb(t)),Zb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ew=(e,t)=>{for(var i in t)Fb(e,i,{get:t[i],enumerable:!0})},tw=(e,t,i)=>(i=null!=e?Vb(zb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Gb(t))!Kb.call(e,o)&&o!==i&&Fb(e,o,{get:()=>t[o],enumerable:!(r=Hb(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:Fb(i,"default",{value:e,enumerable:!0}),e)),iw=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?Hb(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&Fb(t,i,n),n},rw=(e,t,i)=>Xb(e,"symbol"!=typeof t?t+"":t,i),ow=(e,t,i)=>Yb(zb(e),i,t),nw=(e,t,i)=>new Promise(((r,o)=>{var n=e=>{try{s(i.next(e))}catch(aM){o(aM)}},a=e=>{try{s(i.throw(e))}catch(aM){o(aM)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(n,a);s((i=i.apply(e,t)).next())})),aw=Zb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,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,i),!0;case 4:return d.fn.call(d.context,t,i,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+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)&&(!i||a.context===i)&&s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)})),sw=Zb(((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")}))}))})),lw=Zb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var o=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:o&&!i[e.name]&&(i[e.name]={});var n=e.push?{}:o?i[e.name]:i;(function(e,i,r,o){if(o&&!r)i[o]=t(e[1]);else for(var n=0;n<r.length;n+=1)null!=e[n+1]&&(i[r[n]]=t(e[n+1]))})(r.match(e.reg),n,e.names,e.name),e.push&&i[e.push].push(n)},r=sw(),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<(r[t]||[]).length;s+=1){var l=r[t][s];if(l.reg.test(o))return i(l,a,o)}})),t.media=n,t};var n=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(n,{})},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),o=0;o<r.length;o+=3)i.push({component:r[o],ip:r[o+1],port:r[o+2]});return i},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 i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),cw=Zb(((e,t)=>{var i=sw(),r=/%[sdv%]/g,o=function(e){var t=1,i=arguments,o=i.length;return e.replace(r,(function(e){if(t>=o)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""}}))},n=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 n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?r.push(i[t.name][a]):r.push(i[t.names[n]])}else r.push(i[t.name]);return o.apply(null,r)},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 r=t.outerOrder||a,o=t.innerOrder||s,l=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(n(t,i,e))}))}))})),e.media.forEach((function(e){l.push(n("m",i.m[0],e)),o.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(n(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}})),dw=Zb((e=>{var t=lw(),i=cw(),r=sw();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})),uw=((Ub=uw||{})[Ub.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ub[Ub.INVALID_OPERATION=4097]="INVALID_OPERATION",Ub[Ub.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ub[Ub.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ub[Ub.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ub[Ub.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ub[Ub.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ub[Ub.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ub[Ub.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ub[Ub.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ub[Ub.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ub[Ub.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ub[Ub.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ub[Ub.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ub[Ub.CLIENT_BANNED=16448]="CLIENT_BANNED",Ub[Ub.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ub[Ub.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ub[Ub.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ub[Ub.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ub[Ub.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ub[Ub.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ub[Ub.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ub[Ub.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ub[Ub.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ub[Ub.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ub[Ub.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ub[Ub.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ub[Ub.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ub[Ub.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ub[Ub.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ub[Ub.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Ub[Ub.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Ub[Ub.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Ub[Ub.UNKNOWN=65535]="UNKNOWN",Ub),hw=uw,pw=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=hw.UNKNOWN,extraCode:o=0,constraint:n}=e,a="<".concat(function(e){for(let t in hw)if(hw[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),s="".concat(i).concat(n?" constraint: ".concat(n):"").concat(null!=i&&i.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=r,this.extraCode=o,this.name=t,this.message=s,this.constraint=n,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},mw=pw,fw=function(){return 0},_w=function(){return Date.now()+0},gw=function(){let e=new Date;return e.setTime(_w()),e.toLocaleString()},Ew=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)},vw={};ew(vw,{REPORT_TYPE:()=>ON,buildSSOPackage:()=>MN,bytes2ms:()=>MD,calculateScaleResolutionDownNumber:()=>CN,concatArrayBuffers:()=>PN,convertObjectNumberToInt:()=>AN,copyProperties:()=>OD,deepClone:()=>pN,deepCloneBasic:()=>kN,deepMerge:()=>hN,delay:()=>SN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>fN,getEnv:()=>ID,getFirst16Bits:()=>xN,getInternalVersion:()=>aN,getLast16Bits:()=>LN,getLoggerUrl:()=>SD,getMediaStreamTrackInfo:()=>wN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>bD,getNumNetworkType:()=>kD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>vN,getTurnServer:()=>dN,getUint32Version:()=>IN,getValueType:()=>WD,getViewListFromView:()=>mN,glog:()=>UD,ipv4ToUint32:()=>uN,isArray:()=>JD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>ZD,isEmpty:()=>lN,isFunction:()=>GD,isLangChinese:()=>VD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>yN,isPromise:()=>$D,isRemoteTrack:()=>QD,isRotate90Or270:()=>DN,isSetSinkIdSupported:()=>iN,isString:()=>zD,isUndefined:()=>jD,loadImage:()=>TN,loadVideo:()=>NN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>bN,performanceNow:()=>oN,promiseAny:()=>rN,samples2ms:()=>PD,setNetworkTypeFromWebRTC:()=>ND,stringify:()=>gN,stringifyIncludeValue:()=>EN,throttlePromise:()=>RN});var yw={};ew(yw,{AUDIO_MUTE_BIT:()=>lC,AUDIO_STAT_BIT:()=>sC,AUX_STAT_BIT:()=>aC,AUX_STREAM_MSID:()=>pC,BACKEND_ENV:()=>iC,BASE_DOC_URL:()=>Lw,BASE_HOST:()=>kw,CAPABILITIES_KEYS:()=>eD,CLASS_NAME:()=>zC,CLOUD_CONSOLE_URL:()=>Pw,CROSS_ROOM_BIT:()=>uC,DATA_FREEZE_TIMING:()=>VC,DOC_BILLING_CN:()=>Uw,DOC_BILLING_OVERSEA:()=>Vw,DOC_URL:()=>xw,DTLS_STATE_UNKNOWN:()=>AC,ENV_NAME:()=>Gw,EXCHANGE_SDP_TIMEOUT:()=>MC,IS_WORKER:()=>bw,IS_WORKLET:()=>ww,KIBANA_EVENT:()=>NC,LOCAL_STREAM_PUBLISH_STATE:()=>UC,LOGGER_CMD_TYPE:()=>Ww,LOGGER_DOMAIN:()=>Fw,LOGGER_DOMAIN_OVERSEA:()=>Bw,LOG_LEVEL:()=>jw,LOG_LEVEL_NAME:()=>XC,MAIN_STREAM_MSID:()=>hC,MAX_RTT:()=>tD,MICROPHONE_COMMUNICATIONS:()=>JC,MICROPHONE_DEFAULT:()=>qC,MUTE_ALL_BIT:()=>dC,NAME:()=>eC,NETWORK_TYPE:()=>qw,NOT_SUPPORTED_H264:()=>xC,PAUSED_RETRY_COUNT:()=>KC,PEERCONNECTION_CONNECTING_TIMEOUT:()=>WC,PEER_CONNECTION_STATE:()=>SC,PEER_LEAVE_REASON:()=>QC,RECOVER_CAPTURE_INTERVAL:()=>ZC,REMOTE_STREAM_TYPE_AUX:()=>fC,REMOTE_STREAM_TYPE_MAIN:()=>mC,RENDER_FREEZE_TIMING:()=>FC,SCHEDULE_DOMAIN:()=>GC,SCHEDULE_TIMEOUT:()=>jC,SDP_SEMANTICS_PLAN_B:()=>LC,SDP_SEMANTICS_UNIFIED_PLAN:()=>PC,SECOND_HOST:()=>Ow,SIGNAL_PING_PONG_INTERVAL:()=>Kw,SIGNAL_PING_TIMEOUT:()=>zw,SIGNAL_RECONNECTION_COUNT:()=>DC,SMALL_STAT_BIT:()=>nC,SPEAKER_DEFAULT:()=>YC,STORAGE_EXPIRES_TIME:()=>Yw,STREAM_TYPE_BIG:()=>BC,STREAM_TYPE_SMALL:()=>HC,SUBSCRIBE_SMALL_RETRY_COUNT:()=>$C,SYNC_USER_LIST_INTERVAL:()=>kC,Scene:()=>rC,THIRD_HOST:()=>Mw,TRANSPORT_DIRECTION:()=>tC,TRTC_ERROR_ASSISTANCE:()=>Hw,TRTC_QUALITY_BAD:()=>yC,TRTC_QUALITY_DISCONNECTED:()=>IC,TRTC_QUALITY_EXCELLENT:()=>gC,TRTC_QUALITY_GOOD:()=>EC,TRTC_QUALITY_POOR:()=>vC,TRTC_QUALITY_UNKNOWN:()=>_C,TRTC_QUALITY_VERY_BAD:()=>TC,UPDATE_OFFER_TIMEOUT:()=>OC,VIDEO_MUTE_BIT:()=>cC,VIDEO_STAT_BIT:()=>oC,audioProfileMap:()=>Jw,defaultBigVideoProfile:()=>Qw,defaultSmallVideoProfile:()=>$w,getRetryCount:()=>wC,getScriptDir:()=>Cw,innerVersion:()=>Tw,loggerProxy:()=>Dw,screenProfileMap:()=>Zw,setLoggerProxy:()=>Nw,setRetryCount:()=>bC,setVersion:()=>Aw,version:()=>Iw,videoProfileMap:()=>Xw});var Tw="4.15.00.1600",Iw="5.0.0";function Aw(e){Iw=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Tw="".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 Sw,Rw,bw="undefined"!=typeof importScripts,ww="undefined"!=typeof registerProcessor,Cw=()=>{let e=bw?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Dw="",Nw=e=>Dw=e,kw="web.sdk.qcloud.com",Ow="web.sdk.tencent.cn",Mw="web.sdk.cloud.tencent.cn",Pw="https://console.cloud.tencent.com/trtc",Lw="https://".concat(kw,"/trtc/webrtc/doc"),xw="".concat(Lw,"/zh-cn/"),Uw="https://cloud.tencent.com/document/product/647/85386",Vw="https://trtc.io/document/56025",Fw="https://yun.tim.qq.com",Bw="https://apisgp.my-imcloud.com",Hw="trtc_error_assistance",Ww={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Gw={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},jw=((Rw=jw||{})[Rw.TRACE=0]="TRACE",Rw[Rw.DEBUG=1]="DEBUG",Rw[Rw.INFO=2]="INFO",Rw[Rw.WARN=3]="WARN",Rw[Rw.ERROR=4]="ERROR",Rw[Rw.NONE=5]="NONE",Rw),zw=18e3,Kw=2e3,qw={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},Yw=6048e5,Jw={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}},Xw={"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}},Qw=Xw["480p_2"],$w=Xw["120p_2"],Zw={"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}},eC={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",LOADSTART:"loadstart",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"},tC={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},iC={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},rC=((Sw=rC||{}).LIVE="live",Sw.RTC="rtc",Sw),oC=1,nC=2,aC=4,sC=8,lC=64,cC=16,dC=112,uC=128,hC="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",pC="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",mC=eC.MAIN,fC=eC.AUXILIARY,_C=0,gC=1,EC=2,vC=3,yC=4,TC=5,IC=6,AC="unknown",SC={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},RC=1/0;function bC(e){RC=e}function wC(){return RC}var CC,DC=30,NC={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",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},kC=1e4,OC=1e4,MC=1e4,PC="unified-plan",LC="plan-b",xC=1028,UC=((CC=UC||{})[CC.UNPUBLISH=-1]="UNPUBLISH",CC[CC.PUBLISHING=0]="PUBLISHING",CC[CC.PUBLISHED=1]="PUBLISHED",CC),VC=500,FC=1e3,BC=eC.BIG,HC=eC.SMALL,WC=1e4,GC={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"},jC=2e3,zC={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},KC=5,qC="default",YC=qC,JC="communications",XC=Object.keys(jw),QC=["normal leave","timeout leave","kick","role change"],$C=10,ZC=2e3,eD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],tD=1e4,iD=function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())}))},rD=Symbol(32),oD=Symbol(16),nD=Symbol(8),aD=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 iD(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(rD)}readU16(){return this.read(oD)}readU8(){return this.read(nD)}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===rD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===oD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===nD){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}};aD.U32=rD,aD.U16=oD,aD.U8=nD;var sD=128;function lD(e){let t=new aD;for(;e>=128;)t.malloc(1)[0]=255&e|sD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function cD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new aD,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(lD(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(lD(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new aD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=cD(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=cD(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(lD(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var dD=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 uD(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 hD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function pD(e,t){return e[t]}function mD(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var fD=0,_D=2654435769,gD=16,ED=2,vD=7;function yD(e,t){let i=new dD,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,fD);fD=fD+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new dD;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.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,zD(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===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+ED+vD)%8;r&&(r=8-r);let o=i+1+ED+vD+r,n=new Uint8Array(o),a=0,s=new Uint8Array(8),l=new Uint8Array(8),c=new Uint8Array(8),d=0;s[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)s[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<ED;)if(d<8&&(s[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}let u=0;for(;u<i;)if(d<8&&(s[d]=e[u],d+=1,u+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}for(let h=0;h<vD;)if(d<8&&(s[d]=0,d+=1,h+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}return n}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function TD(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=hD(e,0),n=hD(e,4),a=[];for(let l=0;l<4;l++)a[l]=hD(t,4*l);let s=0;for(let l=0;l<gD;l++)s+=_D,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;uD(i,o,r),uD(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var ID=function(){return new URLSearchParams(location.search).get("trtc_env")||""},AD=e=>Number(e)<14e8,SD=function(e,t){let i;i=Dw||(AD(e)?Bw:Fw);let r=Math.floor(Math.random()*Jb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},RD="unknown";function bD(){!function(){var e;CD||(CD=!0,null==(e=navigator.connection)||e.addEventListener("typechange",wD))}();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(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===o&&(o="2g"),r?DD(r,o):RD}function wD(){eM.warn("netType changed",bD())}var CD=!1;function DD(e,t){if(qw[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ND(e){RD=DD(e)}function kD(){return qw[bD()]}function OD(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 MD(e){return PD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function PD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function LD(e){return 4*xD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function xD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var UD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},VD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},FD=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 BD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:BD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function HD(e){return e>8?3e4:1e3*BD(e)}function WD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var GD=e=>"function"==typeof e,jD=e=>void 0===e,zD=e=>"string"==typeof e,KD=e=>"number"==typeof e,qD=e=>"boolean"==typeof e,YD=e=>"object"===WD(e),JD=e=>"array"===WD(e),XD=e=>WD(e)==="MediaStreamTrack".toLowerCase(),QD=e=>e.isRemote,$D=e=>"promise"===WD(e),ZD=e=>GD(e)&&e.prototype.constructor===e,eN=e=>ZD(e)?e.prototype.constructor.name:"",tN="undefined"!=typeof AudioWorkletNode,iN="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function rN(e){return new Promise(((t,i)=>{let r=[];e.forEach((o=>{o.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function oN(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var nN=e=>+e<10?"0".concat(e):e,aN=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=nN(i[1])+nN(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},sN=Object.prototype.hasOwnProperty;function lN(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(FD(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(sN.call(e,t))return!1;return!0}return!1}function cN(e,t){return{userId:t,hasAudio:!!(e&sC),hasVideo:!!(e&oC),hasAuxiliary:!!(e&aC),hasSmall:!!(e&nC),audioMuted:!!(e&lC),videoMuted:!!(e&cC),audioAvailable:!(!(e&sC)||e&lC),videoAvailable:!(!(e&oC)||e&cC)}}function dN(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!jD(e.username)&&!jD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",jD(e.credentialType)||(t.credentialType=e.credentialType)),t}function uN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!zD(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 hN=function(e,t,i,r){if(!YD(e)||!YD(t))return 0;let o,n=0,a=Object.keys(t);for(let s=0,l=a.length;s<l;s++)if(o=a[s],!(jD(t[o])||i&&i.includes(o)))if(YD(e[o])&&YD(t[o]))n+=hN(e[o],t[o],i,r);else{if(r&&r.includes(t[o]))continue;e[o]!==t[o]&&(e[o]=pN(t[o]),n+=1)}return n};function pN(e){if(JD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=pN(e)})),t}if(YD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=pN(e[i])})),t}return e}var mN=e=>{let t=[];if(JD(e))t=[...e];else if(zD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},fN=e=>zD(e)?document.getElementById(e):e,_N=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,o=e.getDate(),n=t(e.getHours()),a=t(e.getMinutes()),s=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(o," ").concat(n,":").concat(a,":").concat(s)})(new Date);function gN(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(JD(e))return"[".concat(e.map((e=>gN(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!FD(e)||!JD(i)&&!JD(r))return JSON.stringify(e);let t={},o=new Set(i),n=new Set(r);return Object.keys(e).forEach((a=>{(0===n.size&&o.has(a)||0===o.size&&!n.has(a))&&(t[a]=FD(e[a])||JD(e[a])?JSON.parse(gN(e[a],{keysToExclude:r,keysToInclude:i})):e[a])})),JSON.stringify(t)}catch(CC){return"{}"}}function EN(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)})),gN(e,{keysToInclude:i})}function vN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var yN=()=>{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},TN=e=>nw(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(zD(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 mw({code:hw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),IN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},AN=e=>(Object.keys(e).forEach((t=>{KD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(FD(e[t])||JD(e[t]))&&AN(e[t])})),e);function SN(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function RN(e,t){let i=null;return function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return i||(i=e.apply(t||this,o),i.finally((()=>i=null)),i)}}function bN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function wN(e){var t;try{let{width:i,height:r,frameRate:o,sampleRate:n,sampleSize:a,channelCount:s}=null==(t=e.getSettings)?void 0:t.call(e),l=e.kind===eC.AUDIO?"".concat(n,"x").concat(a,"@").concat(s):"".concat(i,"x").concat(r,"@").concat(o),c=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(l).concat(c)}catch(Sw){return""}}function CN(e,t){return e.width*e.height==t.width*t.height?1:yN()&&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 DN(e){return 90===e||270===e}function NN(e){return nw(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 kN(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]=kN(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]=kN(e[r],t)})),i}return e}var ON=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(ON||{});function MN(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return jD(r)||(o=$b(Qb({},o),{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(o)}}}(e,t,i,r);return yD(cD(o),i)}catch(cM){return JSON.stringify(e)}}function PN(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 LN(e){return(65535&e)>>>0}function xN(e){return(4294901760&e)>>>0}function UN(e){let t=function(e){try{let t={},i=0;t.totalLength=hD(e,i),i+=4,t.version=hD(e,i),i+=4,t.encryption=pD(e,i),i+=1,t.uinType=pD(e,i),i+=1,t.uinLength=hD(e,i),i+=4,t.uin=t.uinLength>4?mD(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),o=new Uint8Array(e.slice(0,8)),n=VN(o,t),a=7&n[0],s=e.length-1-a-ED-vD,l=new Uint8Array(s),c=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=a;for(let m=1;m<=ED;)if(h<8)h++,m++;else if(8===h){let r=FN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}let p=s;for(;p>0;)if(h<8)l[c++]=n[h]^d[h],h++,p--;else if(8===h){let r=FN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=vD;)if(h<8)n[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=FN(e,i,d,u,n,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}return l}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=hD(e,i),i+=4,t.seqNo=hD(e,i),i+=4,t.retCode=hD(e,i),i+=4,t.retStrLength=hD(e,i),i+=4,t.retStr=t.retStrLength?mD(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=hD(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?mD(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=hD(e,i),i+=4,t.cookie=t.cookieLength?mD(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=hD(e,i),i+=4,t.busiBuffLength=hD(e,i),i+=4,t.busiBuff=t.busiBuffLength?mD(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function VN(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 o=_D*gD>>>0;for(let n=0;n<gD;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=_D,o>>>=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 FN(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:VN(l,n),bufPos:t+8}}var BN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function HN(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise(((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:UN(new Uint8Array(e))||(BN?BN.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(hM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)}))}function WN(e){return nw(this,null,(function*(){let t=oN(),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 eM.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(oN()-t,"ms")),r}catch(CC){return i}}))}var GN=Object.prototype.hasOwnProperty,jN=e=>"function"==typeof e,zN=e=>void 0===e,KN=e=>e.isRemote,qN=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 YN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>nw(this,null,(function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(jN(d)?d():d)?(h++,m=1,jN(o)&&o.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,i)}),jN(u)?u(h):u)):(t(),jN(n)&&n.call(this,_))};jN(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}}));return new Promise(f)}},JN=class e{constructor(e){rw(this,"_parentPath"),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=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:zN(t.userId)?this.userId:t.userId,sdkAppId:zN(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:zN(t.type)?this.type:t.type,isLocal:zN(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:zN(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),eM.log(e,t,zN(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(qN(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(GN.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={};ew(XN,{ANDROID_VERSION:()=>dk,CHROME_MAJOR_VERSION:()=>fO,CHROME_VERSION:()=>_O,EDGE_VERSION:()=>gk,EDG_MAJOR_VERSION:()=>yk,EDG_VERSION:()=>vk,ELECTRON_MAJOR_VERSION:()=>gO,FIREFOX_MAJOR_VERSION:()=>fk,FIREFOX_VERSION:()=>mk,HUAWEI_VERSION:()=>tO,IE_VERSION:()=>kk,IOS_MAIN_VERSION:()=>RO,IOS_VERSION:()=>IO,IPADQQB_VERSION:()=>Wk,IS_ANDROID:()=>ck,IS_ANDROID_WEBVIEW:()=>TO,IS_ANY_SAFARI:()=>vO,IS_CHROME:()=>pO,IS_CHROME_OS:()=>Kk,IS_CHROMIUM_BASE:()=>hO,IS_DESKTOP_IOS_CHROME:()=>DO,IS_EDG:()=>Ek,IS_EDGE:()=>_k,IS_ELECTRON:()=>Jk,IS_FIREFOX:()=>pk,IS_HEADLESS_CHROME:()=>mO,IS_HONOR:()=>eO,IS_HUAWEI:()=>Zk,IS_HUAWEIBROWSER:()=>$k,IS_IE:()=>Nk,IS_IE8:()=>Dk,IS_IOS:()=>sk,IS_IOS_13_OR_14:()=>CO,IS_IOS_15_1:()=>wO,IS_IOS_CHROME:()=>uO,IS_IPAD:()=>rk,IS_IPADQQB:()=>Hk,IS_IPAD_PRO:()=>ok,IS_IPHONE:()=>nk,IS_IPOD:()=>ak,IS_LINUX:()=>zk,IS_LOCAL:()=>NO,IS_MAC:()=>jk,IS_MACQQB:()=>Fk,IS_MIBROWSER:()=>Xk,IS_MQQB:()=>Lk,IS_NATIVE_ANDROID:()=>hk,IS_OLD_ANDROID:()=>uk,IS_OPENHARMONY:()=>lO,IS_OPPOBROWSER:()=>oO,IS_SAFARI:()=>EO,IS_SAFARI_15_1:()=>bO,IS_SAMSUNGBROWSER:()=>iO,IS_SOGOU:()=>Ak,IS_SOGOUM:()=>Tk,IS_TBS:()=>Rk,IS_UCBROWSER:()=>Yk,IS_VIVOBROWSER:()=>aO,IS_WECHAT:()=>Ok,IS_WIN:()=>Gk,IS_WQQB:()=>Uk,IS_WX:()=>qk,IS_X5MQQB:()=>Pk,IS_XWEB:()=>wk,MACQQB_VERSION:()=>Bk,MI_VERSION:()=>Qk,MQQB_VERSION:()=>xk,OPENHARMONY_VERSION:()=>cO,OPPO_VERSION:()=>nO,SAFARI_VERSION:()=>yO,SAMSUNG_VERSION:()=>rO,SOGOUM_VERSION:()=>Ik,SOGOU_VERSION:()=>Sk,TBS_VERSION:()=>bk,UA_DATA_STRING:()=>xO,USER_AGENT:()=>QN,VIVO_VERSION:()=>sO,WECHAT_VERSION:()=>Mk,WQQB_VERSION:()=>Vk,XWEB_VERSION:()=>Ck,browserInfo:()=>OO,getBrowserCoreNumber:()=>jO,getBrowserInfo:()=>MO,getChromeMajorVersion:()=>dO,getDeviceModel:()=>FO,getDeviceModelFromUA:()=>BO,getGPUInfo:()=>VO,getOSName:()=>WO,getOSNumber:()=>GO,getOSString:()=>zO,getOSType:()=>qO,getTerminalType:()=>KO,getUserAgentData:()=>UO,isLocalStorageEnabled:()=>kO,isMobile:()=>LO,isRealIOS:()=>lk,isVersionLargerThan:()=>SO,isVersionSmallerThan:()=>AO});var QN="undefined"==typeof navigator?"":navigator.userAgent,$N=e=>new RegExp(e,"i").test(QN),ZN=e=>{if($N(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=QN.match(t);if(i&&i[1])return i[1]}return""},ek=e=>{if($N(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=QN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},tk=/AppleWebKit\/([\d.]+)/i.exec(QN),ik=tk?parseFloat(tk[1]):NaN,rk=$N("iPad"),ok="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$N("Macintosh"),nk=$N("iPhone")&&!rk,ak=$N("iPod"),sk=nk||rk||ak||ok,lk=()=>{try{return sk&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch(UH){return sk}},ck=$N("Android"),dk=function(){if(ck){let e=QN.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}(),uk=ck&&$N("webkit")&&dk<2.3,hk=ck&&dk<5&&ik<537,pk=$N("Firefox"),mk=ZN("Firefox"),fk=ek("Firefox"),_k=$N("Edge"),gk=ZN("Edge"),Ek=$N("Edg"),vk=ZN("Edg"),yk=ek("Edg"),Tk=$N("SogouMobileBrowser"),Ik=ZN("SogouMobileBrowser"),Ak=$N("MetaSr\\s"),Sk=ZN("MetaSr\\s"),Rk=$N("TBS"),bk=ZN("TBS"),wk=$N("XWEB"),Ck=ZN("XWEB"),Dk=$N("MSIE\\s8\\.0"),Nk=$N("MSIE\\/\\d+"),kk=function(){if(Nk){let e=/MSIE\s(\d+)\.\d/.exec(QN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(QN)&&/rv:11.0/.test(QN)&&(t=11),t}return NaN}(),Ok=$N("(micromessenger|webbrowser)"),Mk=ZN("MicroMessenger"),Pk=!Rk&&$N("MQQBrowser")&&$N("COVC"),Lk=!Rk&&$N("MQQBrowser")&&!$N("COVC"),xk=Lk||Pk?ZN("MQQBrowser"):"",Uk=!Rk&&$N(" QQBrowser"),Vk=ZN(" QQBrowser"),Fk=!Rk&&$N("QQBrowserLite"),Bk=ZN("QQBrowserLite"),Hk=!Rk&&$N("MQBHD"),Wk=ZN("MQBHD"),Gk=$N("Windows"),jk=!sk&&$N("MAC OS X"),zk=!ck&&$N("Linux"),Kk=$N("CrOS"),qk=$N("MicroMessenger"),Yk=$N("UCBrowser"),Jk=$N("Electron"),Xk=$N("MiuiBrowser"),Qk=ZN("MiuiBrowser"),$k=$N("HuaweiBrowser"),Zk=$N("Huawei")||$N("HUAWEI"),eO=$N("Honor")||$N("HONOR"),tO=ZN("HuaweiBrowser"),iO=$N("SamsungBrowser"),rO=ZN("SamsungBrowser"),oO=$N("HeyTapBrowser"),nO=ZN("HeyTapBrowser"),aO=$N("VivoBrowser"),sO=ZN("VivoBrowser"),lO=$N("OpenHarmony"),cO=ZN("OpenHarmony"),dO=()=>ek("Chrome"),uO=$N("CriOS"),hO=$N("Chrome"),pO=!_k&&!Ak&&!Tk&&!Rk&&!wk&&!Ek&&!Uk&&!Xk&&!$k&&!iO&&!oO&&!aO&&hO,mO=$N("HeadlessChrome"),fO=dO(),_O=ZN("Chrome"),gO=ek("Electron"),EO=!hO&&!Lk&&!Pk&&!Fk&&!Hk&&$N("Safari"),vO=EO||sk,yO=ZN("Version"),TO=/Android.*(wv|.0.0.0)/.test(QN),IO=(()=>{if(ok)return yO;if(sk){let e=QN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function AO(e,t){let i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(i.length,r.length);o++){let e=i[o]||0,t=r[o]||0;if(e<t)return!0;if(e>t)return!1}return!1}function SO(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map((e=>Number(e))),o=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(r.length,o.length);n++){let e=r[n]||0,t=o[n]||0;if(e>t)return!0;if(e<t)return!1}return i}var RO=Number(IO.split(".")[0]),bO="15.1"===yO,wO="15.1"===IO,CO=(()=>{let e=Number(IO.split(".")[0]);return 14===e||13===e})(),DO=uO&&"11.1.1"===yO,NO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),kO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(lM){e=!1}return e}})(),OO=MO();function MO(){let e=new Map([[pk,["Firefox",mk]],[Ek,["Edg",vk]],[pO,["Chrome",_O]],[uO,["ChiOS",ZN("CriOS")]],[EO&&!uO,["Safari",yO]],[Rk,["TBS",bk]],[wk,["XWEB",Ck]],[Ok&&nk,["WeChat",Mk]],[Uk,["QQ(Win)",Vk]],[Lk,["QQ(Mobile)",xk]],[Pk,["QQ(Mobile X5)",xk]],[Fk,["QQ(Mac)",Bk]],[Hk,["QQ(iPad)",Wk]],[Xk,["MI",Qk]],[$k,["HW",tO]],[iO,["Samsung",rO]],[oO,["OPPO",nO]],[aO,["VIVO",sO]],[_k,["EDGE",gk]],[Tk,["SogouMobile",Ik]],[Ak,["Sogou",Sk]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var PO=null;function LO(){return PO&&"boolean"==typeof PO.mobile?PO.mobile:ck||sk||nk||rk||lO}var xO="";function UO(){return nw(this,null,(function*(){if(PO)return PO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(PO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!xO&&(xO="UAData: ".concat(PO.platform,"/").concat(PO.platformVersion),PO.architecture&&PO.bitness&&(xO+=" ".concat(PO.architecture,"/").concat(PO.bitness)),PO.mobile&&(xO+=" mobile"),PO.model&&(xO+=" model: ".concat(PO.model.replace(/\s+/g,"/"))),PO.fullVersionList&&(xO+=" ".concat(PO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),PO}catch(UH){return null}}))}function VO(){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(UH){return""}}function FO(){return(null==PO?void 0:PO.model)||BO()||""}function BO(){let e=QN.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var HO=new Map([[ck,"Android"],[sk,"iOS"],[Gk,"Windows"],[jk,"MacOS"],[zk,"Linux"],[Kk,"ChromeOS"]]),WO=function(){return HO.get(!0)?HO.get(!0):PO?PO.platform:"unknown"};function GO(){return Gk?1:ck?2:jk?3:sk?4:zk?5:Kk?6:lO?7:0}function jO(){return Ok||wk?4:hO?1:EO?2:pk?3:0}var zO=()=>{let e=WO();return null!=PO&&PO.platformVersion?e+="/".concat(PO.platformVersion):sk?e+="/".concat(IO):ck&&(e+="/".concat(dk)),e+="/".concat(OO.name,"/").concat(EO&&!uO?OO.version:OO.version.split(".")[0]),null!=PO&&PO.architecture&&(e+="/".concat(PO.architecture)),e};function KO(){return ck?4:nk?2:rk?3:jk?12:Gk?5:zk?13:lO?22:1}function qO(){return ck?"Android":nk?"iPhone":rk?"iPad":jk?"Mac":Gk?"Windows":zk?"Linux":"unknown"}var YO,JO=new(tw(aw(),1).default),XO=((YO=XO||{}).ROOM_DESTROY="1",YO.JOIN_START="21",YO.JOIN_SCHEDULE_SUCCESS="22",YO.JOIN_SIGNAL_CONNECTION_START="23",YO.JOIN_SIGNAL_CONNECTION_END="24",YO.JOIN_SEND_CMD="25",YO.JOIN_RECEIVED_CMD_RES="26",YO.JOIN_SUCCESS="27",YO.JOIN_FAILED="28",YO.LEAVE_START="51",YO.LEAVE_SEND_CMD="52",YO.LEAVE_SUCCESS="53",YO.PUBLISH_START="61",YO.SEND_FIRST_VIDEO_FRAME="62",YO.PUBLISH_FAILED="63",YO.SUBSCRIBE_START="81",YO.SUBSCRIBE_SUCCESS="82",YO.SUBSCRIBE_FAILED="84",YO.UNSUBSCRIBE_SUCCESS="83",YO.LOCAL_TRACK_CAPTURE_START="101",YO.LOCAL_TRACK_CAPTURE_SUCCESS="102",YO.LOCAL_TRACK_CAPTURE_FAILED="103",YO.LOCAL_TRACK_PUBLISHED="104",YO.LOCAL_TRACK_UNPUBLISHED="105",YO.LOCAL_TRACK_REPLACED="106",YO.SWITCH_DEVICE_SUCCESS="107",YO.TRACK_MUTED="108",YO.TRACK_UNMUTED="109",YO.REMOTE_TRACK_SUBSCRIBED="110",YO.REMOTE_TRACK_UNSUBSCRIBED="111",YO.LOCAL_TRACK_RECAPTURE="112",YO.LOCAL_AUDIO_STARTED="113",YO.LOCAL_AUDIO_STOPPED="114",YO.REMOTE_AUDIO_STARTED="115",YO.REMOTE_AUDIO_STOPPED="116",YO.PLAY_TRACK_START="151",YO.PLAYER_STATE_CHANGED="152",YO.VIDEO_LOADED_DATA="153",YO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",YO.AUDIO_CONTEXT_LONG_SUSPENDED="155",YO.REMOTE_VIDEO_PLAY_START="156",YO.REMOTE_VIDEO_PLAY_FINISH="157",YO.SIGNAL_CONNECTION_STATE_CHANGED="201",YO.PEER_CONNECTION_STATE_CHANGED="202",YO.SINGLE_CONNECTION_STAT="203",YO.SPC_RECONNECTED="204",YO.HEARTBEAT_REPORT="251",YO.RECEIVED_PUBLISHED_USER_LIST="252",YO.REMOTE_PUBLISH_STATE_CHANGED="253",YO.AUDIO_LEVEL_INTERVAL="260",YO.NETWORK_QUALITY="261",YO.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",YO.QUALITY_LIMITATION_CHANGED="263",YO.LOG="264",YO.AUDIO_PROCESSOR_DEBUG="265",YO.SSO_SWITCH="266",YO.SEI_MESSAGE="267",YO.USER_PAUSE_IN_PIP="268",YO.USER_RESUME_IN_PIP="269",YO.ENTER_PICTURE_IN_PICTURE="270",YO.LEAVE_PICTURE_IN_PICTURE="271",YO.SWITCH_ROOM_START="401",YO.SWITCH_ROOM_SUCCESS="407",YO.SWITCH_ROOM_FAILED="408",YO),QO=XO,$O=new class{constructor(){rw(this,"enable",!1),rw(this,"ssoFailCount",0),JO.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&JO.emit("266",{enable:!0})})),JO.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&JO.emit("266",{enable:!1})}},ZO=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),!bw&&!ww&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){JO.on(QO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&jw[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),JO.on(QO.JOIN_START,(e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),JO.on(QO.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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})}));else if(zD(i.userId)&&KD(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 nw(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:o}=t[e],n={timestamp:gw(),sdkAppId:String(r),userId:i,version:Iw,log:o.map((e=>e.log)).join("\n")},a=JSON.stringify(n),s=$O.enable?MN(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach((e=>e.uploaded=!0))}}catch(cM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return YN({retryFunction:()=>HN({url:SD(t,Ww.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&($O.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(_w()),"[".concat(Ew(t),"] <").concat(jw[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){jD(jw[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(zD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Sw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=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:r,sdkAppId:o,forAllJoinedClients:i};JO.emit(QO.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(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(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=jw[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",...i):console[s](...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){if(e.parent instanceof JN){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)Kb.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&jb)for(var r of jb(e))t.indexOf(r)<0&&qb.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new JN(r);return o.bindParent(i),o}return new JN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;jw[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};rw(ZO,"PRINT_LOG_TAG",!(sk||ck||mO));var eM=new ZO,tM=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)}))},iM=new class{constructor(){rw(this,"_prefix","TRTC"),rw(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){kO()&&(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(cM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(kO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(lM){eM.warn(lM)}}getItem(e){if(!kO())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(Sw){eM.warn(Sw)}}setItem(e,t){if(kO())try{let i={expiresIn:Date.now()+Yw,value:t};this._queue.set(this.getRealKey(e),i)}catch(CC){eM.warn(CC)}}deleteItem(e){if(!kO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Sw){return eM.warn(Sw),!1}}clear(){if(kO())try{localStorage.clear()}catch(lM){eM.warn(lM)}}},rM={};ew(rM,{HTTPS_API:()=>qP,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>fL,IS_GET_CAPABILITIES_SUPPORTED:()=>mL,IS_GET_SETTINGS_SUPPORTED:()=>pL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>hL,IS_INSERTABLE_STREAM_SUPPORTED:()=>_L,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>DL,IS_RTC_RTP_SENDER_SUPPORTED:()=>cL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>gL,IS_SEI_SUPPORTED:()=>EL,IS_SPC_SUPPORTED:()=>sL,basis:()=>SL,capabilityCheck:()=>wL,checkSystemRequirementsInternal:()=>HP,decodeSupportStatus:()=>BP,detectVideoCodecCapabilities:()=>OL,detectVideoDecoderCapabilities:()=>PL,detectVideoEncoderCapabilities:()=>ML,encodeSupportStatus:()=>FP,getBrowserInfo:()=>kP,getDisplayResolution:()=>JP,getH264ProfileLevelIds:()=>LL,isAddTransceiverSupported:()=>aL,isBrowserSupported:()=>OP,isCanvasCaptureStreamAPISupported:()=>$P,isCanvasSmallStreamSupported:()=>ZP,isGetReceiversSupported:()=>rL,isGetSendersSupported:()=>oL,isGetTransceiversSupported:()=>nL,isGetUserMediaSupported:()=>XP,isMediaDevicesSupported:()=>PP,isMediaSessionSupported:()=>TL,isMediaStreamTrackGeneratorSupported:()=>VP,isMediaStreamTrackProcessorSupported:()=>UP,isReplaceTrackSupported:()=>dL,isRequestVideoFrameCallbackSupported:()=>CL,isSIMDSupported:()=>AL,isScaleResolutionDownBySupported:()=>eL,isScreenCaptureApiAvailable:()=>GP,isSelectedCandidatePair:()=>YP,isSetParametersSupported:()=>uL,isSetSinkIdSupported:()=>jP,isSmallStreamSupported:()=>tL,isStopTransceiverSupported:()=>lL,isTRTCSupported:()=>WP,isUnifiedPlanDefault:()=>iL,isUsedInHttpProtocol:()=>xP,isWebAudioSupported:()=>QP,isWebCodecSupported:()=>yL,isWebCodecsSupported:()=>MP,isWebRTCSupported:()=>vL,isWebTransportSupported:()=>IL});var oM={};ew(oM,{AUDIO_LEVEL_SCALE:()=>XM,AlphaStitchingType:()=>dP,AudioCodecPipelineType:()=>iP,AudioDecoderDowngradeState:()=>kM,AudioPlayerMode:()=>qM,AudioType:()=>UM,BASIC_TYPE:()=>ZM,BannedReason:()=>YM,CONNECTION_CLOSED_REASON:()=>EM,CheckPermissionType:()=>lP,ClientEvent:()=>vM,CodecType:()=>rP,ConnectionEvent:()=>gM,ConnectionState:()=>NM,DECODE_FAILED_ERROR_CODE:()=>oP,DenoiserMode:()=>QM,DeviceType:()=>cP,FacingMode:()=>zM,FrameWorkType:()=>_M,LeaveReason:()=>JM,LocalTrackEvent:()=>TM,MULTI_VIDEO_DATA_TYPE:()=>HM,MediaType:()=>LM,MediaTypeLabel:()=>xM,MonitorEventId:()=>WM,MutedFlag:()=>bM,NetworkQualityValue:()=>GM,PlayerState:()=>IM,ReceiveMode:()=>jM,RemoteStreamType:()=>BM,RemoteTrackEvent:()=>RM,RoomEvent:()=>AM,SMALL_MODE:()=>sP,SceneNumber:()=>wM,StreamEvent:()=>yM,StreamType:()=>FM,SubscribeMediaType:()=>$M,TIMER_TYPE:()=>aP,TRACK_ACTION:()=>PM,TRACK_KIND:()=>MM,TrackEvent:()=>SM,UserRole:()=>DM,UserRoleNumber:()=>CM,VideoCodec:()=>eP,VideoCodecPipelineType:()=>tP,VideoContentHint:()=>nP,VideoDecoderDowngradeState:()=>OM,VideoPlayerMode:()=>KM,VideoType:()=>VM});var nM,aM,sM,lM,cM,dM,uM,hM,pM,mM,fM,_M=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(_M||{}),gM=((fM=gM||{}).TRACK_ADDED="track-added",fM.TRACK_UPDATED="track-updated",fM.TRACK_SUBSCRIBED="track-subscribed",fM.STREAM_ADDED="stream-added",fM.STREAM_REMOVED="stream-removed",fM.STREAM_UPDATED="stream-updated",fM.STREAM_PUBLISHED="stream-published",fM.STREAM_SUBSCRIBED="stream-subscribed",fM.STREAM_UNSUBSCRIBED="stream-unsubscribed",fM.STATE_CHANGED="state-changed",fM.ERROR="error",fM.CONNECTION_STATE_CHANGED="connection-state-changed",fM.FIREWALL_RESTRICTION="firewall-restriction",fM.SEI_MESSAGE="sei-message",fM.CLOSED="closed",fM),EM=(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))(EM||{}),vM=((mM=vM||{}).STREAM_ADDED="stream-added",mM.STREAM_REMOVED="stream-removed",mM.STREAM_UPDATED="stream-updated",mM.STREAM_SUBSCRIBED="stream-subscribed",mM.CONNECTION_STATE_CHANGED="connection-state-changed",mM.PEER_JOIN="peer-join",mM.PEER_LEAVE="peer-leave",mM.MUTE_AUDIO="mute-audio",mM.MUTE_VIDEO="mute-video",mM.UNMUTE_AUDIO="unmute-audio",mM.UNMUTE_VIDEO="unmute-video",mM.CLIENT_BANNED="client-banned",mM.NETWORK_QUALITY="network-quality",mM.AUDIO_VOLUME="audio-volume",mM.SEI_MESSAGE="sei-message",mM.ERROR="error",mM),yM=((pM=yM||{}).PLAYER_STATE_CHANGED="player-state-changed",pM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",pM.CONNECTION_STATE_CHANGED="connection-state-changed",pM.DEVICE_AUTO_RECOVERED="device-auto-recovered",pM.ERROR="error",pM),TM=((hM=TM||{}).DEVICE_AUTO_RECOVERED="1",hM.DEVICE_RECOVER_FAILED="5",hM.DEVICE_CHANGED="2",hM.ERROR="3",hM.PUBLISH_STATE_CHANGED="4",hM.ENCODE_FAILED="6",hM.TRACK_ENDED="7",hM.RENDER="render",hM),IM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(IM||{}),AM=((uM=AM||{}).PEER_JOIN="peer-join",uM.PEER_LEAVE="peer-leave",uM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",uM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",uM.BANNED="banned",uM.NETWORK_QUALITY="network-quality",uM.AUDIO_VOLUME="audio-volume",uM.SEI_MESSAGE="sei-message",uM.ERROR="error",uM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",uM.REMOTE_PUBLISHED="remote-published",uM.REMOTE_UNPUBLISHED="remote-unpublished",uM.FIREWALL_RESTRICTION="firewall-restriction",uM.HEARTBEAT_REPORT="heartbeat-report",uM.CUSTOM_MESSAGE="custom-message",uM.LAYER_DATA="layerData",uM.FIRST_VIDEO_FRAME="first-video-frame",uM.DUMP="dump",uM.AUDIO_FRAME="audio-frame",uM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",uM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",uM.NTP_TIME_UPDATED="ntp-time-updated",uM),SM=(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))(SM||{}),RM=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_FAILED_DURING_CALL="decode-failed-during-call",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e.REMOTE_PUBLISH_CHANGED="remote-publish-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",e))(RM||{}),bM=((dM=bM||{})[dM.VIDEO=1]="VIDEO",dM[dM.SMALL=2]="SMALL",dM[dM.AUX=4]="AUX",dM[dM.AUDIO=8]="AUDIO",dM[dM.VIDEO_MUTE=16]="VIDEO_MUTE",dM[dM.AUX_MUTE=32]="AUX_MUTE",dM[dM.AUDIO_MUTE=64]="AUDIO_MUTE",dM),wM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(wM||{}),CM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(CM||{}),DM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(DM||{}),NM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(NM||{}),kM=((cM=kM||{}).INITIALIZED="INITIALIZED",cM.STARTING="STARTING",cM.STARTED="STARTED",cM.FAILED="FAILED",cM),OM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(OM||{}),MM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(MM||{}),PM=(e=>(e.ADD="add",e.REMOVE="remove",e))(PM||{}),LM=(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))(LM||{}),xM={1:"audio",2:"auxVideo",4:"video"},UM=((lM=UM||{})[lM.opus=111]="opus",lM),VM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(VM||{}),FM=(e=>(e.Big="big",e.Small="small",e))(FM||{}),BM=(e=>(e.Main="main",e.Aux="auxiliary",e))(BM||{}),HM=(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))(HM||{}),WM=((sM=WM||{})[sM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",sM[sM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",sM[sM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",sM[sM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",sM[sM.MUTE_AUDIO=32772]="MUTE_AUDIO",sM[sM.MUTE_VIDEO=32773]="MUTE_VIDEO",sM[sM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",sM[sM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",sM[sM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",sM[sM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",sM[sM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",sM[sM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",sM[sM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",sM[sM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",sM[sM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",sM[sM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",sM[sM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",sM[sM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",sM[sM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",sM[sM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",sM[sM.JOIN=32788]="JOIN",sM[sM.LEAVE=32789]="LEAVE",sM[sM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",sM[sM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",sM[sM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",sM[sM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",sM[sM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",sM[sM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",sM[sM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",sM[sM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",sM[sM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",sM[sM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",sM[sM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",sM[sM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",sM[sM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",sM[sM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",sM[sM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",sM[sM.PUBLISH_AUX=32805]="PUBLISH_AUX",sM[sM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",sM[sM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",sM[sM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",sM[sM.VIDEO_DECODER=4005]="VIDEO_DECODER",sM),GM=(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))(GM||{}),jM=(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))(jM||{}),zM=(e=>(e.user="user",e.environment="environment",e))(zM||{}),KM=(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))(KM||{}),qM=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(qM||{}),YM=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(YM||{}),JM=((aM=JM||{})[aM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",aM[aM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",aM[aM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",aM[aM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",aM[aM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",aM[aM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",aM),XM=1e8,QM=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(QM||{}),$M=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)}},ZM=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(ZM||{}),eP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(eP||{}),tP=(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))(tP||{}),iP=(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))(iP||{}),rP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(rP||{}),oP=((nM=oP||{})[nM.SUCCESS=0]="SUCCESS",nM[nM.FAILED=1]="FAILED",nM[nM.WEBCODEC_INIT=2]="WEBCODEC_INIT",nM[nM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",nM[nM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",nM[nM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",nM[nM.WASM_INIT=6]="WASM_INIT",nM[nM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",nM[nM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",nM[nM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",nM[nM.TEST=10]="TEST",nM[nM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",nM),nP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(nP||{}),aP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(aP||{}),sP=(e=>(e.CANVAS="canvas",e.API="api",e))(sP||{}),lP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(lP||{}),cP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cP||{}),dP=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(dP||{}),uP={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"},hP={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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(o,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the max value of ".concat(t||i.name," is ").concat(i.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: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:o}=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:o}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(o," 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,"()")},pP=(e,t)=>t?"".concat(Lw,"/").concat(e,"/").concat(t):"".concat(Lw,"/").concat(e,"/index.html"),mP=()=>{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(Hw);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 fP(e){let{key:t,data:i,link:r,addDocLink:o=!0}=e,n="",a="",s="";GD(hP[t])?n=hP[t](i):zD(hP[t])&&(n=hP[t]);let{TRTC_ERROR_INFO:l,TRTC_ERROR_LINK:c}=mP();r?s="".concat(r.className,".html#").concat(r.fnName):c&&c[t]&&(GD(c[t])?s=c[t](i):zD(c[t])&&(s=c[t]));let d=n;return VD()&&(l&&l[t]&&(GD(l[t])?a=l[t](i):zD(l[t])&&(a=l[t])),a&&(d=o?"".concat(a,"\n请查看文档: ").concat(pP("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=n)),o&&(d+=" \nRefer to: ".concat(pP("en",s),"\n")),d}var _P,gP,EP,vP=tw(dw(),1),yP=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",eM.createLogger({id:"kv"})),e&&(JO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===eC.AUDIO?501700:511700,cost:i})})),JO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===eC.AUDIO?501700:511700,error:i})})),JO.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:IN(this.version||Iw),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 o;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 n=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map;n.set(i,(n.get(i)||0)+1),this.distributionMap.set(t,n)}addNumber(e){let{key:t,value:i,split:r=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;i>n&&(i=n),this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(a=this.distributionMap)?void 0:a.get(t))||new Map,l=0;if(KD(r))l=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){l=c;break}s.set(l,(s.get(l)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:o}=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:o}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=hw.UNKNOWN;i&&(KD(i)?r=i:(!jD(i.extraCode)||!jD(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})}},TP=((gP=TP||{})[gP.enterRoom=500700]="enterRoom",gP[gP.exitRoom=500701]="exitRoom",gP[gP.switchRole=500702]="switchRole",gP[gP.destroy=500703]="destroy",gP[gP.startLocalAudio=500704]="startLocalAudio",gP[gP.updateLocalAudio=500705]="updateLocalAudio",gP[gP.stopLocalAudio=500706]="stopLocalAudio",gP[gP.startLocalVideo=500707]="startLocalVideo",gP[gP.updateLocalVideo=500708]="updateLocalVideo",gP[gP.stopLocalVideo=500709]="stopLocalVideo",gP[gP.startScreenShare=500710]="startScreenShare",gP[gP.updateScreenShare=500711]="updateScreenShare",gP[gP.stopScreenShare=500712]="stopScreenShare",gP[gP.startRemoteVideo=500713]="startRemoteVideo",gP[gP.updateRemoteVideo=500714]="updateRemoteVideo",gP[gP.stopRemoteVideo=500715]="stopRemoteVideo",gP[gP.muteRemoteAudio=500716]="muteRemoteAudio",gP[gP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",gP[gP.use=500718]="use",gP[gP.switchRoom=500719]="switchRoom",gP[gP.getPermissions=500720]="getPermissions",gP[gP.sendSEIMessage=5e5]="sendSEIMessage",gP[gP.sendCustomMessage=500001]="sendCustomMessage",gP),IP=((_P=IP||{})[_P.AudioMixer=550700]="AudioMixer",_P[_P.AIDenoiser=551700]="AIDenoiser",_P[_P.VirtualBackground=570700]="VirtualBackground",_P[_P.Beauty=571700]="Beauty",_P[_P.Watermark=572700]="Watermark",_P[_P.BasicBeauty=574700]="BasicBeauty",_P[_P.FaceDetector=575700]="FaceDetector",_P[_P.CDNStreaming=590700]="CDNStreaming",_P[_P.DeviceDetector=591700]="DeviceDetector",_P[_P.Debug=592700]="Debug",_P[_P.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",_P[_P.VideoMixer=594700]="VideoMixer",_P[_P.AudioProcessor=595700]="AudioProcessor",_P),AP=(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.FaceDetector=575701]="FaceDetector",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))(AP||{}),SP=(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.FaceDetector=575702]="FaceDetector",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))(SP||{}),RP=((EP=RP||{})[EP.DECODER_TYPE=514700]="DECODER_TYPE",EP[EP.DECODER_HW_SW=514701]="DECODER_HW_SW",EP[EP.DECODE_RESULT=514702]="DECODE_RESULT",EP[EP.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",EP[EP.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",EP[EP.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",EP[EP.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",EP[EP.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",EP[EP.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",EP[EP.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",EP[EP.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",EP[EP.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",EP[EP.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",EP[EP.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",EP[EP.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",EP[EP.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",EP[EP.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",EP[EP.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",EP[EP.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",EP),bP=new yP(!0),wP=new yP(!1),CP=bP,DP={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}},NP=new Map([[pk,["Firefox",mk]],[Ek,["Edg",vk]],[pO,["Chrome",_O]],[EO,["Safari",yO]],[Rk,["TBS",bk]],[wk,["XWEB",Ck]],[Ok&&nk,["WeChat",Mk]],[Uk,["QQ(Win)",Vk]],[Lk,["QQ(Mobile)",xk]],[Pk,["QQ(Mobile X5)",xk]],[Fk,["QQ(Mac)",Bk]],[Hk,["QQ(iPad)",Wk]],[Xk,["MI",Qk]],[$k,["HW",tO]],[iO,["Samsung",rO]],[oO,["OPPO",nO]],[aO,["VIVO",sO]],[_k,["EDGE",gk]],[Tk,["SogouMobile",Ik]],[Ak,["Sogou",Sk]]]);function kP(){let e=NP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var OP=function(){return!(Yk||_k||Ek&&yk<80||pk&&fk<56)},MP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},PP=function(){if(!navigator.mediaDevices)return xP()||eM.error(hP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},LP=!1;function xP(){return"http:"===location.protocol&&!NO&&(LP||eM.error(fP({key:uP.NOT_SUPPORTED_HTTP})),LP=!0,!0)}var UP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},VP=function(){return!(null==window||!window.MediaStreamTrackGenerator)},FP=function(){return nw(this,null,(function*(){var e,t,i;if(DP.detail.isH264EncodeSupported&&DP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:DP.detail.isH264EncodeSupported,isVp8EncodeSupported:DP.detail.isVp8EncodeSupported,isH265EncodeSupported:DP.detail.isH265EncodeSupported};let r,o=!1,n=!1,a=!1;try{let s=new RTCPeerConnection,l=document.createElement(eC.CANVAS);l.getContext("2d");let c=l.captureStream(0);return s.addTrack(c.getVideoTracks()[0],c),r=yield s.createOffer(),o=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),n=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),a=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),s.close(),{isH264EncodeSupported:o,isVp8EncodeSupported:n,isH265EncodeSupported:a}}catch(dM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},BP=function(){return nw(this,null,(function*(){var e;if(DP.detail.isH264DecodeSupported&&DP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:DP.detail.isH264DecodeSupported,isVp8DecodeSupported:DP.detail.isVp8DecodeSupported,isH265DecodeSupported:DP.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let o=new RTCPeerConnection;aL()?(o.addTransceiver(eC.VIDEO,{direction:"recvonly"}),t=yield o.createOffer()):t=yield o.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let n=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return o.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:n}}catch(cM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var HP=RN((e=>nw(void 0,null,(function*(){let t=Date.now(),i=vL(),r=PP(),o=MP();if(DP.detail.isWebRTCSupported=i,DP.detail.isMediaDevicesSupported=r,DP.detail.isWebCodecsSupported=o,DP.detail.isScreenShareSupported=GP(),DP.detail.isSmallStreamSupported=tL(),37===e)return Object.assign(DP.detail,yield function(){return nw(this,null,(function*(){return KP||(KP=new Promise((e=>nw(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!MP())return void e(t);let i=null,r=null,o=null,n=()=>{o&&clearTimeout(o),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let a=0,s=()=>{!r||!i||(r.fillStyle="hsl(".concat(a%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(a),10,30),a++)};o=setTimeout((()=>{n(),e(t)}),5e3);let l=[{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(l.map((e=>nw(this,null,(function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,o)=>nw(this,null,(function*(){try{let n=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:o});n.configure(e.encodeConfig),s();let a=new VideoFrame(i,{timestamp:0});n.encode(a,{keyFrame:!0}),a.close(),yield n.flush(),n.close()}catch(fM){o(fM)}}))))}catch(p){return eM.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise(((i,o)=>nw(this,null,(function*(){try{let n=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:o});n.configure(e.decodeConfig),n.decode(t),yield n.flush(),n.close()}catch(fM){o(fM)}}))))}catch(p){eM.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)})),n(),e(t)}catch(a){n(),eM.warn("detectWebCodecsSupported failed:",a),e(t)}})))),KP)}))}()),DP.detail.isBrowserSupported=o,DP.result=r&&o,DP.result||eM.error("".concat(navigator.userAgent," ").concat(EN(DP.detail,!1))),bL(e),CP.addNumber({key:523800,value:Date.now()-t}),DP;if(DP.result&&DP.detail.isH264EncodeSupported&&DP.detail.isVp8EncodeSupported&&DP.detail.isH265EncodeSupported&&DP.detail.isH264DecodeSupported&&DP.detail.isVp8DecodeSupported&&DP.detail.isH265DecodeSupported)return DP;let n=OP(),{encode:a,decode:s}=yield function(){return nw(this,null,(function*(){let[e,t]=yield Promise.all([FP(),BP()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:l,vp8:c}=a,{h264:d}=s,{h265:u}=a,{vp8:h,h265:p}=s;if(!l||!c){let e=yield FP();eM.warn("detect encode again h264:".concat(l," vp8:").concat(c," result: ").concat(JSON.stringify(e))),l=e.isH264EncodeSupported,c=e.isVp8EncodeSupported}if(l&&d&&ck&&hO&&!wk&&!Rk&&(!oO||115!==fO)){let{encode:e,decode:t}=yield function(){return nw(this,null,(function*(){return zP||(zP=new Promise((e=>nw(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=640,r.height=480;let n=setInterval((()=>{o.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),66),a=-1,s=-1;i=()=>{clearInterval(a),clearInterval(n),clearTimeout(s),c.close(),d.close(),l.getTracks().forEach((e=>e.stop()))},s=setTimeout((()=>{i(),e(t)}),2e3);let l=r.captureStream(),c=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});c.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>c.addIceCandidate(e.candidate))),c.addTrack(l.getVideoTracks()[0],l);let u=yield c.createOffer();yield c.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=vP.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=vP.default.write(p),yield d.setLocalDescription(h),yield c.setRemoteDescription(h),a=setInterval((()=>nw(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,o]=yield Promise.all([c.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===eC.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||o.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===eC.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),eM.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&eM.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(xO)),e))),zP)}))}();l=e,d=t}return DP.result=n&&i&&r&&(l||c)&&(d||h),DP.detail.isBrowserSupported=n,DP.detail.isWebRTCSupported=i,DP.detail.isH264EncodeSupported=l,DP.detail.isVp8EncodeSupported=c,DP.detail.isH265EncodeSupported=u,DP.detail.isH264DecodeSupported=d,DP.detail.isVp8DecodeSupported=h,DP.detail.isH265DecodeSupported=p,DP.result||eM.error("".concat(navigator.userAgent," ").concat(EN(DP.detail,!1))),bL(),CP.addNumber({key:523800,value:Date.now()-t}),DP})))),WP=function(){return DP.result},GP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},jP="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,zP=null;var KP=null;var qP=(e,t,i)=>{"http:"===location.protocol&&!NO&&(e[t]=()=>{throw new mw({code:hw.INVALID_OPERATION,message:hP.NOT_SUPPORTED_HTTP})})},YP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(qD(e.selected)&&!e.selected)};function JP(){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 XP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function QP(){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 $P(){return"captureStream"in HTMLCanvasElement.prototype}function ZP(){return!(Ok||sk||fO&&fO<63)&&!(!OP()||!$P())}function eL(){return!(fO<74||_k||RO<11||fk<46)}function tL(){return ZP()||eL()}var iL=function(){if(jD(window.RTCRtpTransceiver)||!aL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:PC}),e.addTransceiver(eC.AUDIO),t=!0}catch(Sw){}return null==e||e.close(),t};function rL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function oL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function nL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function aL(){return!(11===RO&&!DO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var sL=!(!aL()||hO&&fO<86);function lL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var cL="RTCRtpSender"in window;function dL(){return cL&&"replaceTrack"in window.RTCRtpSender.prototype}function uL(){return cL&&"setParameters"in window.RTCRtpSender.prototype&&oL()}var hL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,pL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,mL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,fL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,_L=cL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&dO()>=86,gL="RTCRtpScriptTransform"in window,EL=cL&&(_L||gL),vL=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function yL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return jD(window.AudioDecoder)||(e.AudioDecoder=!0),jD(window.AudioEncoder)||(e.AudioEncoder=!0),jD(window.VideoDecoder)||(e.VideoDecoder=!0),jD(window.VideoEncoder)||(e.VideoEncoder=!0),jD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function TL(){return"mediaSession"in navigator&&!jD(navigator.mediaSession.setActionHandler)}function IL(){return!jD(window.WebTransport)}function AL(){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 SL(){let e={browser:"".concat(OO.name,"/").concat(OO.version),os:WO(),displayResolution:JP(),isScreenShareSupported:GP(),isWebRTCSupported:vL(),isGetUserMediaSupported:XP(),isWebAudioSupported:QP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:yL(),isMediaSessionSupported:TL(),isWebTransportSupported:IL()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var RL="checkResult";function bL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;iM.setItem(RL+e,{ua:navigator.userAgent,checkResult:DP})}function wL(e){xP();let t=iM.getItem(RL+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!YD(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,DP.detail)&&(DP=t.checkResult),HP(e)}function CL(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var DL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function NL(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var kL=!1;function OL(){return nw(this,null,(function*(){var e;try{if(kL||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=GO(),i=jO();if(0===t||0===i)return;kL=!0;let r=["H264","VP8","VP9","AV1","H265"],[o,n]=yield Promise.all([ML(r),PL(r)]);o&&Object.keys(o).forEach((e=>{let r=NL(e.toLowerCase());CP.addEnum({key:513707,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})})),n&&Object.keys(n).forEach((e=>{let r=NL(e.toLowerCase());CP.addEnum({key:514713,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})}));let{sender:a,receiver:s}=LL();CP.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+a.high),useUV:!1}),CP.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+a.main),useUV:!1}),CP.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+s.high),useUV:!1}),CP.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+s.main),useUV:!1})}catch(lM){eM.info("detectVideoCodecCapabilities failed",lM)}}))}function ML(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return nw(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:i,bitrate:o,framerate:r}});n[a]=e}}catch(Rw){}return n}))}function PL(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return nw(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:i,bitrate:o,framerate:r}});n[a]=e}}catch(Rw){}return n}))}function LL(){let e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};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])switch(i[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}}))}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])switch(i[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}}))}}catch(lM){eM.warn("get H264 profile levelId failed",lM)}return e}var xL=tw(aw(),1),UL=Symbol("instance"),VL=Symbol("cacheResult"),FL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,jL.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},BL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var HL=new Map;function WL(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=HL.get(r)||[];HL.has(r)||HL.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=zL.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[VL]:Promise.resolve(r[VL]);r.state instanceof FL&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof FL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(c=new BL(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new BL(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new FL(u,t,a);jL.call(r,h);let p=e=>{var o;return r[VL]=e,h.aborted||(jL.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[VL])),e},m=e=>(jL.call(r,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):i.sync?p(e):Promise.resolve(p(e))}catch(mM){return m(new BL(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(mM),mM instanceof Error?mM:new Error(String(mM))))}}}}var GL="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 jL(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(zL.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var zL=class e extends xL.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 o=r[UL];o?this.name=o.name+"-"+o.count++:r[UL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=HL.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);HL.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:n})})):o.push({to:i,action:n})})),r.forEach((e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};GL(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){jL.call(this,e)}};zL.STATECHANGED="stateChanged",zL.UPDATEAFSM="updateAFSM",zL.INIT="[*]",zL.ON="on",zL.OFF="off",zL.instances=new Map,zL.instances2=new WeakMap;var KL="undefined"!=typeof window,qL=KL&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},YL=KL&&window.cancelIdleCallback||function(e){clearTimeout(e)},JL=KL&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),XL=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=Qb("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=$b(Qb({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=oN(),o=()=>{if(i=oN()-r,i>=t.delay&&(r=oN()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=qL(o,{timeout:t.delay})};return t.ricID=qL(o,{timeout:t.delay})}static raf(t){let i,r=oN(),o=()=>document.hidden&&t.backgroundTask?(i=oN()-r,r=oN(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(i%t.delay))):(i=oN()-r,i>=t.delay&&(r=oN()-Math.floor(i%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=oN()-r;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:i,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&JL&&JL(r),o&&YL(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(XL,"taskMap",new Map),rw(XL,"currentTaskID",1),rw(XL,"sharedWorker",null),rw(XL,"workerTasks",new Map);var QL=XL;eC.SEI_MESSAGE;var $L={LOAD_START:eC.LOADSTART,LOADED_DATA:eC.LOADEDDATA,LOADED_META_DATA:eC.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:eC.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:eC.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:eC.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP:"user-resume-in-pip",USER_PAUSE_IN_PIP:"user-pause-in-pip"},ZL={};ew(ZL,{create:()=>tx,remove:()=>ix});var ex=new WeakMap;function tx(e,t){ex.has(e)||ex.set(e,[]);let i=ex.get(e),r={add:(e,o)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,o)),t.addEventListener(e,o)):(i.push(t.off.bind(t,e,o)),t.on(e,o)),r)};return r}function ix(e){let t=ex.get(e);t&&(t.forEach((e=>e())),ex.delete(e))}var rx=new class{constructor(){rw(this,"_roomIdMap",new Map),rw(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Iw,env:Gw.QCLOUD,browserVersion:OO.name+OO.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:o}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(e){NO||!eM.isAbleToUpload||this._configs.env===Gw.QCLOUD&&this.uploadEventToKibana($b(Qb({},e),{result:"success"}))}logFailedEvent(e){if(NO||!eM.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:o}=e,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||hw.UNKNOWN};this._configs.env===Gw.QCLOUD&&this.uploadEventToKibana($b(Qb({},n),{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,o={timestamp:gw(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Iw,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+="\n".concat(r.stack)));let n=$O.enable?MN(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(SD(this._configs.sdkAppId,Ww.LOG),n)}sendRequest(e,t){setTimeout((()=>HN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},ox=new WeakMap;function nx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:o}=e;return function(e,n,a){let s=YN({retryFunction:a.value,settings:t,onError(t){let{error:r,retry:o,reject:a,retryFuncArgs:s}=t;var l;i?i.call(this,r,(()=>{var t;null!=(t=ox.get(e))&&t.has(n)?o():a(r)}),a,s):null!=(l=ox.get(e))&&l.has(n)?o():a(r)},onRetrying(t,i){var o;jN(r)&&r.call(this,t,i),null!=(o=ox.get(e))&&o.has(n)&&(ox.get(e).get(n).stopRetry=i)},onRetryFailed:o});return a.value=function(){let t=ox.get(e);for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return t?t.set(n,{args:r}):ox.set(e,new Map([[n,{args:r}]])),s.apply(this,r).finally((()=>{var t;return null==(t=ox.get(e))?void 0:t.delete(n)}))},a}}var ax=class extends zL{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,"isPlayCalled",!1),rw(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=KC,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 nw(this,null,(function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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(Sw){let t=fP({key:uP.PLAY_FAILED,data:{media:this.kind,error:Sw}});if(this._log.warn(Sw),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new mw({code:hw.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!vO?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(eC.ENDED),this._interval>0&&QL.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(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;null==(e=this.element)||e.pause()}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(e)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():wO?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return tx(this.element,this.element).add(eC.PLAYING,e).add(eC.ENDED,e).add(eC.PAUSE,e).add(eC.ERROR,e).add(eC.LOADSTART,e).add(eC.LOADEDDATA,e).add(eC.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==ZL||ZL.create(e,e).add(eC.ENDED,t).add(eC.MUTE,t).add(eC.UNMUTE,t),e.readyState===eC.ENDED&&this.handleTrackEvent({type:eC.ENDED}),e.muted&&this.handleTrackEvent({type:eC.MUTE})}}bindAutoPlayEvent(){JO.listeners(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM).includes(this.resume)||JO.on(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&ix(e)}unbindEvents(){this.element&&ix(this.element),this.unbindTrackEvents(),JO.off(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case eC.PLAYING:Sx()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(eC.PLAYING),this._interval&&(QL.clearTask(this._interval),this._interval=-1);break;case eC.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(eC.ENDED);break;case eC.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(eC.PAUSE);break;case eC.ERROR:if(this.element&&this.element.error){this.handlePaused(eC.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)),rx.uploadEvent({log:"stat-".concat(this.kind,"-").concat(NC.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),eO||Zk?this.emit($L.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case eC.LOADEDDATA:this.kind===eC.VIDEO&&this.emit($L.LOADED_DATA);break;case eC.LOADEDMETADATA:this.kind===eC.VIDEO&&this.emit($L.LOADED_META_DATA);break;case eC.LOADSTART:this.emit($L.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),rx.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),CP.addSuccessEvent({key:this.kind===eC.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),rx.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),CP.addFailedEvent({key:this.kind===eC.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit($L.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{SN(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)}),SN(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 nw(this,null,(function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===eC.UNMUTE?"info":"warn"]("track ".concat(t)),t){case eC.ENDED:this.handleStopped(eC.ENDED);break;case eC.MUTE:this.handlePaused(eC.MUTE);break;case eC.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(eC.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(ax,"PlayerEvent",$L),iw([nx({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],ax.prototype,"doReplayByRecreateMediaStream",1),iw([WL([],"PLAYING",{sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],ax.prototype,"handlePlaying",1),iw([WL("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],ax.prototype,"handlePaused",1),iw([WL([],"STOPPED",{sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],ax.prototype,"handleStopped",1);var sx="trtc_autoplay",lx="".concat(sx,"_mask"),cx="".concat(sx,"_wrapper"),dx="".concat(sx,"_header"),ux="".concat(sx,"_content"),hx="".concat(sx,"_action_wrapper"),px="".concat(sx,"_question"),mx="".concat(sx,"_collapse"),fx="".concat(sx,"_action_confirm"),_x="".concat(sx,"_detail"),gx="#2473E8",Ex="dialog",vx="".concat(Ex,"-show"),yx="".concat(Ex,"-1"),Tx="".concat(Ex,"-2"),Ix=!1,Ax=!1,Sx=()=>Ax,Rx="".concat(Lw,"/").concat(VD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),bx="<br><a href='".concat(Rx,"' target='_blank'>").concat(VD()?"其他方案?":"Any other solution?","</a>"),wx="".concat(VD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(bx):"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(bx)),Cx=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),VD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ix){let e=document.createElement("style");e.innerHTML=".".concat(lx,"{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(lx," div:not(.").concat(hx,"){display:block !important;}.").concat(cx,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(cx," a{color:").concat(gx,";}.").concat(dx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(ux,"{margin:8px 0;}.").concat(hx,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(mx,"{margin-right:auto;cursor:pointer}.").concat(px,"{height:100%;line-height:16px;cursor:pointer;}.").concat(fx,"{margin-left:8px;color:#fff;background:").concat(gx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(fx,":hover{opacity:0.9;}.").concat(mx,",.").concat(fx,",.").concat(ux,",.").concat(px,"{font-size:14px;}@media screen and (max-width:750px){.").concat(cx,"{width:80vw;}}"),document.head.appendChild(e),Ix=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(lx,"\"><div class='").concat(cx,"'><div class='").concat(dx,"'>").concat(location.host,"</div><div class='").concat(ux,"'>").concat(this.content,"</div><div class='").concat(_x,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(wx,"</div><div class='").concat(hx,"'></div></div></div>").trim();let t=document.createElement("button");t.className=fx,t.innerText=VD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=px,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=mx,r.innerText="".concat(VD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let o=e.content.firstChild,n=o.querySelector(".".concat(hx));return n.appendChild(r),n.appendChild(i),n.appendChild(t),o}addDiaLog(){Sx()||(Ax=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(cx)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",eM.info("show autoplay dialog"),rx.uploadEvent({log:vx}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ax=!1),Dx=null}onConfirm(){eM.warn("confirm clicked, try resume stream"),JO.emit(QO.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||rx.uploadEvent({log:yx}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Rx,"_blank"),this._isQuestionClicked||rx.uploadEvent({log:Tx}),this._isQuestionClicked=!0}},Dx=null;function Nx(){Dx||(Dx=new Cx)}var kx,Ox=class e extends ax{constructor(e){super(e,eC.VIDEO),rw(this,"stat",{}),rw(this,"_calculateTimeout",-1),rw(this,"viewMirror",!1),rw(this,"objectFit","cover"),rw(this,"container"),rw(this,"canvas"),rw(this,"shouldRenderAlpha",!1),rw(this,"_preSize",{width:0,height:0}),rw(this,"posterImg"),rw(this,"_originContainerPosition"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,jD(e.viewMirror)||(this.viewMirror=e.viewMirror),jD(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(eC.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,ck&&(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,";").concat(this.shouldRenderAlpha?"":"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(eC.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(eC.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(eC.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===eC.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,i,r,o,n,a;if(2===this.mode)return;super.handleElementEvent(e);let s=e.type,l=this.isPictureInPicture()&&e.isTrusted&&EO;if(s===eC.PLAYING&&l&&(this._log.warn("user resume in pip"),this.emit($L.USER_RESUME_IN_PIP)),s===eC.PAUSE&&(l&&(this._log.warn("user pause in pip"),this.emit($L.USER_PAUSE_IN_PIP)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),SN(500).then((()=>{var e;null!=(e=this.container)&&e.isConnected&&(this._pausedRetryCount=KC,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))}))),this._pausedRetryCount>0&&!Sx()&&!this.isPausedByUserCall&&!l&&(this._log.info("[".concat(KC-this._pausedRetryCount+1,"/").concat(KC,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),sk&&!l&&(this._interval=QL.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&!this.isPausedByUserCall&&this.doResume()}),{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;s===eC.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):s===eC.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}s===eC.RESIZE&&(this._preSize.height!==(null==(t=this.element)?void 0:t.videoHeight)||this._preSize.width!==(null==(i=this.element)?void 0:i.videoWidth))&&(this._log.info("video size changed to ".concat(null==(r=this.element)?void 0:r.videoWidth,"x").concat(null==(o=this.element)?void 0:o.videoHeight)),this._preSize.height=(null==(n=this.element)?void 0:n.videoHeight)||0,this._preSize.width=(null==(a=this.element)?void 0:a.videoWidth)||0,this.emit($L.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),s===eC.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),ck&&hO&&fO<143&&this.isPlayCalled&&this.element&&this.track&&(this._log.warn("reset srcObject for android chrome after exit pip"),this.element.srcObject=new MediaStream([this.track]),this.element.play().catch((e=>{this._log.warn("play failed after reset srcObject",e)}))),this.emit($L.LEAVE_PICTURE_IN_PICTURE)),s===eC.ENTER_PICTURE_IN_PICTURE&&(this._log.warn("enter pip"),this.emit($L.ENTER_PICTURE_IN_PICTURE))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,o,n;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==(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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((i=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),""===e?this.element.removeAttribute("poster"):this.element.poster=e,!t||!EO&&!pk))return i();if(""===e)return this.removePosterImg(),i();if(this.posterImg)return i();let r=document.createElement("img");r.src=e;let o=window.getComputedStyle(this.element).objectFit||this.objectFit;r.style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(o,";"),r.onload=()=>nw(this,null,(function*(){var e;try{r.decode&&(yield r.decode()),this.container&&"static"===window.getComputedStyle(this.container).position&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=r,null==(e=this.container)||e.appendChild(r),lk()&&RO<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(t){this._log.warn("decode poster image error",t)}return i()})),r.onerror=()=>(this._log.warn("load poster image error"),i())}))}removePosterImg(){this.posterImg&&(lk()&&RO<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!jD(this._originContainerPosition)&&"relative"===this.container.style.position&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!(null==(e=this.element)||!e.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return nw(this,null,(function*(){ow(e.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(hO&&fO>=128||t&&(pk||EO))&&(yield this.setPoster(this.getVideoFrame(),!0))}))}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return super.resume(e).then((()=>{var e;(this.posterImg||null!=(e=this.element)&&e.poster)&&this.setPoster("",!0)}))}doResume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&hO&&fO>=128&&"video"===this.track.kind&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPictureInPicture()&&this.exitPictureInPicture().catch((e=>{})),this.isFullscreen()&&this.exitFullscreen().catch((e=>{})),super.stop(e),null==(t=this.canvas)||t.remove(),this.removePosterImg()}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($L.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(CL()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,o)=>{this.stat.width=o.width,this.stat.height=o.height,t&&(this.stat.fps=Math.round((o.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=o,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(Sw){this._log.warn("init stat failed",Sw)}}enterFullscreen(){return nw(this,null,(function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(CC){throw this._log.error("failed to enter fullscreen:",CC),CC}}))}exitFullscreen(){return nw(this,null,(function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(Sw){throw this._log.error("failed to exit fullscreen:",Sw),Sw}}))}isFullscreen(){let e=this.elementToRender;return!!e&&(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e}toggleFullscreen(){return nw(this,null,(function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()}))}enterPictureInPicture(){return nw(this,null,(function*(){var e;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&1!==this.mode)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let i=yield t.requestPictureInPicture();return this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),null==(e=this.container)||e.appendChild(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(CC){throw this._log.error("failed to enter pip:",CC.name,CC.message),CC}}))}exitPictureInPicture(){return nw(this,null,(function*(){var e,t;try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&(null==(e=this.element)||e.remove(),this._pausedRetryCount=KC,null==(t=this.container)||t.appendChild(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(cM){throw this._log.error("failed to exit pip:",cM),cM}}))}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&"picture-in-picture"===e.webkitPresentationMode}togglePictureInPicture(){return nw(this,null,(function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()}))}};function Mx(e,t){return nw(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),eM.info("worklet addModule success")}catch(Sw){throw eM.info("worklet addModule catch error. ".concat(Sw.message)),Sw}}))}"undefined"!=typeof AudioContext?kx=AudioContext:"undefined"!=typeof webkitAudioContext?kx=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(kx=mozAudioContext);var Px,Lx=1500,xx=-1,Ux=0,Vx=-1,Fx=!1,Bx=0,Hx=-1,Wx=-1;!function e(){try{if(Px)return;(Px=new kx({sampleRate:48e3})).onstatechange=()=>{eM.info("context state: ".concat(Px.state).concat("running"!==Px.state?" visibilityState: ".concat(document.visibilityState):"")),Gx()},clearTimeout(xx)}catch(UH){eM.error("initAudioContext failed: ".concat(UH," typeof AudioContextClass: ").concat(typeof kx)),xx=setTimeout(e,1e3)}}();var Gx=()=>{"suspended"===Px.state?(Ux=oN(),-1===Vx&&(Vx=setTimeout((()=>{"suspended"===Px.state&&(Fx=!0,JO.emit("155",{isSuspended:!0}))}),Lx)),Kx(),document.addEventListener("click",Gx)):"interrupted"===Px.state?Kx():(Ux&&(CP.addNumber({key:507800,value:oN()-Ux,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Ux=0),-1!==Vx&&(clearTimeout(Vx),Vx=-1,Fx&&(Fx=!1,JO.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",Gx),document.removeEventListener("click",Gx))},jx=0,zx=-1;function Kx(){return new Promise(((e,t)=>{if("running"===Px.state)return e();Date.now()-jx<1e3?(clearTimeout(zx),zx=setTimeout((()=>{jx=Date.now(),Px.resume().then(e,t)}),1e3)):(clearTimeout(zx),jx=Date.now(),Px.resume().then(e,t))})).catch((e=>{eM.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",Gx)}))}document.addEventListener("click",Gx);var qx=e=>Px,Yx=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(CC){eM.error(CC)}}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(),CP.addSuccessEvent({key:502701})}catch(cM){eM.error(cM),CP.addFailedEvent({key:502701,error:cM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),CP.addSuccessEvent({key:502702})}catch(Sw){eM.error(Sw),CP.addFailedEvent({key:502702,error:Sw})}}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}},Jx=class extends Yx{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,i=0,r="M".concat(t,",").concat(i);for(let o=0;o<e.length;o++)i=e[o]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},Xx=class{constructor(){rw(this,"source",new Yx),rw(this,"gain",new Yx),rw(this,"destination",new Yx)}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(qx().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=eU(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}},Qx=class extends Xx{constructor(e){super(),this.context=e,rw(this,"aec",new Yx("aec")),rw(this,"mixNode",new Yx("mixNode")),rw(this,"silentNode",new Yx("silentNode")),rw(this,"denoiser",new Yx("denoiser")),rw(this,"voiceChanger",new Yx("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()}},$x=class{constructor(){rw(this,"audioContext",qx()),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]}},Zx=new WeakMap;function eU(e){try{let t=Zx.get(e);if(t)return t;let i=qx();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return Zx.set(e,t),t}catch(lM){if(!(pk&&lM instanceof Error&&"NotSupportedError"===lM.name))throw lM;eM.warn(lM)}}var tU=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,JO.on(QO.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=Mx(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(lM){this._log.error("volumeMeter init audio worklet error: ".concat(lM)),rx.logFailedEvent({userId:this._log.userId,eventType:NC.LOAD_WORKLET,error:lM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qx().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(lM){this._log.error("volumeMeter init script processor error: ".concat(lM))}}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,JO.off(QO.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})}};rw(tU,"lastMessageTime",0),rw(tU,"audioContext",qx()),rw(tU,"workletReady");var iU=tU,rU=class extends Yx{constructor(e){super(),rw(this,"_volumeMeter"),this._volumeMeter=new iU(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return nw(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()}}},oU=iU,nU=tw(aw(),1),aU=e=>t=>t.deviceId===e,sU=class{constructor(e,t){rw(this,"kind"),rw(this,"type"),rw(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&&dU(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(aU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");eM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(aU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");eM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},lU=class extends nU.EventEmitter{constructor(){super(),rw(this,"audioInputs",new sU(eC.AUDIO,"Input")),rw(this,"videoInputs",new sU(eC.VIDEO,"Input")),rw(this,"audioOutputs",new sU(eC.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||QL.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){uU().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return nw(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield uU(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=qx())?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)))))}},cU=ww||bw?null:new lU;function dU(e){return e.deviceId===e.groupId&&""===e.groupId}function uU(){return nw(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(xP()||!PP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{dU(e)&&(e.kind===eC.AUDIO_INPUT?i.audio=!0:e.kind===eC.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&&Kx()}catch(cM){eM.debug("capture before getDevices failed: ",cM)}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&&_U.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function hU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return cU.update(e?1:0).then((e=>e.audioInputs.devices))}function pU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return cU.update(e?2:0).then((e=>e.videoInputs.devices))}var mU=!1;function fU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nw(this,null,(function*(){return(sk||EO)&&(e=!1),cU.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var _U=new Set;function gU(e,t){return nw(this,null,(function*(){let i=(yield hU()).find((e=>e.deviceId===qC));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var EU,vU=class extends Xx{constructor(e){super(),this.log=e,rw(this,"volumeMeter"),rw(this,"volumeMeterAfter3A"),rw(this,"volumeDestination"),rw(this,"analyser",new Jx),this.volumeMeter=new rU({log:this.log}),this.volumeMeterAfter3A=new rU({log:this.log}),this.volumeDestination=new Yx,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},yU=class e extends ax{constructor(e){super(e,eC.AUDIO),rw(this,"_outputDeviceId"),rw(this,"_floatVolume",1),rw(this,"_destination"),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 vU(this._log)}setTrack(e){}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"===IO||"15.3"===IO||"15.4"===IO)&&this.muted)return void this._log.info("audioElement is muted.");let t=EU||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,this.setVolume(KD(e)?e/100:this._floatVolume),t===EU&&(EU=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit($L.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return nw(this,null,(function*(){if(this.track||this.url){try{!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(qx().createAnalyser()),function(){nw(this,null,(function*(){try{mU||(mU=!0,eM.info("speakers:".concat((yield fU()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}()}catch(CC){throw this._log.warn("audio play error: ".concat(CC)),(wk||Ok)&&SO(IO,"18.7",!0)&&this.bindAutoPlayEvent(),CC}return ow(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._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return nw(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 yU{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit($L.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},IU=class extends yU{constructor(e){super(e),rw(this,"_sourceElement"),rw(this,"_output",new Yx),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(qx().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($L.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){var t;let i=e<=1&&!lk();if(this._floatVolume!==e||!(i&&(null==(t=this.element)?void 0:t.volume)===e||!i&&this.pipeline.volume===e))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(i)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(lk()){if(!this.enableVolumeControlInIOS)return;!function(){if(!sk||-1!==Wx)return;let e=()=>{oN()-Bx<500||(Px&&"running"===Px.state&&Px.currentTime===Hx&&(eM.warn("context is fake running, auto resume"),Px.suspend().catch((e=>{eM.warn("context suspend failed: ".concat(e))}))),Hx=Px.currentTime,Bx=oN())};Wx=setInterval((()=>{e()}),2e3),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&e()}))}()}if(pk&&!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._destination||(this._destination=qx().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),ix(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch((e=>{this.emit($L.AUTOPLAY_FAILED,e)})))}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&vO&&(EU=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},AU=class extends zL{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:o,PlayerClass:n=(1===r?IU:Ox)}=e;var a;super(),rw(this,"id",tM()),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=r,this._log=eM.createLogger({parent:null==o?void 0:o.getLogger(),id:"".concat(this.kind[0],"t"),userId:null==(a=o||this.room)?void 0:a.userId,remoteUserId:this instanceof sB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof sB}),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($L.PLAYER_STATE_CHANGED,(e=>{if(JO.emit(QO.PLAYER_STATE_CHANGED,Qb({track:this},e)),this.emit("player-state-changed",e),"PLAYING"===e.state&&this.room){let e=!0;for(let{remoteAudioTrack:t,remoteVideoTrack:i,remoteAuxiliaryTrack:r}of[...this.room.remotePublishedUserMap.values()])if(t.isAvailable&&!t.player.isPlaying||i.isAvailable&&!i.player.isPlaying||r.isAvailable&&!r.player.isPlaying){e=!1;break}e&&Sx()&&Dx&&Dx.deleteDialog()}})),this.kind===eC.VIDEO&&(this.player.on($L.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent($L.LOADED_DATA),JO.emit(QO.VIDEO_LOADED_DATA,{track:this})})),this.player.on($L.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent($L.LOADED_META_DATA)})),this.player.on($L.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})),this.player.on($L.RESIZE,(e=>{this.emitFirstVideoFrameEvent($L.RESIZE),this.emit("video-size-changed",Qb({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($L.ERROR,this.onPlayerError.bind(this)),this.player.on($L.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||eM}get kind(){return 1===this.mediaType?eC.AUDIO:eC.VIDEO}get isAudio(){return this.kind===eC.AUDIO}get strMediaType(){return 4===this.mediaType?eC.VIDEO:2===this.mediaType?eC.SCREEN:eC.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 nw(this,null,(function*(){let i=JD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!jD(t.muted)&&this.setPlayerMute(t.muted),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof Ox&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),JD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!jD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===eC.VIDEO)&&this.setPlayerMute(!0),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Ox&&(this.player.setObjectFit(this.objectFit),t&&!jD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof Ox&&this.player.setContainer(i)),JO.emit(QO.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),JD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(pM){throw this.handleAutoPlayFailed(pM),pM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==eC.VIDEO||jD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(qD(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 nw(this,null,(function*(){if(!this._outputTrack||this.kind===eC.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,o]of e.entries()){let e=this.subVideoPlayerMap.get(o);e?t&&(jD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new Ox({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(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.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(KN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return nw(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),JO.emit(e?QO.TRACK_MUTED:QO.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){tx(e,e).add(eC.MUTE,this.onTrackMuted).add(eC.UNMUTE,this.onTrackUnmuted).add(eC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===eC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ix(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){var t,i;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){if(KN(this)&&this.isAudio&&null!=(t=this.user)&&t.muteState.hasAudio&&null!=(i=this.user)&&i.muteState.audioMuted)return;return this.player.stop(KN(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){return nw(this,null,(function*(){var t;this.log.warn("handleAutoPlayFailed",e);let i=()=>{this.resume().then((()=>{document.removeEventListener("click",i,!0)}))};if(this.room&&this.room.enableAutoPlayDialog){if((wk||Ok)&&(yield SN(100),null!=(t=this.player)&&t.isPlaying))return;Nx()}else document.addEventListener("click",i,!0);JO.once(QO.LOCAL_TRACK_CAPTURE_SUCCESS,(e=>{let{track:t}=e;"audio"===t.kind&&Sx()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()})),this.emit("error",e)}))}getVideoFrame(){return this.player instanceof Ox?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let o=null==(t=this.mediaTrack)?void 0:t.getSettings(),n=(null==o?void 0:o.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,a=(null==o?void 0:o.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===$L.RESIZE&&!n&&!a||e===$L.LOADED_META_DATA&&!n&&!a||(e===$L.LOADED_DATA&&!n&&!a&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,DN(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"))}};iw([WL([],zL.INIT,{sync:!0})],AU.prototype,"_toInitState",1);var SU=Object.prototype.hasOwnProperty;var RU=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(FD(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(SU.call(e,t))return!1;return!0}return!1},bU=YN({retryFunction:function(e){return nw(this,null,(function*(){let t=function(e){return{audio:CU(e),video:DU(e)}}(e);eM.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],o=["label","deviceId","groupId"];if(t.audio&&(i=yield hU(),eM.info("microphones: ".concat(gN(i.map((e=>$b(Qb({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:o})))),t.video&&(r=yield pU(),eM.info("cameras: ".concat(gN(r,{keysToInclude:o}))),!qD(t.video)&&"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,eM.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let i=yield navigator.mediaDevices.getUserMedia(t);return mL&&i.getTracks().forEach((t=>{var i;let r=t.getCapabilities();eM.info("".concat(t.kind," capabilities: ").concat(gN(r,{keysToInclude:eD}))),!jD(e.echoCancellation)&&-1===(null==(i=r.echoCancellation)?void 0:i.indexOf(e.echoCancellation))&&eM.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(r.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))})),t.audio&&Kx(),i}catch(pM){let{message:o}=pM;throw"NotFoundError"===pM.name&&(e.video&&r&&0===r.length&&(o=fP({key:uP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(o=fP({key:uP.MICROPHONE_NOT_FOUND}))),new mw({code:hw.INITIALIZE_FAILED,name:pM.name,message:o,constraint:pM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,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,(!EO||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),i()):r(t),o[0].microphoneId&&wU(o[0].microphoneId,!1),o[0].cameraId&&wU(o[0].cameraId,!0)},onRetrying:e=>{eM.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{rx.logFailedEvent({eventType:NC.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{rx.logSuccessEvent({eventType:NC.GET_USER_MEDIA_RETRY}),rx.uploadEvent({log:"stat-".concat(NC.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function wU(e,t){return nw(this,null,(function*(){let i=(t?yield pU():yield hU()).find((t=>t.deviceId===e));i&&GD(i.getCapabilities)&&eM.warn(gN(i.getCapabilities(),{keysToInclude:eD}))}))}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!RU(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(KD(e.channelCount)&&(t.channelCount=e.channelCount),(qD(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),qD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),qD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!RU(t)||t)}function DU(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&&!RU(i)?i:(e.width&&(i.width={ideal:e.width},t&&!pk&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!pk&&(i.height.max=e.height)),pk&&jk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!RU(i)||i)}var NU=bU;function kU(e){return OU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return nw(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function OU(e){return function(t,i,r){return r.value=e(r.value,i),r}}var MU=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&eM.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{eM.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),PU=0,LU=class{constructor(e){rw(this,"log"),rw(this,"isRunning",!1),rw(this,"queue",[]);let t="fq".concat(++PU);e&&(t+="|".concat(e)),this.log=eM.createLogger({id:t})}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 o=Qb({},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==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(o.resolve,o.reject):this.queue.push(o),this.log.debug("push ".concat(this.length),e.funcName,e.args),this.isRunning||this.callNext(),n}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length),null==e?void 0:e.funcName,null==e?void 0:e.args),e}callNext(){if(this.isRunning||0===this.length)return;let{fn:e,args:t,context:i,resolve:r,reject:o,funcName:n}=this.queue[0];this.log.debug("callNext",this.length,n,t),this.isRunning=!0,e.apply(i,t).then(r,o).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},xU=new WeakMap,UU=new WeakMap;function VU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let o=r.value;return r.value=function(){let t=xU.get(this)||new LU;for(var r=arguments.length,n=new Array(r),a=0;a<r;a++)n[a]=arguments[a];return xU.set(this,t),t.push({fn:o,args:n,context:this,funcName:i},e)},r}}function FU(e,t){return function(i,r,o){let n=o.value,a=t=>e(...t);return o.value=function(){for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];let s=UU.get(this)||new Map,l=s.get(a(i))||new LU(null==t?void 0:t(...i));return s.set(a(i),l),UU.set(this,s),l.push({fn:n,args:i,context:this,funcName:r})},o}}function BU(e,t){return OU(((i,r)=>function(){let r=e;try{for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let e=i.apply(this,n),s=oN();return $D(e)?e.then((e=>(t?CP.addSuccessEvent({key:r,cost:oN()-s}):CP.addSuccessEvent({key:r}),e))).catch((e=>{throw CP.addFailedEvent({key:r,error:e}),e})):(CP.addSuccessEvent({key:r}),e)}catch(Rw){throw CP.addFailedEvent({key:r,error:Rw}),Rw}}))}var HU={};function WU(){}ew(HU,{Events:()=>rV,Inspect:()=>YU,LastSink:()=>JU,Sink:()=>XU,Subscribe:()=>QU,TimeoutError:()=>oV,audit:()=>uF,bindCallback:()=>BV,bindNodeCallback:()=>HV,buffer:()=>gV,bufferCount:()=>_V,bufferTime:()=>YF,call:()=>GU,catchError:()=>XF,combineLatest:()=>hV,concat:()=>cV,concatMap:()=>xF,concatMapTo:()=>UF,count:()=>qV,create:()=>ZU,debounce:()=>mF,debounceTime:()=>fF,defer:()=>yV,delay:()=>JF,deliver:()=>eV,dispose:()=>zU,elementAt:()=>_F,empty:()=>jV,every:()=>TF,exhaustMap:()=>jF,exhaustMapTo:()=>zF,expand:()=>$F,filter:()=>QV,find:()=>gF,findIndex:()=>EF,first:()=>vF,fromAnimationFrame:()=>VV,fromArray:()=>wV,fromEvent:()=>OV,fromEventPattern:()=>kV,fromFetch:()=>PV,fromIterable:()=>LV,fromPromise:()=>MV,fromReadableStream:()=>UV,fromReader:()=>xV,groupBy:()=>KF,identity:()=>jU,ignoreElements:()=>$V,iif:()=>uV,inspect:()=>KU,interval:()=>CV,last:()=>yF,map:()=>RF,mapTo:()=>bF,max:()=>YV,merge:()=>sV,mergeMap:()=>BF,mergeMapTo:()=>HF,min:()=>JV,never:()=>WV,nothing:()=>WU,of:()=>bV,pairwise:()=>AF,pipe:()=>$U,race:()=>lV,range:()=>FV,reduce:()=>KV,retry:()=>oB,scan:()=>IF,setAsapScheduler:()=>SV,share:()=>aV,shareReplay:()=>dV,skip:()=>rF,skipUntil:()=>oF,skipWhile:()=>nF,startWith:()=>mV,subject:()=>vV,subscribe:()=>tB,sum:()=>XV,switchMap:()=>kF,switchMapTo:()=>MF,take:()=>ZV,takeLast:()=>iF,takeUntil:()=>eF,takeWhile:()=>tF,tap:()=>iB,throttle:()=>cF,throwError:()=>GV,timeInterval:()=>qF,timeout:()=>rB,timer:()=>DV,toPromise:()=>ZF,toReadableStream:()=>eB,withLatestFrom:()=>fV,zip:()=>pV});var GU=e=>e(),jU=e=>e;function zU(){this.dispose()}var KU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,qU=1,YU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new iV(e,this,this.streamId++);return rV.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},JU=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=WU,this.error=WU,this.next=WU,this.dispose=WU,this.subscribe=WU,this.doDefer()}subscribe(e){return e instanceof YU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(GU),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}},XU=class extends JU{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)}},QU=class extends JU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:WU,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:WU;if(super(),this._next=t,this._error=i,this._complete=r,this.then=WU,e instanceof YU){let o={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{rV.defer(o,0)})),rV.create(o),rV.pipe(o),this.sourceId=o.id,this.subscribe(e),rV.subscribe({id:o.id,end:!0}),t==WU?this._next=e=>rV.next(o,0,e):this.next=e=>{rV.next(o,0,e),t(e)},r==WU?this._complete=()=>rV.complete(o,0):this.complete=()=>{this.dispose(),rV.complete(o,0),r()},i==WU?this._error=e=>rV.complete(o,0,e):this.error=e=>{this.dispose(),rV.complete(o,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 $U(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 ZU(e,t,i){if(KU()){let r=Object.defineProperties(Object.setPrototypeOf(e,YU.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}});rV.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof YU&&rV.addSource(r,t)}return r}return e}function eV(e,t){return function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return i=>{if(i instanceof YU){let o=ZU((t=>{let n=new e(t,...r);n.sourceId=o.id,n.subscribe(i)}),t,arguments);return o.source=i,rV.pipe(o),o}return t=>i(new e(t,...r))}}}function tV(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var iV=class extends XU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{rV.defer(this.source,this.id)}))}next(e){rV.next(this.source,this.id,e),this.sink.next(e)}complete(){rV.complete(this.source,this.id),this.sink.complete()}error(e){rV.complete(this.source,this.id,e),this.sink.error(e)}},rV={addSource(e,t){tV("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){tV("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;tV("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){tV("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){tV("defer",{id:e.id,streamId:t})},pipe(e){tV("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){tV("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=qU++),tV("create",{name:e.toString(),id:e.id})}},oV=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},nV=class extends JU{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 aV(){return e=>{let t=new nV(e);if(e instanceof YU){let i=ZU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,rV.pipe(i),i}return ZU(t.add.bind(t),"share",arguments)}}function sV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=new XU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function lV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=new Map;t.forEach((t=>{let r=new XU(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 cV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=0,r=t.length,o=new XU(e);o.complete=()=>{i<r&&!o.disposed?(o.doDefer(),o.subscribe(t[i++])):e.complete()},o.complete()}),"concat",arguments)}function dV(e){return t=>{let i=new nV(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},ZU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function uV(e,t,i){return ZU((r=>e()?t(r):i(r)),"iif",arguments)}function hV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=t.length,r=i,o=i,n=new Array(i),a=()=>{0==--o&&e.complete()};t.forEach(((t,i)=>{let o=new XU(e);o.next=t=>{r--,o.next=t=>{n[i]=t,0===r&&e.next(n)},o.next(t)},o.complete=a,o.subscribe(t)}))}),"combineLatest",arguments)}function pV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=t.length,r=i,o=new Array(i),n=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new XU(e),a=[];o[i]=a,r.next=t=>{a.push(t),o.every((e=>e.length))&&e.next(o.map((e=>e.shift())))},r.complete=n,r.subscribe(t)}))}),"zip",arguments)}function mV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>ZU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<o&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}var fV=eV(class extends XU{constructor(e){super(e);let t=new XU(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];t.next=e=>this.buffer=e,t.complete=WU,t.subscribe(hV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),_V=eV(class extends XU{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"),gV=eV(class extends XU{constructor(e,t){super(e),this.buffer=[];let i=new XU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=WU,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),EV=function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())}))};function vV(e){let t=arguments,i=aV()(ZU((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=WU,i.complete=WU,i.error=WU,i}function yV(e){return ZU((t=>t.subscribe(e())),"defer",arguments)}var TV={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},IV="undefined"!=typeof Promise?TV.promise:TV.setImmediate?TV.setImmediate:TV.setTimeout,AV=e=>t=>{IV((()=>e(t)))},SV=e=>{"function"==typeof e?IV=e:TV[e]&&(IV=TV[e])},RV=e=>AV((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function bV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU(RV(t),"of",arguments)}function wV(e){return ZU(RV(e),"fromArray",arguments)}function CV(e){return ZU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function DV(e,t){return ZU((i=>{let r=0,o=setTimeout((()=>{if(i.removeDefer(n),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),n=()=>clearTimeout(o);i.defer(n)}),"timer",arguments)}function NV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function kV(e,t){return ZU(NV(e,t),"fromEventPattern",arguments)}function OV(e,t){if("on"in e&&"off"in e)return ZU(NV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return ZU(NV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return ZU(NV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function MV(e){return ZU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function PV(e,t){return ZU(yV((()=>MV(fetch(e,t)))),"fromFetch",arguments)}function LV(e){return ZU(AV((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(Sw){t.error(Sw)}})),"fromIterable",arguments)}function xV(e){let t=i=>EV(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:o}=yield e.read();r?i.complete():(i.next(o),t(i))}));return ZU((e=>{t(e)}),"fromReader",arguments)}function UV(e){return ZU((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 VV(){return ZU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function FV(e,t){return ZU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<o&&!i.disposed;)i.next(r++);return i.complete(),"range"}),"range",arguments)}function BV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return ZU((i=>{let o=r.concat((e=>(i.next(e),i.complete())));e.apply(t,o)}),"bindCallback",arguments)}function HV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return ZU((i=>{let o=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,o)}),"bindNodeCallback",arguments)}function WV(){return ZU((()=>{}),"never",arguments)}function GV(e){return ZU((t=>t.error(e)),"throwError",arguments)}function jV(){return ZU((e=>e.complete()),"empty",arguments)}var zV=class extends XU{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)}},KV=eV(zV,"reduce"),qV=e=>eV(zV,"count")(((t,i)=>e(i)?t+1:t),0),YV=()=>eV(zV,"max")(Math.max),JV=()=>eV(zV,"min")(Math.min),XV=()=>eV(zV,"sum")(((e,t)=>e+t),0),QV=eV(class extends XU{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"),$V=eV(class extends XU{next(e){}},"ignoreElements"),ZV=eV(class extends XU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&(this.doDefer(),this.complete())}},"take"),eF=eV(class extends XU{constructor(e,t){super(e);let i=new XU(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=zU,i.subscribe(t)}},"takeUntil"),tF=eV(class extends XU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),iF=e=>KV(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),rF=eV(class extends XU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),oF=eV(class extends XU{constructor(e,t){super(e),e.next=WU;let i=new XU(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=zU,i.subscribe(t)}},"skipUntil"),nF=eV(class extends XU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),aF={leading:!0,trailing:!1},sF=class extends XU{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)}},lF=class extends XU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:aF;super(e),this.durationSelector=t,this.config=i,this._throttle=new sF(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=WU,this._throttle.complete(),super.complete()}},cF=eV(lF,"throttle"),dF={leading:!1,trailing:!0},uF=e=>eV(lF,"audit")(e,dF),hF=class extends XU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},pF=class extends XU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new hF(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()}},mF=eV(pF,"debounce"),fF=e=>eV(pF,"debounceTime")((t=>DV(e))),_F=eV(class extends XU{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"),gF=e=>t=>ZV(1)(nF((t=>!e(t)))(t)),EF=eV(class extends XU{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"),vF=eV(class extends XU{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"),yF=eV(class extends XU{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"),TF=eV(class extends XU{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"),IF=eV(class extends XU{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"),AF=eV(class extends XU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),SF=class extends XU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},RF=eV(SF,"map"),bF=e=>eV(SF,"mapTo")((t=>e)),wF=class extends XU{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()}},CF=class e extends XU{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()}},DF=class extends wF{},NF=class extends CF{next(e){this.subInner(e,DF),this.next=e=>{this.currentSink.dispose(),this.subInner(e,DF)}}},kF=eV(NF,"switchMap");function OF(e){return(t,i)=>e((()=>t),i)}var MF=OF(eV(NF,"switchMapTo")),PF=class extends wF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},LF=class extends CF{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(),PF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},xF=eV(LF,"concatMap"),UF=OF(eV(LF,"concatMapTo")),VF=class extends wF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},FF=class extends CF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,VF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},BF=eV(FF,"mergeMap"),HF=OF(eV(FF,"mergeMapTo")),WF=class extends wF{dispose(){this.context.resetNext(),super.dispose()}},GF=class extends CF{next(e){this.next=WU,this.subInner(e,WF)}},jF=eV(GF,"exhaustMap"),zF=OF(eV(GF,"exhaustMapTo")),KF=eV(class extends XU{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=vV(),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"),qF=eV(class extends XU{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"),YF=eV(class extends XU{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"),JF=eV(class extends XU{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"),XF=eV(class extends XU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),QF=class extends wF{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},$F=eV(class extends CF{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 QF(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"),ZF=()=>e=>new Promise(((t,i)=>{let r;new QU(e,(e=>r=e),i,(()=>t(r)))})),eB=()=>e=>{let t;return new ReadableStream({start(i){t=new QU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},tB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:WU,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:WU;return r=>new QU(r,e,t,i)},iB=eV(class extends XU{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"),rB=eV(class extends XU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new oV(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),oB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof YU){let i=ZU((r=>{let o=e,n=new XU(r);n.error=e=>{o-- >0?n.subscribe(t):r.error(e)},n.sourceId=i.id,n.subscribe(t)}),"retry",[e]);return i.source=t,rV.pipe(i),i}return i=>{let r=e,o=new XU(i);o.error=e=>{r-- >0?t(o):i.error(e)},t(o)}}},nB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(nB||{}),aB=class e extends AU{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.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(eC.MUTE,this.onTrackMuted),e.addEventListener(eC.UNMUTE,this.onTrackUnmuted),e.addEventListener(eC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===eC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(eC.MUTE,this.onTrackMuted),e.removeEventListener(eC.UNMUTE,this.onTrackUnmuted),e.removeEventListener(eC.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(this,null,(function*(){var i;let r=this.sourceTrack;try{let r,o=oN();JO.emit(QO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(t||null==(i=this.sourceTrack)||i.stop(),r=yield NU(e));let n=r.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),JO.emit(QO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:oN()-o}),r}catch(Rw){throw JO.emit(QO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Rw}),this.log.error("getUserMedia error observed ".concat(Rw)),Rw}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=cN((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 nw(this,null,(function*(){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.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)}))}_checkPublishFlag(e){return new Promise(((t,i)=>nw(this,null,(function*(){var r,o,n,a;let s=()=>i(new mw({code:hw.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===zL.INIT||"ready"===this.state)&&s(),$U(OV(e,"local-publish-flag-changed"),QV((()=>this.hasFlag)),eF(sV(OV(this,zL.INIT),OV(this,"ready"))),tB(t,i,s))),((null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.uplinkNetworkQuality)||0)>3)return t();let l=e.heartbeatCount,c=(null==(a=null==(n=this.mediaTrack)?void 0:n.stats)?void 0:a.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout((()=>nw(this,null,(function*(){var r,o,n,a,s,d,u;if(((null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.uplinkNetworkQuality)||0)>3||e.heartbeatCount-l<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(null!=(n=this.mediaTrack)&&n.stats){let e=this.mediaTrack.stats.totalFrames||0;e-c==0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",e)}let e=this.kind===eC.AUDIO,r=this.stat.bytesSent>0;if(CP[r?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(s=null==(a=this.room)?void 0:a.videoCodec)?void 0:s.toUpperCase())||"H264"];e&&CP[r?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!r){if(CP.addEnum({key:e?503701:513703,value:GO()}),rx.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(FO()||zO()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(u=null==(d=this.room)?void 0:d.videoCodec)?void 0:u.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield SN(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),i(new mw({message:"".concat(this.strMediaType," encode failed"),code:e?hw.AUDIO_ENCODE_FAILED:hw.VIDEO_ENCODE_FAILED}))}}}))),1e4)}))))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),JO.emit(QO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return nw(this,null,(function*(){if(this.sourceTrack&&pL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return nw(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:o,kind:n}=e;return function*(){return t===i&&(n!==eC.AUDIO||t!==qC||(yield gU(r,o)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),uU().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===eC.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(eC.AUDIO_INPUT);return!!_U.has(i)}(this.sourceTrack)||this.kind===eC.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(eC.VIDEO_INPUT);return!!_U.has(i)}(this.sourceTrack)||this._isRecapturing||e&&jk&&EO)}onTrackMuted(){if(super.onTrackMuted(),MU(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ZC)return void setTimeout((()=>this.onTrackMuted()),ZC);this._onMuteTimeoutId=setTimeout((()=>nw(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((sk||ck)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return nw(this,null,(function*(){if(ow(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<ZC)return void setTimeout((()=>this.onTrackEnded()),ZC);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(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 o={useExactDeviceId:!0};if("user"===e||"environment"===e)o.facingMode=e;else{let t;("audio"===this.kind?yield hU():yield pU()).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}),JO.emit(QO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),JO.emit(QO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})})).finally((()=>{t&&(null==r||r.stop())}))}))}getRecoverCaptureDeviceId(){return nw(this,null,(function*(){let e=this instanceof fB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(lB.get(t)||0)+1;if(lB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield pU()).find((e=>!lB.has(e.deviceId))):(yield hU()).find((e=>!lB.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)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};iw([WL(zL.INIT,"ready",{ignoreError:!0,sync:!0})],aB.prototype,"setStateToReady",1),iw([VU()],aB.prototype,"capture",1),iw([WL("ready","publish",{ignoreError:!0,success(){JO.emit(QO.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var t;null==(t=this.room)||t.localTracks.delete(this);let i="error",r=e instanceof mw?e:e.cause instanceof mw?e.cause:e,o=!1;r instanceof mw&&(r.message.includes("timeout")?i="timeout":r.code===hw.API_CALL_ABORTED&&(o=!0,i="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:r}),this.log[o?"info":"error"]("publish failed",r)}}),BU(521714,!1)],aB.prototype,"publish",1),iw([OU((e=>function(){return nw(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)}))})),WL([],"ready",{sync:!0})],aB.prototype,"unpublish",1);var sB=aB,lB=new Map;JO.on(QO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&lB.delete(e.track.deviceId)}));var cB=class e extends sB{constructor(e){super(1,TU),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 Yx),rw(this,"_output",new Yx),rw(this,"codecPipeline",[]),rw(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),rw(this,"mixedAudioReferenceMap",new Map),rw(this,"isAudioContextLongSuspended",!1),rw(this,"after3aSilenceStartTime",0),this.manager=e,this.pipeline=new Qx(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),JO.on(QO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return oU.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.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){jD(e)||(0!==e||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=oN())}setInputMediaStreamTrack(t){return nw(this,null,(function*(){let i=this.trackSettings||{};CP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),CP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),CP.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:o}))),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(t),yield ow(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(t){return nw(this,arguments,(function(t){var i=this;let{deviceId:r,customSource:o,useExactDeviceId:n=!0,retryWhenExactFailed:a}=t,s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield ow(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:n,retryWhenExactFailed:a,customSource:o},s);return Kx(),t}()}))}switchDevice(e){return nw(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==qC)return;if(yield gU(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}),JO.emit(QO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(CC){throw this.log.error("switch microphone failed ".concat(CC)),this.deviceId&&this.recapture(this.deviceId),CC}}}))}listenDeviceChange(){cU&&!cU.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&cU.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return nw(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(nB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield hU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&cU.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(cU.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return nw(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:o}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let n=e.getConstraints(),a=!1;!jD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,n.echoCancellation=i,a=!0),!jD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,n.noiseSuppression=r,a=!0),!jD(o)&&o!==t.profile.autoGainControl&&(t.profile.autoGainControl=o,n.autoGainControl=o,a=!0),a&&(pk||EO?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&&CP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),sk&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(qx().createGain()),this._output.setNode(qx().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!EO&&!sk)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;fO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(CP.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=eU(e);if(!i)return;let r=new Yx,o=qx().createGain();o.gain.value=1;let n=new Yx;r.pipeTo(n).pipeTo(this.pipeline.mixNode),r.setNode(i),n.setNode(o),this.mixedAudioReferenceMap.set(t,[r,n])}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(),cU.off("audioInputAdded",this.handleMicrophoneAdded,this),cU.off("audioInputRemoved",this.handleMicrophoneRemoved,this),JO.off(QO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(this,null,(function*(){try{yield ow(e.prototype,this,"recapture").call(this,t,i)}catch(cM){let r=(yield hU()).find((e=>e.deviceId!==t));if(!r)throw cM;yield ow(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,ntp:_w()}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}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(vO?"":", 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)}};function dB(e,t){return t+4<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&0===e.getUint8(t+2)&&1===e.getUint8(t+3)?4:t+3<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&1===e.getUint8(t+2)?3:0}function uB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=new DataView(e),r=[],o=0;for(;o<i.byteLength;){let e=dB(i,o);if(0===e){o+=1;continue}let n=-1;for(let t=o+e;t<i.byteLength;t+=1)if(dB(i,t)>0){n=t;break}let a=-1===n?i.byteLength:n,s=a-o,l=new ArrayBuffer(s),c=new DataView(l);for(let t=0;t<s;t+=1)c.setUint8(t,i.getUint8(o+t));r.push(new hB(c,t)),o=a}return r}var hB=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{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-2,i=[],r=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===r&&(i.push(3),r=0),0===e?r+=1:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}removePreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-1,i=[],r=0;for(let n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:r++,i.push(this.dataView.getInt8(n));break;case 3:2!==r&&i.push(this.dataView.getInt8(n)),r=0;break;default:i.push(this.dataView.getInt8(n)),r=0}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e+=1,255===this.dataView.getUint8(t));t+=1);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+=1){let i=this.dataView.getUint8(n);if(t+=1,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i),o=t;for(let n=0;n<i.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(o+n));return r}get naluType(){let e=this.getStartCodeLength();return e>=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&0===this.dataView.getUint8(2)&&1===this.dataView.getUint8(3)?4:this.dataView.byteLength>=3&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&1===this.dataView.getUint8(2)?3:0}get isIDR(){return 5===this.naluType}get isSPS(){return 7===this.naluType}get isPPS(){return 8===this.naluType}get isSEI(){return 6===this.naluType}},pB=class{constructor(){rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)o.push(255);o.push(r);let n=new DataView(e);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hB(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,i=0,r=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(r.getUint8(o)){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)),o=r.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(o+e.data.byteLength),a=new DataView(n),s=new DataView(e.data),l=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)a.setInt8(l++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)a.setInt8(l++,s.getInt8(i));return e.data=n,r.length}return 0}},mB=class e extends sB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Ox),rw(this,"profile",Qb({},Qw)),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 pB),this.manager=e;let t=()=>{var e;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1});else{let t=AD((null==(e=this.room)?void 0:e.sdkAppId)||0)?Vw:Uw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(t)),this.setProfile($b(Qb({},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(pL&&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 nw(this,null,(function*(){var i,r,o;if(zD(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,fillVideo:!0}),this.muteImage=t,ow(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(o=this.manager)?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),ow(e.prototype,this,"setMute").call(this,t)}))}capture(t){return nw(this,arguments,(function(t){var i=this;let{deviceId:r,facingMode:o,useExactDeviceId:n=!0,customSource:a,retryWhenExactFailed:s=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:o||i.facingMode,cameraId:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:s,customSource:a};if("environment"===t.facingMode){let e=yield i.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return ow(e.prototype,i,"capture").call(i,t)}()}))}setProfile(e){var t;let i=this.fallbackProfile(e);if(i.bitrate&&(this.isNeedToSetBandwidth=i.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(i);else{let e=AD((null==(t=this.room)?void 0:t.sdkAppId)||0)?Vw:Uw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(e)),super.setProfile($b(Qb({},this.profile),{width:1920,height:1080}))}}applyProfile(){return nw(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(16===RO&&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 n&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:eC.VIDEO,videoType:eC.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return pL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:CN(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 nw(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),JO.emit(QO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(CC){throw this.log.error("switch camera failed ".concat(CC)),this.deviceId&&this.recapture(this.deviceId),CC}}))}getDeviceIdWhenUsingBackCamera(){return nw(this,null,(function*(){let e;try{if(Zk&&!lO&&fL){let t=(yield pU(!0)).map((e=>{var t;return $b(Qb({},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,o,n;let{capabilities:a}=e;(null!=(t=a.width)&&t.max&&null!=(r=a.height)&&r.max?a.width.max*a.height.max:0)>(null!=(o=i.capabilities.width)&&o.max&&null!=(n=i.capabilities.height)&&n.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(CC){this._log.warn("get max res camera failed",CC)}return e}))}updateSmallConfig(e){return nw(this,null,(function*(){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),yield null==(t=this.manager)?void 0:t.update(),r&&(yield null==(i=this.room)?void 0: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=Qb({},e);return e.width*e.height<=19200&&ck&&hO&&(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&&CO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),AO(IO,"14.3")&&SO(IO,"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&&(hO||pk)&&!LO()&&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(){cU&&!cU.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&cU.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return nw(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(nB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield pU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&cU.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return nw(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(cU.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 jD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){cU.off("videoInputAdded",this.handleCameraAdded,this),cU.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return nw(this,null,(function*(){try{yield ow(e.prototype,this,"recapture").call(this,t)}catch(CC){let r=(yield pU()).find((e=>e.deviceId!==t));if(!r)throw CC;yield ow(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||jD(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};iw([kU((function(e){this.setContentHint(e.contentHint||"motion")}))],mB.prototype,"capture",1);var fB=mB,_B={};ew(_B,{REPORT_TYPE:()=>ON,buildSSOPackage:()=>MN,bytes2ms:()=>MD,calculateScaleResolutionDownNumber:()=>CN,concatArrayBuffers:()=>PN,convertObjectNumberToInt:()=>AN,copyProperties:()=>OD,deepClone:()=>pN,deepCloneBasic:()=>kN,deepMerge:()=>hN,delay:()=>SN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>fN,getEnv:()=>ID,getFirst16Bits:()=>xN,getInternalVersion:()=>aN,getLast16Bits:()=>LN,getLoggerUrl:()=>SD,getMediaStreamTrackInfo:()=>wN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>bD,getNumNetworkType:()=>kD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>vN,getTurnServer:()=>dN,getUint32Version:()=>IN,getValueType:()=>WD,getViewListFromView:()=>mN,glog:()=>UD,ipv4ToUint32:()=>uN,isArray:()=>JD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>ZD,isEmpty:()=>lN,isFunction:()=>GD,isLangChinese:()=>VD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>yN,isPromise:()=>$D,isRemoteTrack:()=>QD,isRotate90Or270:()=>DN,isSetSinkIdSupported:()=>iN,isString:()=>zD,isUndefined:()=>jD,loadImage:()=>TN,loadVideo:()=>NN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>bN,performanceNow:()=>oN,promiseAny:()=>rN,samples2ms:()=>PD,setNetworkTypeFromWebRTC:()=>ND,stringify:()=>gN,stringifyIncludeValue:()=>EN,throttlePromise:()=>RN});var gB=[-1,-1,1,-1,-1,1,1,1],EB=[0,0,1,0,0,1,1,1],vB=class e extends zL{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 xB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==RO?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(EB),this.positionBuffer=this.createBuffer(gB),!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(cM){this.context.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(cM.message||cM)}))}}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 LB&&this.render(e)||this.context instanceof xB&&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 LB){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,o,n,a,s,l,c){let d=!(jD(a)||jD(s)||jD(l)||jD(c));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,a,s,l,c):this.ctx2d.putImageData(t,i,r),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,a,s,l,c,i,r,o,n):this.ctx2d.drawImage(t,i,r,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:i,y:r,width:o,height:n,name:a,cost:s}=this,l=Date.now(),c=(t-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:o,height:n,timestamp:l,fps:c,name:a,cost:s},Qb({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}};rw(vB,"RENDER","render"),iw([WL(zL.INIT,"connected",{sync:!0})],vB.prototype,"connect",1),iw([WL("connected",zL.INIT,{ignoreError:!0,sync:!0})],vB.prototype,"disconnect",1),iw([WL([],"closed",{sync:!0})],vB.prototype,"close",1);var yB=vB,TB=$U(CV(250),RF((()=>performance.now())),aV()),IB=e=>t=>{let i=performance.now();$U(TB,nF((t=>t-i<e)),ZV(1))(t)},AB=[0,1,1,1,0,0,1,0],SB=class extends yB{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 xB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(AB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),QL.clearTask(this._intervalId),this._intervalId=QL.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(QL.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof LB){let e=this.context.ctx.getError();e&&this.context.destroy(new mw({code:hw.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(yB.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&&(QL.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),QL.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),QL.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},RB=class extends SB{constructor(e,t){super(e,t),rw(this,"_videoTrack"),rw(this,"_muteOb"),rw(this,"_closedOb",OV(this,"closed")),rw(this,"_subscription"),rw(this,"_canvasContainer"),Number(yO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=OV(this._videoTrack,"mute"),$U(OV(this._videoTrack,"ended"),eF(this._closedOb),tB((()=>{this.context.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=$U(this._muteOb,eF(this._closedOb),MF(IB(5e3)),QV((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),tB((()=>{this.context.destroy(new mw({code:hw.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()}},bB=class extends RB{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),this.emit(yB.RENDER,this.context._canvas2d)}else this.emit(yB.RENDER,this.context._canvas);return i}},wB=class extends RB{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=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," ")),r>o?i=r/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)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},CB=class extends yB{constructor(e,t){super(e,Qb({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===RO&&(this._canvasRendered=vV(),$U(this._canvasRendered,mV(this._image),kF((e=>e instanceof HTMLCanvasElement?OV(e,"rendered"):jV())),eF(OV(this,"closed")),tB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),CL()&&!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:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:o}=n),!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:r,height:o}=n),n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?(({width:r,height:o}=n),this._lastImage=n):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame&&(({displayWidth:r,displayHeight:o}=n),null==(i=this._lastImage)||i.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&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(r,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)}},DB=class extends CB{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",$U(OV(this._player,$L.PLAYER_STATE_CHANGED),eF(OV(this,"closed")),QV((e=>{let{state:t}=e;return"PLAYING"===t})),tB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},NB=class extends DB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new Ox({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()}},kB=class extends yB{constructor(e,t,i){super(e,$b(Qb({name:"textSource"},i),{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: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 o=this.font.match(/(\d+)px/),n=(o?parseInt(o[1],10):16)*i,a=this.content.split("\n");for(let s=0;s<a.length;s++)this.ctx2d.fillText(a[s],e,t+s*n)}},OB=class extends zL{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 NB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new RB(this,e)}createVideoImageSource(e,t){return new CB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new DB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new kB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};rw(OB,"_ids",0);var MB={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},PB=class extends OB{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(OB._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",MB),!this.ctx)throw new mw({code:hw.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 mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,CP.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}};rw(PB,"UNAVAILABLE","unavailable"),iw([WL(zL.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),CP.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),CP.addSuccessEvent({key:512700})}})],PB.prototype,"create",1),iw([WL("created",zL.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(PB.UNAVAILABLE,e),this.removeAllListeners()}})],PB.prototype,"destroy",1);var LB=PB,xB=class extends OB{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(OB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new mw({code:hw.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,CP.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(),CP.addSuccessEvent({key:512703})}};function UB(e,t,i,r,o){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let n={sWidth:e,sHeight:t,dWidth:i,dHeight:r,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(i/e,r/t);n.dWidth=e*o,n.dHeight=t*o,n.dx=(i-n.dWidth)/2,n.dy=(r-n.dHeight)/2;break}case"cover":{let o=Math.max(i/e,r/t),a=i/o,s=r/o;n.sx=(e-a)/2,n.sy=(t-s)/2,n.sWidth=a,n.sHeight=s;break}}return n}iw([WL(zL.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),CP.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),CP.addSuccessEvent({key:512701})}})],xB.prototype,"create",1),iw([WL("created",zL.INIT,{ignoreError:!0,sync:!0})],xB.prototype,"destroy",1);var VB=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}},FB=class extends yB{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 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 o=new VB(e,t);this.inputs.splice(i,0,o)}changeInputLayout(e,t){let i=this.inputs.findIndex((t=>t.node===e));if(i<0)return;let{x:r,y:o,width:n,height:a,zIndex:s,fillMode:l,rotation:c,hidden:d}=t;if(!jD(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[i];jD(r)||(u.layout.x=r),jD(o)||(u.layout.y=o),jD(n)||(u.layout.width=n),jD(a)||(u.layout.height=a),jD(c)||(u.layout.rotation=c),jD(d)||(u.layout.hidden=d),l&&(u.layout.fillMode=l),!jD(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 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 LB&&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=UB(t.node.width,t.node.height,t.width,t.height,t.fillMode,DN(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 o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(o&&([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: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:i,width:r,height:o,timestamp:a,fps:s,name:n},Qb({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 LB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(cM){}}))}close(){super.close(),this.removeAllInputs()}},BB=[1,0,0,0,1,1,0,1],HB=class extends yB{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),rw(this,"mirror",!1),rw(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof LB)try{this.setTexBuffer(BB)}catch(Rw){e.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Rw.message||Rw)}))}}draw2d(e,t,i,r,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(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(o/r,r/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/r,r/o));let n=super.draw2d(e,t,i,r,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){DN(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},WB=class extends sB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Ox),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(yB.RENDER,(e=>{this.emit("render",e)})),this.mixNode=new FB(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=QL.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new xB({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,i=0,r=!0;for(let[o,n]of this.inputLocalVideoTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.cameraNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o}for(let[o,n]of this.inputLocalScreenTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.screenNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o,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 nw(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),vO&&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:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tx(this,cU).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===RO&&o instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(o,"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 o=this.videoContext.createVideoTrackSource(r,"screenNodeSource");o.resize(t.settings.width,t.settings.height),o.shouldUpdate=!1,this._connectMix(o,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,o),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,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:i,font:r,color:o});a.resize(n.width,n.height),this._connectMix(a,n),this.textNodeMap.set(t,a)}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,o=this.cameraNodeMap.get(e);if(o){if(i){if(16===RO&&i instanceof CanvasCaptureMediaStreamTrack)if(o instanceof NB){let t=o.output;o.close(),o=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),o.connect(t),this.cameraNodeMap.set(e,o)}else o.image=i.canvas;else if(o instanceof NB)o.replaceTrack(i);else{let t=o.output;o.close(),o=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),o.connect(t),this.cameraNodeMap.set(e,o)}let{width:t,height:r}=i.getSettings();t&&r&&o.resize(t,r)}r&&o.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(o,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:o,layout:n}=e,a=this.textNodeMap.get(t);a&&(jD(i)||(a.content=i),jD(r)||(a.font=r),jD(o)||(a.color=o),a.resize(n.width,n.height),this._changeMixLayout(a,n))}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:o}=t;e.disconnect();let n=new HB(this.videoContext,this.log,r,o);n=e.connect(n),t.fillMode||(t.fillMode=i),n.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,o=e.output||e;o instanceof HB&&(jD(i)||(o.mirror=i),jD(r)||(o.rotation=r),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 i=this.cameraNodeMap.get(e);i&&(i.output instanceof HB&&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 HB&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof HB&&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(),QL.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(),ix(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")}},GB=tM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:GB,exposeOrigin:!0,permittedOrigins:["*"]})}catch(UH){}var jB=function(e){return nw(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:EO?{max:e.width}:{ideal:e.width,max:e.width},height:EO?{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:o=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return t}(e);eM.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(pO&&fO<74||EO||pk)&&eM.warn("Your browser not support capture system audio");let o=r.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(pM){eM.warn("screen applyConstraints failed: ".concat(pM))}e.captureElement&&(yield function(e,t){return nw(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&GD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==GB)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){eM.warn("cropTo target failed ".concat(r))}}))}(o,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 jD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);eM.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},zB=class extends fB{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 GB===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(cM){return}}capture(e){return nw(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:n,audioTrack:a,videoTrack:s,captureElement:l,preferDisplaySurface:c}=e;return function*(){try{let e;return s||a?(e=new MediaStream,s&&e.addTrack(s),a&&e.addTrack(a)):(e=yield jB({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:n,captureElement:l,preferDisplaySurface:c}),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 mw?e:new mw({code:hw.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return nw(this,null,(function*(){throw new Error("Method not implemented.")}))}};iw([kU((function(e){this.setContentHint(e.contentHint||"detail")}))],zB.prototype,"capture",1);var KB,qB=class extends cB{constructor(e){super(e),this._log.id="s-".concat(this._log.id),this.isScreen=!0}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 YB(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 nw(this,null,(function*(){let o=qx();KB||(KB=Mx(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=i,r&&a.port.postMessage({port:r},[r]),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 JB=class extends $x{constructor(e){super(),this.room=e,rw(this,"_localAudioTrack"),rw(this,"_localScreenAudioTrack"),rw(this,"log"),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),this.log=eM.createLogger({parent:null==e?void 0:e.getLogger(),id:"am",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0: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=[],o=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.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),l=()=>{for(let e=0;e<o.length;e++){let t=URL.createObjectURL(new Blob(a[e])),i=document.createElement("a");i.href=t,i.download="".concat(o[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(s),n.abort("download")},c=YB(r).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=>l))));return{then:c.then.bind(c),download:l}}getPCM(e,t){var i,r,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:l}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!n)return;this.log.info("getPCM ".concat(t||"local"));let c,d,u=Math.floor(.04*a),h=new Float32Array(u),p=new Float32Array(u),m=0,f=new AbortController,_=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(o=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:o.remoteAudioTrack.mediaTrack;if(_)return YB([qx().createMediaStreamSource(new MediaStream([_]))],a,s,l).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),c=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):(c&&(h.set(c,m),m+=c.length,c=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: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!jD(this._localScreenAudioTrack)}get hasAudioTrack(){return!jD(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof qB?(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 cB?(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 $B?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 qB?delete this._localScreenAudioTrack:e instanceof cB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var o;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==(o=this._localScreenAudioTrack)||o.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 o=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,o),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(){JO.on("113",this.handleLocalTrackStarted,this),JO.on("114",this.handleLocalTrackStopped,this),JO.on("115",this.handleRemoteTrackStarted,this),JO.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){JO.off("113",this.handleLocalTrackStarted),JO.off("114",this.handleLocalTrackStopped),JO.off("115",this.handleRemoteTrackStarted),JO.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:o}=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||jD(o))return;this.setAudioReferenceVolume(r,o)}}};var XB=class e extends AU{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,rw(this,"tinyId"),rw(this,"isRemote",!0),rw(this,"jitterBufferDelay",0),rw(this,"availableState"),rw(this,"remotePublishState"),rw(this,"_triggerCheckDecodeSubject",vV(OV(this,e.STATE_SUBSCRIBE))),rw(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new zL("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new zL("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),$U(sV(OV(this,zL.STATECHANGED),OV(this.remotePublishState,zL.STATECHANGED)),RF((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),tB((e=>{this.availableState.state!==(e?zL.ON:zL.OFF)&&(this.availableState.state=e?zL.ON:zL.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(e)})));let o=$U(OV(this.player,$L.ERROR),QV((e=>e.code===MediaError.MEDIA_ERR_DECODE))),n=$U(DV(5e3),QV((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===eC.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),a=$U(lV(o,n),eF(OV(this,zL.INIT)));$U(this._triggerCheckDecodeSubject,QV((()=>!this.ignoreDecodeError)),MF(a),tB((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===zL.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var i,r;let o=this.kind===eC.AUDIO;if(CP[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";CP[e?"addSuccessEvent":"addFailedEvent"]({key:RP["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(CP.addEnum({key:o?504701:514703,value:GO()}),rx.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(FO()||zO()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===eC.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),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?zL.ON:zL.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};rw(XB,"STATE_SUBSCRIBE","subscribe"),iw([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 OU(((i,r)=>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 i=new mw({code:hw.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||eM).warn(i),2===t?a(i):1===t&&o()}),1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(s),i.apply(this,n).then(o,a).finally((()=>{clearTimeout(s),this._checkPendingPromiseSet&&s&&this._checkPendingPromiseSet.delete(s)}))}))}))}(5,1)],XB.prototype,"waitHasMediaTrack",1),iw([WL(zL.INIT,XB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),JO.emit(QO.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),BU(521716,!1)],XB.prototype,"subscribe",1),iw([WL(XB.STATE_SUBSCRIBE,zL.INIT,{sync:!0,success(){this.log.info("unsubscribed"),JO.emit(QO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],XB.prototype,"unsubscribe",1);var QB=XB,$B=class extends QB{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 oU.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&&yL().AudioDecoder&&_L)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let o={frame:e,track:this};if(1===i&&this.isAvailable&&"audience"===this.room.role&&(o.onAudioFrameNTPTime=e=>{let{ntp:t,frame:i,hasLeavingTag:r}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:i,hasLeavingTag:r})}),t=r(o),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},ZB=class extends yB{constructor(e,t,i,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,rw(this,"initStat",{alphaStitchingType:1}),rw(this,"end",vV()),rw(this,"minSize",320),rw(this,"maxSize",1280),rw(this,"draggable",!1),rw(this,"startDragX",0),rw(this,"startDragY",0),rw(this,"left",0),rw(this,"top",0),rw(this,"baseWidth",320),rw(this,"baseRatio"),rw(this,"container"),this.initStat=o,this.draggable=i,this.bindDragEvents(),CP.addEnum({key:515700,value:1}),this.draggable&&CP.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=eF(this.end);$U(OV(e,"mousedown"),iB(this.startDrag.bind(this)),kF((()=>$U(OV(window,"mousemove"),eF(OV(window,"mouseup"))))),t,tB(this.doDrag.bind(this))),$U(OV(e,"dblclick"),t,tB(this.resetPosition.bind(this))),$U(OV(e,"wheel"),t,tB(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(e){e.preventDefault(),0===e.button&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),e&&this.baseRatio&&this.draggable&&(e.style.setProperty("width","".concat(this.baseWidth,"px")),e.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),e.style.setProperty("position","fixed"),e.style.setProperty("left","".concat(this.left,"px")),e.style.setProperty("top","".concat(this.top,"px")))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=e.deltaY,i=this.context._canvas;i&&(this.baseWidth||(this.baseWidth=i.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,i,r,o){var n;let{ctx2d:a}=this,s=this.context._canvas;if(!a||!s)return!1;let l=super.draw2d(e,t,i,r,o),c=a.getImageData(0,0,r,o),{data:d}=c,u=!1;if(1===this.initStat.alphaStitchingType){let e=Math.floor(r/2);for(let t=0;t<o;t++)for(let i=0;i<e;i++){let o=4*(t*r+i),n=4*(t*r+(i+e)),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,e,o),s.width=e}else if(2===this.initStat.alphaStitchingType){let e=Math.floor(o/2);for(let t=0;t<e;t++)for(let i=0;i<r;i++){let o=4*(t*r+i),n=4*((t+e)*r+i),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,r,e),s.height=e}return null==(n=this.context.ctx)||n.clearRect(0,0,r,o),l&&u}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};var eH=class extends QB{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,"shouldRenderAlpha",!1),rw(this,"alphaNode"),rw(this,"shouldBeDraggable",!0),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.on("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}isAlphaSei(e){if(this.userId!==e.userId||50!==e.seiPayloadType)return!1;let t=new Uint8Array(e.data);return t.length%3==0&&0===t[0]&&1===t[1]&&t}play(e,t){return null!=t&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat(),JO.emit("156",{track:this,player:this.player})}))}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(this.alphaNode){let e=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===e)return;this.alphaNode.initStat={alphaStitchingType:e};let i=this.player.getElement();if(i){let t=i.videoWidth/i.videoHeight;t&&(this.alphaNode.baseRatio=t*(1===e?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(e))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(e){let t=dP[e];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(e){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new xB({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let i=new SB(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let r=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},o=new ZB(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(o),o.connect(i),this.alphaNode=o}else this.source.connect(i);CL()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),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;!KD(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),JO.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},tH=class extends eH{constructor(e,t){super(e,t,2),rw(this,"mediaType",2),rw(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},iH=new Map;function rH(e,t){let i=$b(Qb({},t),{timestamp:_w()});iH.has(e)?iH.get(e).push(i):iH.set(e,[i])}function oH(e){if(iH.has(e)){let t=iH.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 iH.delete(e),t}return[]}function nH(e,t,i,r){try{if(JD(e))for(let o=0;o<e.length;o++)aH.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else aH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(cM){throw eM.error(cM),cM}}function aH(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;if(jD(i)){if(t.required)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(jD(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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),zD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>ZD(e)?eN(e):zD(e)?e:WD(e)))},fnName:o,value:i},link:{className:n,fnName:o}})})}else if(!jD(t.type)&&WD(i)!==t.type)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),a=zD(i)&&""===i.trim();if(e||a)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}if(t.notLessThanZero&&KD(i)&&i<0)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!jD(t.min)&&KD(i)&&i<t.min)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!jD(t.max)&&KD(i)&&i>t.max)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(zD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(t.values&&!t.values.includes(i))throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});let{properties:a}=t;FD(a)&&YD(i)&&Object.keys(a).forEach((e=>{aH.call(this,{rule:a[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:o,className:n})}));let{arrayItem:s}=t;FD(s)&&JD(i)&&i.forEach(((e,t)=>{aH.call(this,{rule:s,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})})),GD(t.validate)&&t.validate.call(this,i,r,o,n,this)}JO.on(QO.JOIN_SUCCESS,(e=>{let{room:t}=e;rH(t.userId,{eventId:32788})})),JO.on(QO.LEAVE_START,(e=>{let{room:t}=e;rH(t.userId,{eventId:32789})})),JO.on(QO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),rH(t.room.userId,{eventId:e})}})),JO.on(QO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),rH(t.room.userId,{eventId:e})}})),JO.on(QO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===eC.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),JO.on(QO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===eC.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),JO.on(QO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),JO.on(QO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),JO.on(QO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===eC.VIDEO?32780:32781})})),JO.on(QO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===eC.VIDEO?32782:32783})})),JO.on(QO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:o}=e;switch(o){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&rH(i.userId,{eventId:t})})),JO.on(QO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:o,remoteUserId:n}=e,a=!!n;switch(o){case"CONNECTED":t="RECONNECTING"===r?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&rH(i.userId,{eventId:t,remoteUserId:n})})),JO.on(QO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:o,isHWCodec:n,prevImplementation:a,streamType:s}=e,l=n?1:0;a||(l=n?3:2);let c={H264:0,H265:1,VP8:2}[o.toUpperCase()],d={eventId:4004,param1:l,param2:c,streamType:s||2};r&&(d.remoteUserId=r,d.eventId=4005),rH(i,d),CP.addEnum({key:r?514701:513701,value:l}),CP.addEnum({key:r?514700:513700,value:c})})),JO.on(QO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===eC.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),rH(t.userId,e)}})),tw(aw(),1);var sH=Object.create,lH=Object.defineProperty,cH=Object.defineProperties,dH=Object.getOwnPropertyDescriptor,uH=Object.getOwnPropertyDescriptors,hH=Object.getOwnPropertyNames,pH=Object.getOwnPropertySymbols,mH=Object.getPrototypeOf,fH=Object.prototype.hasOwnProperty,_H=Object.prototype.propertyIsEnumerable,gH=(e,t,i)=>t in e?lH(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,EH=(e,t)=>{for(var i in t||(t={}))fH.call(t,i)&&gH(e,i,t[i]);if(pH)for(var i of pH(t))_H.call(t,i)&&gH(e,i,t[i]);return e},vH=(e,t)=>cH(e,uH(t)),yH=(e,t,i)=>(i=null!=e?sH(mH(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of hH(t))fH.call(e,o)||o===i||lH(e,o,{get:()=>t[o],enumerable:!(r=dH(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:lH(i,"default",{value:e,enumerable:!0}),e)),TH=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?dH(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&lH(t,i,n),n},IH=(e,t,i)=>gH(e,"symbol"!=typeof t?t+"":t,i),AH=((e,t)=>function(){return t||(0,e[hH(e)[0]])((t={exports:{}}).exports,t),t.exports})({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,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,i),!0;case 4:return d.fn.call(d.context,t,i,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+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||i&&a.context!==i||s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)}}),SH=yH(AH(),1),RH=Symbol("instance"),bH=Symbol("cacheResult"),wH=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,OH.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},CH=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var DH=new Map;function NH(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=DH.get(r)||[];DH.has(r)||DH.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=MH.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[bH]:Promise.resolve(r[bH]);r.state instanceof wH&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof wH&&r.state.abort(r):"string"==typeof r.state&&e.includes(r.state)||(c=new CH(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new CH(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new wH(u,t,a);OH.call(r,h);let p=e=>{var o;return r[bH]=e,h.aborted||(OH.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[bH])),e},m=e=>(OH.call(r,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):i.sync?p(e):Promise.resolve(p(e))}catch(mM){return m(new CH(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(mM),mM instanceof Error?mM:new Error(String(mM))))}}}}var kH="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 OH(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(MH.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var MH=class e extends SH.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 o=r[RH];o?this.name=o.name+"-"+o.count++:r[RH]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=DH.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);DH.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:n})})):o.push({to:i,action:n})})),r.forEach((e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};kH(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){OH.call(this,e)}};MH.STATECHANGED="stateChanged",MH.UPDATEAFSM="updateAFSM",MH.INIT="[*]",MH.ON="on",MH.OFF="off",MH.instances=new Map,MH.instances2=new WeakMap;var PH=class extends MH{constructor(){super(...arguments),IH(this,"decoder"),IH(this,"config")}initialize(){return nw(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(vH(EH({},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 LH(){var e;self.onmessage=t=>{if("init"===t.data.type){let{canvas:i,wasmScript:r,wasmBinary:o}=t.data,n=null==i?void 0:i.getContext("2d"),a=0,s=0,l={wasmBinary:o,postRun:()=>{e=new l.VideoDecoder({videoInfo(e,t){a=e,s=t,console.log("video info",e,t)},yuvData(e,t){let r=a*s,o=r>>2,c=l.HEAPU32[e>>2],d=l.HEAPU32[1+(e>>2)],u=l.HEAPU32[2+(e>>2)],h=l.HEAPU8.subarray(c,c+r),p=l.HEAPU8.subarray(d,d+o),m=l.HEAPU8.subarray(u,u+o),f=new Uint8Array(r+o+o);f.set(h),f.set(p,r),f.set(m,r+o);let _=new VideoFrame(f,{codedWidth:a,codedHeight:s,format:"I420",timestamp:t});i?(null==n||n.drawImage(_,0,0,i.width,i.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 "+r)()(l)}else if("decode"===t.data.type){let{packet:i}=t.data;null==e||e.decode(i.data,"key"==i.type,i.timestamp)}else if("setCodec"===t.data.type){let{codec:i,format:r,description:o}=t.data;null==e||e.setCodec(i,r,null!=o?o:"")}}}TH([NH([MH.INIT,"closed"],"initialized")],PH.prototype,"initialize",1),TH([NH("initialized","configured",{sync:!0})],PH.prototype,"configure",1),TH([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return(e,i,r)=>{let o=r.value,n=i;r.value=function(){if(!t.includes(this.state.toString()))throw new CH(this.state,"".concat(this.name," ").concat(n," failed: current state ").concat(this.state," not in ").concat(t));for(var e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return o.apply(this,i)}}}("configured")],PH.prototype,"decode",1),TH([NH([],MH.INIT,{sync:!0})],PH.prototype,"reset",1),TH([NH([],"closed",{ignoreError:!0,sync:!0})],PH.prototype,"close",1);var xH=class extends MH{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=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=i,this.canvas=r,this.yuvMode=o,IH(this,"worker"),IH(this,"decoder"),IH(this,"config"),IH(this,"module",{}),IH(this,"width",0),IH(this,"height",0)}initialize(e){return nw(this,null,(function*(){var t;if(this.workerMode){let e=new RegExp("\\{(.+)\\}","s").exec(LH.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"text/javascript"})));let i=null==(t=this.canvas)?void 0:t.transferControlToOffscreen(),r=yield this.wasmBinary;return console.warn("worker mode",r),this.worker.postMessage({type:"init",canvas:i,wasmScript:this.createModule.toString(),wasmBinary:r},i?[i,r]:[r]),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 i=this.module;return this.wasmBinary&&(i.wasmBinary=yield this.wasmBinary),i.print=e=>console.log(e),i.printErr=e=>console.log("[JS] ERROR: ".concat(e)),i.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise((t=>{i.postRun=e=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),t()},e&&Object.assign(i,e),this.createModule(i)}))}))}configure(e){var t,i,r;this.config=e;let o=this.config.codec.startsWith("avc")?"avc":"hevc",n=this.config.description?"avc"==o?"avcc":"hvcc":"annexb";null==(i=this.decoder)||i.setCodec(o,n,null!=(t=this.config.description)?t:""),null==(r=this.worker)||r.postMessage({type:"setCodec",codec:o,format:n,description:this.config.description})}decode(e){var t,i;null==(t=this.decoder)||t.decode(e.data,"key"==e.type,e.timestamp),"configured"===this.state&&(null==(i=this.worker)||i.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 i={width:e,height:t};this.emit("videoCodecInfo",i)}yuvData(e,t){if(!this.module)return;let i=this.width*this.height,r=i>>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+i),l=this.module.HEAPU8.subarray(n,n+r),c=this.module.HEAPU8.subarray(a,a+r);if(this.yuvMode)return void this.emit("videoFrame",{y:s,u:l,v:c,timestamp:t});let d=new Uint8Array(i+r+r);d.set(s),d.set(l,i),d.set(c,i+r),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)}};TH([NH([MH.INIT,"closed"],"initialized")],xH.prototype,"initialize",1),TH([NH("initialized","configured",{sync:!0})],xH.prototype,"configure",1),TH([NH([],MH.INIT,{sync:!0})],xH.prototype,"reset",1),TH([NH([],"closed",{sync:!0})],xH.prototype,"close",1);var UH,VH=(UH="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,i,r=e;r.ready=new Promise(((e,r)=>{t=e,i=r}));var o,n,a,s=Object.assign({},r),l="./this.program",c="object"==typeof window,d="function"==typeof importScripts,u=("object"==typeof process&&"object"==typeof process.versions&&process.versions.node,"");(c||d)&&(d?u=self.location.href:"undefined"!=typeof document&&document.currentScript&&(u=document.currentScript.src),UH&&(u=UH),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,i)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):i()},r.onerror=i,r.send(null)});var h,p,m=r.print||console.log.bind(console),f=r.printErr||console.error.bind(console);Object.assign(r,s),s=null,r.arguments&&r.arguments,r.thisProgram&&(l=r.thisProgram),r.quit&&r.quit,r.wasmBinary&&(h=r.wasmBinary),r.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,P=null;function L(e){M++,r.monitorRunDependencies&&r.monitorRunDependencies(M)}function x(e){if(M--,r.monitorRunDependencies&&r.monitorRunDependencies(M),0==M&&P){var t=P;P=null,t()}}function U(e){r.onAbort&&r.onAbort(e),f(e="Aborted("+e+")"),D=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(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,i){return(r=e,h||!c&&!d||"function"!=typeof fetch?Promise.resolve().then((()=>F(r))):fetch(r,{credentials:"same-origin"}).then((e=>{if(!e.ok)throw"failed to load wasm binary file at '"+r+"'";return e.arrayBuffer()})).catch((()=>F(r)))).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(i,(e=>{f("failed to asynchronously prepare wasm: "+e),U(e)}));var r}V(R="videodec.wasm")||(b=R,R=r.locateFile?r.locateFile(b,u):u+b);var H=e=>{for(;e.length>0;)e.shift()(r)};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 G={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var i=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),i++):i&&(e.splice(r,1),i--)}if(t)for(;i;i--)e.unshift("..");return e},normalize:e=>{var t=G.isAbs(e),i="/"===e.substr(-1);return(e=G.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&i&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=G.splitPath(e),i=t[0],r=t[1];return i||r?(r&&(r=r.substr(0,r.length-1)),i+r):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=G.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return G.normalize(e.join("/"))},join2:(e,t)=>G.normalize(e+"/"+t)},j=e=>(j=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);U("initRandomDevice")})())(e),z={resolve:function(){for(var e="",t=!1,i=arguments.length-1;i>=-1&&!t;i--){var r=i>=0?arguments[i]:re.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");if(!r)return"";e=r+"/"+e,t=G.isAbs(r)}return(t?"/":"")+(e=G.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function i(e){for(var t=0;t<e.length&&""===e[t];t++);for(var i=e.length-1;i>=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=z.resolve(e).substr(1),t=z.resolve(t).substr(1);for(var r=i(e.split("/")),o=i(t.split("/")),n=Math.min(r.length,o.length),a=n,s=0;s<n;s++)if(r[s]!==o[s]){a=s;break}var l=[];for(s=a;s<r.length;s++)l.push("..");return(l=l.concat(o.slice(a))).join("/")}},K="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,q=(e,t,i)=>{for(var r=t+i,o=t;e[o]&&!(o>=r);)++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 l=63&e[t++];if((a=224==(240&a)?(15&a)<<12|s<<6|l:(7&a)<<18|s<<12|l<<6|63&e[t++])<65536)n+=String.fromCharCode(a);else{var c=a-65536;n+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else n+=String.fromCharCode((31&a)<<6|s)}else n+=String.fromCharCode(a)}return n},Y=[],J=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++i):t+=3}return t},X=(e,t,i,r)=>{if(!(r>0))return 0;for(var o=i,n=i+r-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(i>=n)break;t[i++]=s}else if(s<=2047){if(i+1>=n)break;t[i++]=192|s>>6,t[i++]=128|63&s}else if(s<=65535){if(i+2>=n)break;t[i++]=224|s>>12,t[i++]=128|s>>6&63,t[i++]=128|63&s}else{if(i+3>=n)break;t[i++]=240|s>>18,t[i++]=128|s>>12&63,t[i++]=128|s>>6&63,t[i++]=128|63&s}}return t[i]=0,i-o};function Q(e,t,i){var r=i>0?i:J(e)+1,o=new Array(r),n=X(e,o,0,o.length);return t&&(o.length=n),o}var $={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){$.ttys[e]={input:[],output:[],ops:t},re.registerDevice(e,$.stream_ops)},stream_ops:{open:function(e){var t=$.ttys[e.node.rdev];if(!t)throw new re.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,i,r,o){if(!e.tty||!e.tty.ops.get_char)throw new re.ErrnoError(60);for(var n=0,a=0;a<r;a++){var s;try{s=e.tty.ops.get_char(e.tty)}catch(l){throw new re.ErrnoError(29)}if(void 0===s&&0===n)throw new re.ErrnoError(6);if(null==s)break;n++,t[i+a]=s}return n&&(e.node.timestamp=Date.now()),n},write:function(e,t,i,r,o){if(!e.tty||!e.tty.ops.put_char)throw new re.ErrnoError(60);try{for(var n=0;n<r;n++)e.tty.ops.put_char(e.tty,t[i+n])}catch(a){throw new re.ErrnoError(29)}return r&&(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=Q(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,i){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,i,r){if(re.isBlkdev(i)||re.isFIFO(i))throw new re.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:re.chrdev_stream_ops}});var o=re.createNode(e,t,i,r);return re.isDir(o.mode)?(o.node_ops=ee.ops_table.dir.node,o.stream_ops=ee.ops_table.dir.stream,o.contents={}):re.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):re.isLink(o.mode)?(o.node_ops=ee.ops_table.link.node,o.stream_ops=ee.ops_table.link.stream):re.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 i=e.contents?e.contents.length:0;if(!(i>=t)){t=Math.max(t,i*(i<1048576?2:1.125)>>>0),0!=i&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var i=e.contents;e.contents=new Uint8Array(t),i&&e.contents.set(i.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=re.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,re.isDir(e.mode)?t.size=4096:re.isFile(e.mode)?t.size=e.usedBytes:re.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 re.genericErrors[44]},mknod:(e,t,i,r)=>ee.createNode(e,t,i,r),rename(e,t,i){if(re.isDir(e.mode)){var r;try{r=re.lookupNode(t,i)}catch(n){}if(r)for(var o in r.contents)throw new re.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=i,t.contents[i]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var i=re.lookupNode(e,t);for(var r in i.contents)throw new re.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var i in e.contents)e.contents.hasOwnProperty(i)&&t.push(i);return t},symlink(e,t,i){var r=ee.createNode(e,t,41471,0);return r.link=i,r},readlink(e){if(!re.isLink(e.mode))throw new re.ErrnoError(28);return e.link}},stream_ops:{read(e,t,i,r,o){var n=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,r);if(a>8&&n.subarray)t.set(n.subarray(o,o+a),i);else for(var s=0;s<a;s++)t[i+s]=n[o+s];return a},write(e,t,i,r,o,n){if(!r)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(i,i+r),a.usedBytes=r,r;if(0===a.usedBytes&&0===o)return a.contents=t.slice(i,i+r),a.usedBytes=r,r;if(o+r<=a.usedBytes)return a.contents.set(t.subarray(i,i+r),o),r}if(ee.expandFileStorage(a,o+r),a.contents.subarray&&t.subarray)a.contents.set(t.subarray(i,i+r),o);else for(var s=0;s<r;s++)a.contents[o+s]=t[i+s];return a.usedBytes=Math.max(a.usedBytes,o+r),r},llseek(e,t,i){var r=t;if(1===i?r+=e.position:2===i&&re.isFile(e.node.mode)&&(r+=e.node.usedBytes),r<0)throw new re.ErrnoError(28);return r},allocate(e,t,i){ee.expandFileStorage(e.node,t+i),e.node.usedBytes=Math.max(e.node.usedBytes,t+i)},mmap(e,t,i,r,o){if(!re.isFile(e.node.mode))throw new re.ErrnoError(43);var n,a,s=e.node.contents;if(2&o||s.buffer!==_.buffer){if((i>0||i+t<s.length)&&(s=s.subarray?s.subarray(i,i+t):Array.prototype.slice.call(s,i,i+t)),a=!0,!(n=Z()))throw new re.ErrnoError(48);_.set(s,n)}else a=!1,n=s.byteOffset;return{ptr:n,allocated:a}},msync:(e,t,i,r,o)=>(ee.stream_ops.write(e,t,0,r,i,!1),0)}},te=r.preloadPlugins||[];function ie(e,t){var i=0;return e&&(i|=365),t&&(i|=146),i}var re={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 re.ErrnoError(32);for(var i=e.split("/").filter((e=>!!e)),r=re.root,o="/",n=0;n<i.length;n++){var a=n===i.length-1;if(a&&t.parent)break;if(r=re.lookupNode(r,i[n]),o=G.join2(o,i[n]),re.isMountpoint(r)&&(!a||a&&t.follow_mount)&&(r=r.mounted.root),!a||t.follow)for(var s=0;re.isLink(r.mode);){var l=re.readlink(o);if(o=z.resolve(G.dirname(o),l),r=re.lookupPath(o,{recurse_count:t.recurse_count+1}).node,s++>40)throw new re.ErrnoError(32)}}return{path:o,node:r}},getPath:e=>{for(var t;;){if(re.isRoot(e)){var i=e.mount.mountpoint;return t?"/"!==i[i.length-1]?"".concat(i,"/").concat(t):i+t:i}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var i=0,r=0;r<t.length;r++)i=(i<<5)-i+t.charCodeAt(r)|0;return(e+i>>>0)%re.nameTable.length},hashAddNode:e=>{var t=re.hashName(e.parent.id,e.name);e.name_next=re.nameTable[t],re.nameTable[t]=e},hashRemoveNode:e=>{var t=re.hashName(e.parent.id,e.name);if(re.nameTable[t]===e)re.nameTable[t]=e.name_next;else for(var i=re.nameTable[t];i;){if(i.name_next===e){i.name_next=e.name_next;break}i=i.name_next}},lookupNode:(e,t)=>{var i=re.mayLookup(e);if(i)throw new re.ErrnoError(i,e);for(var r=re.hashName(e.id,t),o=re.nameTable[r];o;o=o.name_next){var n=o.name;if(o.parent.id===e.id&&n===t)return o}return re.lookup(e,t)},createNode:(e,t,i,r)=>{var o=new re.FSNode(e,t,i,r);return re.hashAddNode(o),o},destroyNode:e=>{re.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)=>re.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>re.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return re.lookupNode(e,t),20}catch(i){}return re.nodePermissions(e,"wx")},mayDelete:(e,t,i)=>{var r;try{r=re.lookupNode(e,t)}catch(n){return n.errno}var o=re.nodePermissions(e,"wx");if(o)return o;if(i){if(!re.isDir(r.mode))return 54;if(re.isRoot(r)||re.getPath(r)===re.cwd())return 10}else if(re.isDir(r.mode))return 31;return 0},mayOpen:(e,t)=>e?re.isLink(e.mode)?32:re.isDir(e.mode)&&("r"!==re.flagsToPermissionString(t)||512&t)?31:re.nodePermissions(e,re.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=re.MAX_OPEN_FDS;e++)if(!re.streams[e])return e;throw new re.ErrnoError(33)},getStreamChecked:e=>{var t=re.getStream(e);if(!t)throw new re.ErrnoError(8);return t},getStream:e=>re.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return re.FSStream||(re.FSStream=function(){this.shared={}},re.FSStream.prototype={},Object.defineProperties(re.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 re.FSStream,e),-1==t&&(t=re.nextfd()),e.fd=t,re.streams[t]=e,e},closeStream:e=>{re.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=re.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new re.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{re.devices[e]={stream_ops:t}},getDevice:e=>re.devices[e],getMounts:e=>{for(var t=[],i=[e];i.length;){var r=i.pop();t.push(r),i.push.apply(i,r.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),re.syncFSRequests++,re.syncFSRequests>1&&f("warning: ".concat(re.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var i=re.getMounts(re.root.mount),r=0;function o(e){return re.syncFSRequests--,t(e)}function n(e){if(e)return n.errored?void 0:(n.errored=!0,o(e));++r>=i.length&&o(null)}i.forEach((t=>{if(!t.type.syncfs)return n(null);t.type.syncfs(t,e,n)}))},mount:(e,t,i)=>{var r,o="/"===i,n=!i;if(o&&re.root)throw new re.ErrnoError(10);if(!o&&!n){var a=re.lookupPath(i,{follow_mount:!1});if(i=a.path,r=a.node,re.isMountpoint(r))throw new re.ErrnoError(10);if(!re.isDir(r.mode))throw new re.ErrnoError(54)}var s={type:e,opts:t,mountpoint:i,mounts:[]},l=e.mount(s);return l.mount=s,s.root=l,o?re.root=l:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),l},unmount:e=>{var t=re.lookupPath(e,{follow_mount:!1});if(!re.isMountpoint(t.node))throw new re.ErrnoError(28);var i=t.node,r=i.mounted,o=re.getMounts(r);Object.keys(re.nameTable).forEach((e=>{for(var t=re.nameTable[e];t;){var i=t.name_next;o.includes(t.mount)&&re.destroyNode(t),t=i}})),i.mounted=null;var n=i.mount.mounts.indexOf(r);i.mount.mounts.splice(n,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,i)=>{var r=re.lookupPath(e,{parent:!0}).node,o=G.basename(e);if(!o||"."===o||".."===o)throw new re.ErrnoError(28);var n=re.mayCreate(r,o);if(n)throw new re.ErrnoError(n);if(!r.node_ops.mknod)throw new re.ErrnoError(63);return r.node_ops.mknod(r,o,t,i)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,re.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,re.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var i=e.split("/"),r="",o=0;o<i.length;++o)if(i[o]){r+="/"+i[o];try{re.mkdir(r,t)}catch(n){if(20!=n.errno)throw n}}},mkdev:(e,t,i)=>(void 0===i&&(i=t,t=438),t|=8192,re.mknod(e,t,i)),symlink:(e,t)=>{if(!z.resolve(e))throw new re.ErrnoError(44);var i=re.lookupPath(t,{parent:!0}).node;if(!i)throw new re.ErrnoError(44);var r=G.basename(t),o=re.mayCreate(i,r);if(o)throw new re.ErrnoError(o);if(!i.node_ops.symlink)throw new re.ErrnoError(63);return i.node_ops.symlink(i,r,e)},rename:(e,t)=>{var i,r,o=G.dirname(e),n=G.dirname(t),a=G.basename(e),s=G.basename(t);if(i=re.lookupPath(e,{parent:!0}).node,r=re.lookupPath(t,{parent:!0}).node,!i||!r)throw new re.ErrnoError(44);if(i.mount!==r.mount)throw new re.ErrnoError(75);var l,c=re.lookupNode(i,a),d=z.relative(e,n);if("."!==d.charAt(0))throw new re.ErrnoError(28);if("."!==(d=z.relative(t,o)).charAt(0))throw new re.ErrnoError(55);try{l=re.lookupNode(r,s)}catch(p){}if(c!==l){var u=re.isDir(c.mode),h=re.mayDelete(i,a,u);if(h)throw new re.ErrnoError(h);if(h=l?re.mayDelete(r,s,u):re.mayCreate(r,s))throw new re.ErrnoError(h);if(!i.node_ops.rename)throw new re.ErrnoError(63);if(re.isMountpoint(c)||l&&re.isMountpoint(l))throw new re.ErrnoError(10);if(r!==i&&(h=re.nodePermissions(i,"w")))throw new re.ErrnoError(h);re.hashRemoveNode(c);try{i.node_ops.rename(c,r,s)}catch(p){throw p}finally{re.hashAddNode(c)}}},rmdir:e=>{var t=re.lookupPath(e,{parent:!0}).node,i=G.basename(e),r=re.lookupNode(t,i),o=re.mayDelete(t,i,!0);if(o)throw new re.ErrnoError(o);if(!t.node_ops.rmdir)throw new re.ErrnoError(63);if(re.isMountpoint(r))throw new re.ErrnoError(10);t.node_ops.rmdir(t,i),re.destroyNode(r)},readdir:e=>{var t=re.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new re.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=re.lookupPath(e,{parent:!0}).node;if(!t)throw new re.ErrnoError(44);var i=G.basename(e),r=re.lookupNode(t,i),o=re.mayDelete(t,i,!1);if(o)throw new re.ErrnoError(o);if(!t.node_ops.unlink)throw new re.ErrnoError(63);if(re.isMountpoint(r))throw new re.ErrnoError(10);t.node_ops.unlink(t,i),re.destroyNode(r)},readlink:e=>{var t=re.lookupPath(e).node;if(!t)throw new re.ErrnoError(44);if(!t.node_ops.readlink)throw new re.ErrnoError(28);return z.resolve(re.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var i=re.lookupPath(e,{follow:!t}).node;if(!i)throw new re.ErrnoError(44);if(!i.node_ops.getattr)throw new re.ErrnoError(63);return i.node_ops.getattr(i)},lstat:e=>re.stat(e,!0),chmod:(e,t,i)=>{var r;if(!(r="string"==typeof e?re.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new re.ErrnoError(63);r.node_ops.setattr(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})},lchmod:(e,t)=>{re.chmod(e,t,!0)},fchmod:(e,t)=>{var i=re.getStreamChecked(e);re.chmod(i.node,t)},chown:(e,t,i,r)=>{var o;if(!(o="string"==typeof e?re.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new re.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,t,i)=>{re.chown(e,t,i,!0)},fchown:(e,t,i)=>{var r=re.getStreamChecked(e);re.chown(r.node,t,i)},truncate:(e,t)=>{if(t<0)throw new re.ErrnoError(28);var i;if(!(i="string"==typeof e?re.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new re.ErrnoError(63);if(re.isDir(i.mode))throw new re.ErrnoError(31);if(!re.isFile(i.mode))throw new re.ErrnoError(28);var r=re.nodePermissions(i,"w");if(r)throw new re.ErrnoError(r);i.node_ops.setattr(i,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var i=re.getStreamChecked(e);if(!(2097155&i.flags))throw new re.ErrnoError(28);re.truncate(i.node,t)},utime:(e,t,i)=>{var r=re.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,i)})},open:(e,t,i)=>{if(""===e)throw new re.ErrnoError(44);var o;if(i=void 0===i?438:i,i=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&i|32768:0,"object"==typeof e)o=e;else{e=G.normalize(e);try{o=re.lookupPath(e,{follow:!(131072&t)}).node}catch(l){}}var n=!1;if(64&t)if(o){if(128&t)throw new re.ErrnoError(20)}else o=re.mknod(e,i,0),n=!0;if(!o)throw new re.ErrnoError(44);if(re.isChrdev(o.mode)&&(t&=-513),65536&t&&!re.isDir(o.mode))throw new re.ErrnoError(54);if(!n){var a=re.mayOpen(o,t);if(a)throw new re.ErrnoError(a)}512&t&&!n&&re.truncate(o,0),t&=-131713;var s=re.createStream({node:o,path:re.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),!r.logReadFiles||1&t||(re.readFiles||(re.readFiles={}),e in re.readFiles||(re.readFiles[e]=1)),s},close:e=>{if(re.isClosed(e))throw new re.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{re.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,i)=>{if(re.isClosed(e))throw new re.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new re.ErrnoError(70);if(0!=i&&1!=i&&2!=i)throw new re.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,i),e.ungotten=[],e.position},read:(e,t,i,r,o)=>{if(r<0||o<0)throw new re.ErrnoError(28);if(re.isClosed(e))throw new re.ErrnoError(8);if(1==(2097155&e.flags))throw new re.ErrnoError(8);if(re.isDir(e.node.mode))throw new re.ErrnoError(31);if(!e.stream_ops.read)throw new re.ErrnoError(28);var n=void 0!==o;if(n){if(!e.seekable)throw new re.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,t,i,r,o);return n||(e.position+=a),a},write:(e,t,i,r,o,n)=>{if(r<0||o<0)throw new re.ErrnoError(28);if(re.isClosed(e))throw new re.ErrnoError(8);if(!(2097155&e.flags))throw new re.ErrnoError(8);if(re.isDir(e.node.mode))throw new re.ErrnoError(31);if(!e.stream_ops.write)throw new re.ErrnoError(28);e.seekable&&1024&e.flags&&re.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new re.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,i,r,o,n);return a||(e.position+=s),s},allocate:(e,t,i)=>{if(re.isClosed(e))throw new re.ErrnoError(8);if(t<0||i<=0)throw new re.ErrnoError(28);if(!(2097155&e.flags))throw new re.ErrnoError(8);if(!re.isFile(e.node.mode)&&!re.isDir(e.node.mode))throw new re.ErrnoError(43);if(!e.stream_ops.allocate)throw new re.ErrnoError(138);e.stream_ops.allocate(e,t,i)},mmap:(e,t,i,r,o)=>{if(2&r&&!(2&o)&&2!=(2097155&e.flags))throw new re.ErrnoError(2);if(1==(2097155&e.flags))throw new re.ErrnoError(2);if(!e.stream_ops.mmap)throw new re.ErrnoError(43);return e.stream_ops.mmap(e,t,i,r,o)},msync:(e,t,i,r,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,i,r,o):0,munmap:e=>0,ioctl:(e,t,i)=>{if(!e.stream_ops.ioctl)throw new re.ErrnoError(59);return e.stream_ops.ioctl(e,t,i)},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 i,r=re.open(e,t.flags),o=re.stat(e).size,n=new Uint8Array(o);return re.read(r,n,0,o,0),"utf8"===t.encoding?i=q(n,0):"binary"===t.encoding&&(i=n),re.close(r),i},writeFile:function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};i.flags=i.flags||577;var r=re.open(e,i.flags,i.mode);if("string"==typeof t){var o=new Uint8Array(J(t)+1),n=X(t,o,0,o.length);re.write(r,o,0,n,void 0,i.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");re.write(r,t,0,t.byteLength,void 0,i.canOwn)}re.close(r)},cwd:()=>re.currentPath,chdir:e=>{var t=re.lookupPath(e,{follow:!0});if(null===t.node)throw new re.ErrnoError(44);if(!re.isDir(t.node.mode))throw new re.ErrnoError(54);var i=re.nodePermissions(t.node,"x");if(i)throw new re.ErrnoError(i);re.currentPath=t.path},createDefaultDirectories:()=>{re.mkdir("/tmp"),re.mkdir("/home"),re.mkdir("/home/web_user")},createDefaultDevices:()=>{re.mkdir("/dev"),re.registerDevice(re.makedev(1,3),{read:()=>0,write:(e,t,i,r,o)=>r}),re.mkdev("/dev/null",re.makedev(1,3)),$.register(re.makedev(5,0),$.default_tty_ops),$.register(re.makedev(6,0),$.default_tty1_ops),re.mkdev("/dev/tty",re.makedev(5,0)),re.mkdev("/dev/tty1",re.makedev(6,0));var e=new Uint8Array(1024),t=0,i=()=>(0===t&&(t=j(e).byteLength),e[--t]);re.createDevice("/dev","random",i),re.createDevice("/dev","urandom",i),re.mkdir("/dev/shm"),re.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{re.mkdir("/proc");var e=re.mkdir("/proc/self");re.mkdir("/proc/self/fd"),re.mount({mount:()=>{var t=re.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var i=+t,r=re.getStreamChecked(i),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{r.stdin?re.createDevice("/dev","stdin",r.stdin):re.symlink("/dev/tty","/dev/stdin"),r.stdout?re.createDevice("/dev","stdout",null,r.stdout):re.symlink("/dev/tty","/dev/stdout"),r.stderr?re.createDevice("/dev","stderr",null,r.stderr):re.symlink("/dev/tty1","/dev/stderr"),re.open("/dev/stdin",0),re.open("/dev/stdout",1),re.open("/dev/stderr",1)},ensureErrnoError:()=>{re.ErrnoError||(re.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},re.ErrnoError.prototype=new Error,re.ErrnoError.prototype.constructor=re.ErrnoError,[44].forEach((e=>{re.genericErrors[e]=new re.ErrnoError(e),re.genericErrors[e].stack="<generic error, no stack>"})))},staticInit:()=>{re.ensureErrnoError(),re.nameTable=new Array(4096),re.mount(ee,{},"/"),re.createDefaultDirectories(),re.createDefaultDevices(),re.createSpecialDirectories(),re.filesystems={MEMFS:ee}},init:(e,t,i)=>{re.init.initialized=!0,re.ensureErrnoError(),r.stdin=e||r.stdin,r.stdout=t||r.stdout,r.stderr=i||r.stderr,re.createStandardStreams()},quit:()=>{re.init.initialized=!1;for(var e=0;e<re.streams.length;e++){var t=re.streams[e];t&&re.close(t)}},findObject:(e,t)=>{var i=re.analyzePath(e,t);return i.exists?i.object:null},analyzePath:(e,t)=>{try{e=(r=re.lookupPath(e,{follow:!t})).path}catch(o){}var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var r=re.lookupPath(e,{parent:!0});i.parentExists=!0,i.parentPath=r.path,i.parentObject=r.node,i.name=G.basename(e),r=re.lookupPath(e,{follow:!t}),i.exists=!0,i.path=r.path,i.object=r.node,i.name=r.node.name,i.isRoot="/"===r.path}catch(o){i.error=o.errno}return i},createPath:(e,t,i,r)=>{e="string"==typeof e?e:re.getPath(e);for(var o=t.split("/").reverse();o.length;){var n=o.pop();if(n){var a=G.join2(e,n);try{re.mkdir(a)}catch(s){}e=a}}return a},createFile:(e,t,i,r,o)=>{var n=G.join2("string"==typeof e?e:re.getPath(e),t),a=ie(r,o);return re.create(n,a)},createDataFile:(e,t,i,r,o,n)=>{var a=t;e&&(e="string"==typeof e?e:re.getPath(e),a=t?G.join2(e,t):e);var s=ie(r,o),l=re.create(a,s);if(i){if("string"==typeof i){for(var c=new Array(i.length),d=0,u=i.length;d<u;++d)c[d]=i.charCodeAt(d);i=c}re.chmod(l,146|s);var h=re.open(l,577);re.write(h,i,0,i.length,0,n),re.close(h),re.chmod(l,s)}return l},createDevice:(e,t,i,r)=>{var o=G.join2("string"==typeof e?e:re.getPath(e),t),n=ie(!!i,!!r);re.createDevice.major||(re.createDevice.major=64);var a=re.makedev(re.createDevice.major++,0);return re.registerDevice(a,{open:e=>{e.seekable=!1},close:e=>{r&&r.buffer&&r.buffer.length&&r(10)},read:(e,t,r,o,n)=>{for(var a=0,s=0;s<o;s++){var l;try{l=i()}catch(c){throw new re.ErrnoError(29)}if(void 0===l&&0===a)throw new re.ErrnoError(6);if(null==l)break;a++,t[r+s]=l}return a&&(e.node.timestamp=Date.now()),a},write:(e,t,i,o,n)=>{for(var a=0;a<o;a++)try{r(t[i+a])}catch(s){throw new re.ErrnoError(29)}return o&&(e.node.timestamp=Date.now()),a}}),re.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=Q(o(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new re.ErrnoError(29)}},createLazyFile:(e,t,i,r,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,i=e/this.chunkSize|0;return this.getter(i)[t]}},n.prototype.setDataGetter=function(e){this.getter=e},n.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",i,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+i+". Status: "+e.status);var t,r=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=r);var s=this;s.setDataGetter((e=>{var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,r-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>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",i,!1),r!==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 "+i+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):Q(o.responseText||"",!0)})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!n&&r||(a=r=1,r=this.getter(0).length,a=r,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,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:i};var l=re.createFile(e,t,s,r,o);s.contents?l.contents=s.contents:s.url&&(l.contents=null,l.url=s.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,i,r,o){var n=e.node.contents;if(o>=n.length)return 0;var a=Math.min(n.length-o,r);if(n.slice)for(var s=0;s<a;s++)t[i+s]=n[o+s];else for(s=0;s<a;s++)t[i+s]=n.get(o+s);return a}return Object.keys(l.stream_ops).forEach((e=>{var t=l.stream_ops[e];c[e]=function(){return re.forceLoadFile(l),t.apply(null,arguments)}})),c.read=(e,t,i,r,o)=>(re.forceLoadFile(l),u(e,t,i,r,o)),c.mmap=(e,t,i,r,o)=>{re.forceLoadFile(l);var n=Z();if(!n)throw new re.ErrnoError(48);return u(e,_,n,t,i),{ptr:n,allocated:!0}},l.stream_ops=c,l}},oe=(e,t)=>e?q(g,e,t):"",ne={DEFAULT_POLLMASK:5,calculateAt:function(e,t,i){if(G.isAbs(t))return t;var r;if(r=-100===e?re.cwd():ne.getStreamFromFD(e).path,0==t.length){if(!i)throw new re.ErrnoError(44);return r}return G.join2(r,t)},doStat:function(e,t,i){try{var r=e(t)}catch(s){if(s&&s.node&&G.normalize(t)!==G.normalize(re.getPath(s.node)))return-54;throw s}y[i>>2]=r.dev,y[i+4>>2]=r.mode,T[i+8>>2]=r.nlink,y[i+12>>2]=r.uid,y[i+16>>2]=r.gid,y[i+20>>2]=r.rdev,C=[r.size>>>0,(w=r.size,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[i+24>>2]=C[0],y[i+28>>2]=C[1],y[i+32>>2]=4096,y[i+36>>2]=r.blocks;var o=r.atime.getTime(),n=r.mtime.getTime(),a=r.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[i+40>>2]=C[0],y[i+44>>2]=C[1],T[i+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[i+56>>2]=C[0],y[i+60>>2]=C[1],T[i+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[i+72>>2]=C[0],y[i+76>>2]=C[1],T[i+80>>2]=a%1e3*1e3,C=[r.ino>>>0,(w=r.ino,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[i+88>>2]=C[0],y[i+92>>2]=C[1],0},doMsync:function(e,t,i,r,o){if(!re.isFile(t.node.mode))throw new re.ErrnoError(43);if(2&r)return 0;var n=g.slice(e,e+i);re.msync(t,n,o,i,r)},varargs:void 0,get:()=>(ne.varargs+=4,y[ne.varargs-4>>2]),getStr:e=>oe(e),getStreamFromFD:function(e){return re.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 le(e){for(var t="",i=e;g[i];)t+=se[g[i++]];return t}var ce={},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,i){function r(t){var r=i(t);r.length!==e.length&&fe("Mismatched type converter count");for(var o=0;o<e.length;++o)ge(e[o],r[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),ce.hasOwnProperty(e)||(ce[e]=[]),ce[e].push((()=>{o[t]=de[e],++a===n.length&&r(o)})))})),0===n.length&&r(o)}function ge(e,t){let i=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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r=t.name;if(e||pe('type "'.concat(r,'" must have a positive integer typeid pointer')),de.hasOwnProperty(e)){if(i.ignoreDuplicateRegistrations)return;pe("Cannot register type '".concat(r,"' twice"))}if(de[e]=t,delete ue[e],ce.hasOwnProperty(e)){var o=ce[e];delete ce[e],o.forEach((e=>e()))}}(e,t,i)}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,i){if(t===i)return e;if(void 0===i.baseClass)return null;var r=Ie(e,t,i.baseClass);return null===r?null:i.downcast(r)}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 i={$$:t};ve.register(e,i,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,i){if(void 0===e[t].overloadTable){var r=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||pe("Function '".concat(i,"' 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[r.argCount]=r}}function Pe(e,t,i,r,o,n,a,s){this.name=e,this.constructor=t,this.instancePrototype=i,this.rawDestructor=r,this.baseClass=o,this.getActualType=n,this.upcast=a,this.downcast=s,this.pureVirtualFunctions=[]}function Le(e,t,i){for(;t!==i;)t.upcast||pe("Expected null or instance of ".concat(i.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 i=t.$$.ptrType.registeredClass;return Le(t.$$.ptr,i,this.registeredClass)}function Ue(e,t){var i;if(null===t)return this.isReference&&pe("null is not a valid ".concat(this.name)),this.isSmartPointer?(i=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,i),i):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 r=t.$$.ptrType.registeredClass;if(i=Le(t.$$.ptr,r,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?i=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:i=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)i=t.$$.smartPtr;else{var o=t.clone();i=this.rawShare(i,et.toHandle((function(){o.delete()}))),null!==e&&e.push(this.rawDestructor,i)}break;default:pe("Unsupporting sharing policy")}return i}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 i=t.$$.ptrType.registeredClass;return Le(t.$$.ptr,i,this.registeredClass)}function Fe(e){return this.fromWireType(y[e>>2])}function Be(e,t,i,r,o,n,a,s,l,c,d){this.name=e,this.registeredClass=t,this.isReference=i,this.isConst=r,this.isSmartPointer=o,this.pointeeType=n,this.sharingPolicy=a,this.rawGetPointee=s,this.rawConstructor=l,this.rawShare=c,this.rawDestructor=d,o||void 0!==t.baseClass?this.toWireType=Ue:r?(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 Ge(e,t){var i,o,n,a=(e=le(e)).includes("j")?(i=e,o=t,n=[],function(){return n.length=0,Object.assign(n,arguments),((e,t,i)=>{return e.includes("j")?(o=t,n=i,a=r["dynCall_"+e],n&&n.length?a.apply(null,[o].concat(n)):a.call(null,o)):We(t).apply(null,i);var o,n,a})(i,o,n)}):We(t);return"function"!=typeof a&&pe("unknown function pointer with signature ".concat(e,": ").concat(t)),a}var je=void 0;function ze(e){var t=St(e),i=le(t);return It(t),i}function Ke(e,t){var i=[],r={};throw t.forEach((function e(t){r[t]||de[t]||(ue[t]?ue[t].forEach(e):(i.push(t),r[t]=!0))})),new je("".concat(e,": ")+i.map(ze).join([", "]))}function qe(e,t){for(var i=[],r=0;r<e;r++)i.push(T[t+4*r>>2]);return i}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 i=Oe(e.name||"unknownFunctionName",(function(){}));i.prototype=e.prototype;var r=new i,o=e.apply(r,t);return o instanceof Object?o:r}function Xe(e,t,i,r,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!==i,l=!1,c=1;c<t.length;++c)if(null!==t[c]&&void 0===t[c].destructorFunction){l=!0;break}var d="void"!==t[0].name,u="",h="";for(c=0;c<a-2;++c)u+=(0!==c?", ":"")+"arg"+c,h+=(0!==c?", ":"")+"arg"+c+"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 }");l&&(p+="var destructors = [];\n");var m=l?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[pe,r,o,Ye,t[0],t[1]];for(s&&(p+="var thisWired = classParam.toWireType("+m+", this);\n"),c=0;c<a-2;++c)p+="var arg"+c+"Wired = argType"+c+".toWireType("+m+", arg"+c+"); // "+t[c+2].name+"\n",f.push("argType"+c),_.push(t[c+2]);if(s&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||n?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",l)p+="runDestructors(destructors);\n";else for(c=s?1:2;c<t.length;++c){var g=1===c?"thisWired":"arg"+(c-2)+"Wired";null!==t[c].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[c].name+"\n",f.push(g+"_dtor"),_.push(t[c].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),Je(Function,f).apply(null,_)}function Qe(){this.allocated=[void 0],this.freelist=[]}var $e=new Qe;function Ze(e){e>=$e.reserved&&0==--$e.get(e).refcount&&$e.free(e)}var et={toValue:e=>(e||pe("Cannot use deleted val. handle = "+e),$e.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 $e.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 it(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 rt(e,t,i){switch(t){case 0:return i?function(e){return _[e]}:function(e){return g[e]};case 1:return i?function(e){return E[e>>1]}:function(e){return v[e>>1]};case 2:return i?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 i=e,r=i>>1,o=r+t/2;!(r>=o)&&v[r];)++r;if((i=r<<1)-e>32&&at)return at.decode(g.subarray(e,i));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},lt=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<2)return 0;for(var r=t,o=(i-=2)<2*e.length?i/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-r},ct=e=>2*e.length,dt=(e,t)=>{for(var i=0,r="";!(i>=t/4);){var o=y[e+4*i>>2];if(0==o)break;if(++i,o>=65536){var n=o-65536;r+=String.fromCharCode(55296|n>>10,56320|1023&n)}else r+=String.fromCharCode(o)}return r},ut=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<4)return 0;for(var r=t,o=r+i-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-r},ht=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r>=55296&&r<=57343&&++i,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",_:l||"./this.program"};for(var t in _t)void 0===_t[t]?delete e[t]:e[t]=_t[t];var i=[];for(var t in e)i.push("".concat(t,"=").concat(e[t]));gt.strings=i}return gt.strings},Et=function(e,t,i,r){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=re.nextInode++,this.name=t,this.mode=i,this.node_ops={},this.stream_ops={},this.rdev=r};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 re.isDir(this.mode)}},isDevice:{get:function(){return re.isChrdev(this.mode)}}}),re.FSNode=Et,re.createPreloadedFile=function(e,t,i,r,o,a,s,l,c,d){var u=t?z.resolve(G.join2(e,t)):e;function h(i){function n(i){d&&d(),l||re.createDataFile(e,t,i,r,o,c),a&&a(),x()}(function(e,t,i,r){"undefined"!=typeof Browser&&Browser.init();var o=!1;return te.forEach((function(n){o||n.canHandle(t)&&(n.handle(e,t,i,r),o=!0)})),o})(i,u,n,(()=>{s&&s(),x()}))||n(i)}L(),"string"==typeof i?((e,t,i,r)=>{var o=r?"":"al ".concat(e);n(e,(i=>{var r;r='Loading data file "'.concat(e,'" failed (no arrayBuffer).'),i||U(r),t(new Uint8Array(i)),o&&x()}),(t=>{if(!i)throw'Loading data file "'.concat(e,'" failed.');i()})),o&&L()})(i,(e=>h(e)),s):h(i)},re.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);se=e}(),he=r.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},me=r.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,i=this.$$.ptr,r=e.$$.ptrType.registeredClass,o=e.$$.ptr;t.baseClass;)i=t.upcast(i),t=t.baseClass;for(;r.baseClass;)o=r.upcast(o),r=r.baseClass;return t===r&&i===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},r.getInheritedInstanceCount=function(){return Object.keys(we).length},r.getLiveInheritedInstances=function(){var e=[];for(var t in we)we.hasOwnProperty(t)&&e.push(we[t]);return e},r.flushPendingDeletes=Re,r.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 i=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!==i){if(0===i.$$.count.value)return i.$$.ptr=t,i.$$.smartPtr=e,i.clone();var r=i.clone();return this.destructor(e),r}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 l=Ie(t,this.registeredClass,n.registeredClass);return null===l?o.call(this):this.isSmartPointer?Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:l,smartPtrType:this,smartPtr:e}):Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:l})},je=r.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(Qe.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)}}),$e.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),$e.reserved=$e.allocated.length,r.count_emval_handles=function(){for(var e=0,t=$e.reserved;t<$e.allocated.length;++t)void 0!==$e.allocated[t]&&++e;return e};var vt,yt={p:function(e,t,i){throw new W(e).init(t,i),e},C:function(e,t,i){ne.varargs=i;try{var r=ne.getStreamFromFD(e);switch(t){case 0:return(o=ne.get())<0?-28:re.createStream(r,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return r.flags;case 4:var o=ne.get();return r.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===re||"ErrnoError"!==n.name)throw n;return-n.errno}},w:function(e,t,i,r){ne.varargs=r;try{t=ne.getStr(t),t=ne.calculateAt(e,t);var o=r?ne.get():0;return re.open(t,i,o).fd}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return-n.errno}},t:function(e,t,i,r,o){},n:function(e,t,i,r,o){var n=ae(i);ge(e,{name:t=le(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?r:o},argPackAdvance:8,readValueFromPointer:function(e){var r;if(1===i)r=_;else if(2===i)r=E;else{if(4!==i)throw new TypeError("Unknown boolean type size: "+t);r=y}return this.fromWireType(r[e>>n])},destructorFunction:null})},r:function(e,t,i,o,n,a,s,l,c,d,u,h,p){u=le(u),a=Ge(n,a),l&&(l=Ge(s,l)),d&&(d=Ge(c,d)),p=Ge(h,p);var m,f,_,g=ke(u);m=g,f=function(){Ke("Cannot construct ".concat(u," due to unbound types"),[o])},r.hasOwnProperty(m)?(pe("Cannot register public name '".concat(m,"' twice")),Me(r,m,m),r.hasOwnProperty(_)&&pe("Cannot register multiple overloads of a function with the same number of arguments (".concat(_,")!")),r[m].overloadTable[_]=f):r[m]=f,_e([e,t,i],o?[o]:[],(function(t){var i,n;t=t[0],n=o?(i=t.registeredClass).instancePrototype:Ne.prototype;var s=Oe(g,(function(){if(Object.getPrototypeOf(this)!==c)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)})),c=Object.create(n,{constructor:{value:s}});s.prototype=c;var h=new Pe(u,s,c,p,i,a,l,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,r.hasOwnProperty(m)||fe("Replacing nonexistant public symbol"),r[m].overloadTable,r[m]=f,r[m].argCount=_,[E,v,y]}))},q:function(e,t,i,r,o,n){var a=qe(t,i);o=Ge(r,o),_e([],[e],(function(e){var i="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(r){return r.splice(1,0,null),e.registeredClass.constructor_body[t-1]=Xe(i,r,null,o,n),[]})),[]}))},d:function(e,t,i,r,o,n,a,s,l){var c=qe(i,r);t=le(t),n=Ge(o,n),_e([],[e],(function(e){var r="".concat((e=e[0]).name,".").concat(t);function o(){Ke("Cannot call ".concat(r," due to unbound types"),c)}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===i-2?(o.argCount=i-2,o.className=e.name,d[t]=o):(Me(d,t,r),d[t].overloadTable[i-2]=o),_e([],c,(function(o){var s=Xe(r,o,e,n,a,l);return void 0===d[t].overloadTable?(s.argCount=i-2,d[t]=s):d[t].overloadTable[i-2]=s,[]})),[]}))},D:function(e,t){ge(e,{name:t=le(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,i){var r=ae(i);ge(e,{name:t=le(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:it(t,r),destructorFunction:null})},c:function(e,t,i,r,o){t=le(t);var n=ae(i),a=e=>e;if(0===r){var s=32-8*i;a=e=>e<<s>>>s}var l=t.includes("unsigned");ge(e,{name:t,fromWireType:a,toWireType:l?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:rt(t,n,0!==r),destructorFunction:null})},b:function(e,t,i){var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function o(e){var t=T,i=t[e>>=2],o=t[e+1];return new r(t.buffer,o,i)}ge(e,{name:i=le(i),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var i="std::string"===(t=le(t));ge(e,{name:t,fromWireType:function(e){var t,r=T[e>>2],o=e+4;if(i)for(var n=o,a=0;a<=r;++a){var s=o+a;if(a==r||0==g[s]){var l=oe(n,s-n);void 0===t?t=l:(t+="\0",t+=l),n=s+1}}else{var c=new Array(r);for(a=0;a<r;++a)c[a]=String.fromCharCode(g[o+a]);t=c.join("")}return It(e),t},toWireType:function(e,t){var r;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"),r=i&&o?J(t):t.length;var n=Tt(4+r+1),a=n+4;if(T[n>>2]=r,i&&o)X(t,g,a,r+1);else if(o)for(var s=0;s<r;++s){var l=t.charCodeAt(s);l>255&&(It(a),pe("String has UTF-16 code units that do not fit in 8 bits")),g[a+s]=l}else for(s=0;s<r;++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,i){var r,o,n,a,s;i=le(i),2===t?(r=st,o=lt,a=ct,n=()=>v,s=1):4===t&&(r=dt,o=ut,a=ht,n=()=>T,s=2),ge(e,{name:i,fromWireType:function(e){for(var i,o=T[e>>2],a=n(),l=e+4,c=0;c<=o;++c){var d=e+4+c*t;if(c==o||0==a[d>>s]){var u=r(l,d-l);void 0===i?i=u:(i+="\0",i+=u),l=d+t}}return It(e),i},toWireType:function(e,r){"string"!=typeof r&&pe("Cannot pass non-string to C++ string type ".concat(i));var n=a(r),l=Tt(4+n+t);return T[l>>2]=n>>s,o(r,l+4,n+t),null!==e&&e.push(It,l),l},argPackAdvance:8,readValueFromPointer:Fe,destructorFunction:function(e){It(e)}})},o:function(e,t){ge(e,{isVoid:!0,name:t=le(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,i,r){var o,n;(e=mt[e])(t=et.toValue(t),i=void 0===(n=pt[o=i])?le(o):n,null,r)},m:Ze,l:function(e,t){var i=function(e,t){for(var i,r,o,n=new Array(e),a=0;a<e;++a)n[a]=(i=T[t+4*a>>2],r="parameter "+a,void 0===(o=de[i])&&pe(r+" has unknown type "+ze(i)),o);return n}(e,t),r=i[0],o=r.name+"_$"+i.slice(1).map((function(e){return e.name})).join("_")+"$",n=ft[o];if(void 0!==n)return n;for(var a=["retType"],s=[r],l="",c=0;c<e-1;++c)l+=(0!==c?", ":"")+"arg"+c,a.push("argType"+c),s.push(i[1+c]);var d,u,h="return function "+ke("methodCaller_"+o)+"(handle, name, destructors, args) {\n",p=0;for(c=0;c<e-1;++c)h+=" var arg"+c+" = argType"+c+".readValueFromPointer(args"+(p?"+"+p:"")+");\n",p+=i[c+1].argPackAdvance;for(h+=" var rv = handle[name]("+l+");\n",c=0;c<e-1;++c)i[c+1].deleteObject&&(h+=" argType"+c+".deleteObject(arg"+c+");\n");return r.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,i)=>g.copyWithin(e,t,t+i),u:e=>{g.length,U("OOM")},y:(e,t)=>{var i=0;return gt().forEach((function(r,o){var n=t+i;T[e+4*o>>2]=n,((e,t)=>{for(var i=0;i<e.length;++i)_[0|t++]=e.charCodeAt(i);_[0|t]=0})(r,n),i+=r.length+1})),0},z:(e,t)=>{var i=gt();T[e>>2]=i.length;var r=0;return i.forEach((function(e){r+=e.length+1})),T[t>>2]=r,0},i:function(e){try{var t=ne.getStreamFromFD(e);return re.close(t),0}catch(i){if(void 0===re||"ErrnoError"!==i.name)throw i;return i.errno}},x:function(e,t){try{var i=ne.getStreamFromFD(e),r=i.tty?2:re.isDir(i.mode)?3:re.isLink(i.mode)?7:4;return _[0|t]=r,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===re||"ErrnoError"!==o.name)throw o;return o.errno}},B:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=re.read(e,_,a,s,r);if(l<0)return-1;if(o+=l,l<s)break;void 0!==r&&(r+=l)}return o})(ne.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return n.errno}},s:function(e,t,i,r,o){var n,a,s=(a=i)+2097152>>>0<4194305-!!(n=t)?(n>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var l=ne.getStreamFromFD(e);return re.llseek(l,s,r),C=[l.position>>>0,(w=l.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],l.getdents&&0===s&&0===r&&(l.getdents=null),0}catch(c){if(void 0===re||"ErrnoError"!==c.name)throw c;return c.errno}},h:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=re.write(e,_,a,s,r);if(l<0)return-1;o+=l,void 0!==r&&(r+=l)}return o})(ne.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return n.errno}}},Tt=(function(){var e,t,o,n,a={a:yt};function s(e,t){var i,o,n=e.exports;return i=(p=n).E.buffer,r.HEAP8=_=new Int8Array(i),r.HEAP16=E=new Int16Array(i),r.HEAP32=y=new Int32Array(i),r.HEAPU8=g=new Uint8Array(i),r.HEAPU16=v=new Uint16Array(i),r.HEAPU32=T=new Uint32Array(i),r.HEAPF32=I=new Float32Array(i),r.HEAPF64=A=new Float64Array(i),S=p.H,o=p.F,k.unshift(o),x(),n}if(L(),r.instantiateWasm)try{return r.instantiateWasm(a,s)}catch(l){f("Module.instantiateWasm callback failed with error: "+l),i(l)}(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(i)}(),e=>(Tt=p.G)(e)),It=e=>(It=p.I)(e),At=()=>(At=p.J)(),St=e=>(St=p.K)(e),Rt=(r.__embind_initialize_bindings=()=>(r.__embind_initialize_bindings=p.L)(),e=>(Rt=p.M)(e));function bt(){function e(){vt||(vt=!0,r.calledRun=!0,D||(r.noFSInit||re.init.initialized||re.init(),re.ignorePermissions=!1,H(k),t(r),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)e=r.postRun.shift(),O.unshift(e);var e;H(O)}()))}M>0||(function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)e=r.preRun.shift(),N.unshift(e);var e;H(N)}(),M>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}if(r.dynCall_jiji=(e,t,i,o,n)=>(r.dynCall_jiji=p.N)(e,t,i,o,n),r._ff_h264_cabac_tables=67061,P=function e(){vt||bt(),vt||(P=e)},r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return bt(),e.ready}),FH=VH,BH=class extends xH{constructor(e){super(FH,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 HH=(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.SEI_MESSAGE="267",e.USER_PAUSE_IN_PIP="268",e.USER_RESUME_IN_PIP="269",e.ENTER_PICTURE_IN_PICTURE="270",e.LEAVE_PICTURE_IN_PICTURE="271",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(HH||{}),WH="undefined"!=typeof importScripts,GH="undefined"!=typeof registerProcessor,jH="jssdk_log",zH=(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))(zH||{}),KH=Symbol(32),qH=Symbol(16),YH=Symbol(8),JH=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 function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,s)}l((r=r.apply(e,t||[])).next())}))}(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(KH)}readU16(){return this.read(qH)}readU8(){return this.read(YH)}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===KH){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===qH){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===YH){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}};JH.U32=KH,JH.U16=qH,JH.U8=YH;function XH(e){let t=new JH;for(;e>=128;)t.malloc(1)[0]=255&e|128,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function QH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new JH,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(XH(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(XH(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new JH;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=QH(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=QH(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(XH(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var $H=class{constructor(){IH(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 ZH(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 eW(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function tW(e,t){return e[t]}function iW(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var rW=0,oW=2654435769;function nW(e,t){let i=new $H,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,rW);rW=rW+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new $H;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.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,wG(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===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+2+7)%8;r&&(r=8-r);let o=new Uint8Array(i+1+2+7+r),n=0,a=new Uint8Array(8),s=new Uint8Array(8),l=new Uint8Array(8),c=0;a[0]=248&Math.floor(256*Math.random())|r,c=1;for(let u=0;u<r;u++)a[c]=255&Math.floor(256*Math.random()),c+=1;for(let u=0;u<2;)if(c<8&&(a[c]=255&Math.floor(256*Math.random()),c+=1,u+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}let d=0;for(;d<i;)if(c<8&&(a[c]=e[d],c+=1,d+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}for(let u=0;u<7;)if(c<8&&(a[c]=0,c+=1,u+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}return o}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function aW(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=eW(e,0),n=eW(e,4),a=[];for(let l=0;l<4;l++)a[l]=eW(t,4*l);let s=0;for(let l=0;l<16;l++)s+=oW,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;ZH(i,o,r),ZH(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var sW=function(){return Date.now()+0},lW=function(){let e=new Date;return e.setTime(sW()),e.toLocaleString()};function cW(e){let t=function(e){try{let t={},i=0;t.totalLength=eW(e,i),i+=4,t.version=eW(e,i),i+=4,t.encryption=tW(e,i),i+=1,t.uinType=tW(e,i),i+=1,t.uinLength=eW(e,i),i+=4,t.uin=t.uinLength>4?iW(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),o=dW(new Uint8Array(e.slice(0,8)),t),n=7&o[0],a=e.length-1-n-2-7,s=new Uint8Array(a),l=0,c=r,d=e.slice(0,8);i=8;let u=1;u+=n;for(let p=1;p<=2;)if(u<8)u++,p++;else if(8===u){let r=uW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}let h=a;for(;h>0;)if(u<8)s[l++]=o[u]^c[u],u++,h--;else if(8===u){let r=uW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}for(let p=1;p<=7;)if(u<8)o[u],c[u],u++,p++;else if(8===u){if(i>=e.length)break;let r=uW(e,i,c,d,o,t);if(!r.success)break;c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}return s}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=eW(e,i),i+=4,t.seqNo=eW(e,i),i+=4,t.retCode=eW(e,i),i+=4,t.retStrLength=eW(e,i),i+=4,t.retStr=t.retStrLength?iW(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=eW(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?iW(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=eW(e,i),i+=4,t.cookie=t.cookieLength?iW(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=eW(e,i),i+=4,t.busiBuffLength=eW(e,i),i+=4,t.busiBuff=t.busiBuffLength?iW(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function dW(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 o=16*oW>>>0;for(let n=0;n<16;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=oW,o>>>=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 uW(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:dW(l,n),bufPos:t+8}}var hW="undefined"!=typeof TextDecoder?new TextDecoder:void 0;var pW=Object.prototype.hasOwnProperty,mW=e=>"function"==typeof e,fW=e=>void 0===e;function _W(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(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)}(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(pW.call(e,t))return!1;return!0}return!1}var gW=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>nw(this,null,(function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(mW(d)?d():d)?(h++,m=1,mW(o)&&o.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,i)}),mW(u)?u(h):u)):(t(),mW(n)&&n.call(this,_))};mW(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}}));return new Promise(f)}},EW=class e{constructor(e){IH(this,"_parentPath"),IH(this,"userId"),IH(this,"remoteUserId"),IH(this,"id"),IH(this,"sdkAppId"),IH(this,"type"),IH(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:fW(t.userId)?this.userId:t.userId,sdkAppId:fW(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:fW(t.type)?this.type:t.type,isLocal:fW(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:fW(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),SG.log(e,t,fW(this.userId)||_W(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)}},vW="undefined"==typeof navigator?"":navigator.userAgent,yW=e=>new RegExp(e,"i").test(vW),TW=e=>{if(yW(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=vW.match(t);if(i&&i[1])return i[1]}return""},IW=e=>{if(yW(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=vW.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},AW=/AppleWebKit\/([\d.]+)/i.exec(vW);AW&&parseFloat(AW[1]);var SW=yW("iPad"),RW="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&yW("Macintosh"),bW=yW("iPhone")&&!SW,wW=yW("iPod"),CW=bW||SW||wW||RW,DW=yW("Android");!function(){if(DW){let e=vW.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}}}();DW&&yW("webkit");var NW=yW("Firefox"),kW=TW("Firefox");IW("Firefox");var OW=yW("Edge"),MW=TW("Edge"),PW=yW("Edg"),LW=TW("Edg");IW("Edg");var xW=yW("SogouMobileBrowser"),UW=TW("SogouMobileBrowser"),VW=yW("MetaSr\\s"),FW=TW("MetaSr\\s"),BW=yW("TBS"),HW=TW("TBS"),WW=yW("XWEB"),GW=TW("XWEB");yW("MSIE\\s8\\.0");var jW=yW("MSIE\\/\\d+");!function(){if(jW){let e=/MSIE\s(\d+)\.\d/.exec(vW),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(vW)&&/rv:11.0/.test(vW)&&(t=11),t}}();var zW=yW("(micromessenger|webbrowser)"),KW=TW("MicroMessenger"),qW=!BW&&yW("MQQBrowser")&&yW("COVC"),YW=!BW&&yW("MQQBrowser")&&!yW("COVC"),JW=YW||qW?TW("MQQBrowser"):"",XW=!BW&&yW(" QQBrowser"),QW=TW(" QQBrowser"),$W=!BW&&yW("QQBrowserLite"),ZW=TW("QQBrowserLite"),eG=!BW&&yW("MQBHD"),tG=TW("MQBHD");yW("Windows"),!CW&&yW("MAC OS X"),!DW&&yW("Linux"),yW("CrOS"),yW("MicroMessenger"),yW("UCBrowser"),yW("Electron");var iG=yW("MiuiBrowser"),rG=TW("MiuiBrowser"),oG=yW("HuaweiBrowser");yW("Huawei")||yW("HUAWEI"),yW("Honor")||yW("HONOR");var nG=TW("HuaweiBrowser"),aG=yW("SamsungBrowser"),sG=TW("SamsungBrowser"),lG=yW("HeyTapBrowser"),cG=TW("HeyTapBrowser"),dG=yW("VivoBrowser"),uG=TW("VivoBrowser");yW("OpenHarmony"),TW("OpenHarmony");var hG=yW("CriOS"),pG=yW("Chrome"),mG=!OW&&!VW&&!xW&&!BW&&!WW&&!PW&&!XW&&!iG&&!oG&&!aG&&!lG&&!dG&&pG,fG=yW("HeadlessChrome");IW("Chrome");var _G=TW("Chrome");IW("Electron");var gG=!pG&&!YW&&!qW&&!$W&&!eG&&yW("Safari"),EG=TW("Version");/Android.*(wv|.0.0.0)/.test(vW);var vG=(()=>{if(RW)return EG;if(CW){let e=vW.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();Number(vG.split(".")[0]),(()=>{let e=Number(vG.split(".")[0])})(),function(){let e=new Map([[NW,["Firefox",kW]],[PW,["Edg",LW]],[mG,["Chrome",_G]],[hG,["ChiOS",TW("CriOS")]],[gG&&!hG,["Safari",EG]],[BW,["TBS",HW]],[WW,["XWEB",GW]],[zW&&bW,["WeChat",KW]],[XW,["QQ(Win)",QW]],[YW,["QQ(Mobile)",JW]],[qW,["QQ(Mobile X5)",JW]],[$W,["QQ(Mac)",ZW]],[eG,["QQ(iPad)",tG]],[iG,["MI",rG]],[oG,["HW",nG]],[aG,["Samsung",sG]],[lG,["OPPO",cG]],[dG,["VIVO",uG]],[OW,["EDGE",MW]],[xW,["SogouMobile",UW]],[VW,["Sogou",FW]]]),t="unknown",i="unknown";e.has(!0)&&([t,i]=e.get(!0))}();var yG=new(yH(AH(),1).default),TG=HH,IG=new class{constructor(){IH(this,"enable",!1),IH(this,"ssoFailCount",0),yG.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&yG.emit("266",{enable:!0})})),yG.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&yG.emit("266",{enable:!1})}},AG=class e{constructor(){IH(this,"_isEnableUploadLog",!0),IH(this,"_localJoinedUser",new Map),IH(this,"_queue",[]),IH(this,"_timeoutId",-1),IH(this,"_logLevel",1),IH(this,"_logLevelToUpload",2),WH||GH||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){yG.on(TG.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&zH[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),yG.on(TG.JOIN_START,(e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),yG.on(TG.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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})}));else if(wG(i.userId)&&CG(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 nw(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:o}=t[e],n={timestamp:lW(),sdkAppId:String(r),userId:i,version:"5.0.0",log:o.map((e=>e.log)).join("\n")},a=JSON.stringify(n),s=IG.enable?DG(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach((e=>e.uploaded=!0))}}catch(cM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return gW({retryFunction:()=>function(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise(((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:cW(new Uint8Array(e))||(hW?hW.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(hM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)}))}({url:RG(t,jH),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&(IG.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(sW()),"[".concat(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)}(t),"] <").concat(zH[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){bG(zH[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(wG(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Sw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=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:r,sdkAppId:o,forAllJoinedClients:i};yG.emit(TG.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(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(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=zH[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",...i):console[s](...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){if(e.parent instanceof EW){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)fH.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&pH)for(var r of pH(e))t.indexOf(r)<0&&_H.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new EW(r);return o.bindParent(i),o}return new EW(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zH[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};IH(AG,"PRINT_LOG_TAG",!(CW||DW||fG));var SG=new AG,RG=function(e,t){let i;return i=(e=>Number(e)<14e8)(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com","".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(Math.floor(Math.random()*Jb(2,31)),"&sdkappid=").concat(e,"&cmdtype=").concat(t)},bG=e=>void 0===e,wG=e=>"string"==typeof e,CG=e=>"number"==typeof e;function DG(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return bG(r)||(o=vH(EH({},o),{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(o)}}}(e,t,i,r);return nW(QH(o),i)}catch(cM){return JSON.stringify(e)}}var NG=class e{constructor(e){this.core=e,IH(this,"contextMap",new Map),IH(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 i;switch(e){case"wasm":let e=(null==(i=this.core.assetsPath)?void 0:i.replace(/\/+$/,""))||".";return new BH(vH(EH({},t),{wasmPath:"".concat(e,"/videodec.wasm")}));case"webCodecs":return new PH;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:i}=e;var r;return(null==(r=this.decodeProcessorMap.get(i))?void 0:r({frame:t,track:i}))||t},type:3})}decode(e){let{pipe:t,take:i,subscribe:r}=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(vH(EH({},e),{createDecoder:this.createDecoder}));return t(s.trackDoneOB,i(1),r((()=>{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 i=(performance&&performance.now?Math.floor(performance.now()):Date.now())-e.startPerformanceTime,{renderFreezeTotal:r,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):"");i&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(r/i*100),split:1,max:100}),n+=" RENDER_FREEZE_RATE: ".concat(Math.floor(r/i*100),"%")),i&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(o/i*100),split:1,max:100}),n+=" DATA_FREEZE_RATE: ".concat(Math.floor(o/i*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(vH(EH({},e),{createDecoder:this.createDecoder})))):t.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(e,t){let i=this.core.room.badCaseDetector.getDataFreezeMap().get("".concat(e.userId,"_").concat(e.streamType)),r=this.core.room.badCaseDetector.getRenderFreezeDuration("".concat(e.userId,"_").concat(e.streamType)),o=0;return i&&i.durationItemList.forEach((e=>{e.startTime>t.startPerformanceTime&&(o+=e.getDuration())})),{renderFreezeTotal:r,dataFreezeTotal:o}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};IH(NG,"Name","TRTCVideoDecoder");var kG=NG,OG=tw(aw());function MG(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return OU(((e,o)=>{let n=new WeakMap;return JO.on(QO.ROOM_DESTROY,(e=>{let{room:t}=e;return n.delete(t)})),function(){let a=n.get(this);for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];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),r&&(a.totalSizeInSecond+=r(...l)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>i))throw new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>i,name:o,timesInSecond:t,maxSizeInSecond:i}})});a.callCountInSecond++,e.call(this,...l)}}))}var PG,LG=!0,xG={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"},UG={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},VG=((PG=VG||{})[PG.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",PG[PG.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",PG[PG.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",PG[PG.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",PG[PG.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",PG[PG.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",PG[PG.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",PG[PG.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",PG[PG.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",PG[PG.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",PG[PG.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",PG[PG.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",PG[PG.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",PG[PG.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",PG[PG.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",PG[PG.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",PG[PG.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",PG[PG.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",PG[PG.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",PG[PG.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",PG[PG.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",PG[PG.INVALID_OPERATION=5100]="INVALID_OPERATION",PG[PG.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",PG[PG.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",PG[PG.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",PG[PG.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",PG[PG.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",PG[PG.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",PG[PG.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",PG[PG.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",PG[PG.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",PG[PG.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",PG[PG.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",PG[PG.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",PG[PG.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",PG[PG.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",PG[PG.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",PG[PG.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",PG[PG.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",PG[PG.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",PG[PG.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",PG[PG.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",PG[PG.DEVICE_ERROR=5300]="DEVICE_ERROR",PG[PG.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",PG[PG.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",PG[PG.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",PG[PG.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",PG[PG.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",PG[PG.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",PG[PG.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",PG[PG.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",PG[PG.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",PG[PG.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",PG[PG.SERVER_ERROR=5400]="SERVER_ERROR",PG[PG.NEED_TO_BUY=5401]="NEED_TO_BUY",PG[PG.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",PG[PG.OPERATION_FAILED=5500]="OPERATION_FAILED",PG[PG.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",PG[PG.REJOIN_FAILED=5502]="REJOIN_FAILED",PG[PG.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",PG[PG.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",PG[PG.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",PG[PG.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",PG[PG.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",PG[PG.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",PG[PG.OPERATION_ABORT=5998]="OPERATION_ABORT",PG[PG.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",PG);var FG=$b(Qb({},hP),{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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},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=BG(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=BG(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=BG(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=BG(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=BG(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=BG(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=BG(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 BG(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var HG=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:o,fnName:n="",originError:a,data:s}=e;var l;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:o=!1}=e,a="",s=VG[i];try{t=FG[s]}catch(n){t=FG.UNKNOWN_ERROR}return GD(t)?a=t(r):zD(t)&&(a=t),r.fnName&&!a.includes(r.fnName)&&("."!==a[a.length-1]&&(a+="."),a+=" thrown from ".concat(r.fnName,"()")),o&&(a+=" doc:"),a}({code:t===UG.SERVER_ERROR?t:i||t,params:Qb({fnName:n,error:a},o)}),super(c),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=VG[t],this.code=t,this.extraCode=i,this.functionName=n,this.originError=a,this.message=c,this.data=s,5302===this.extraCode&&null!=(l=this.originError)&&l.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");Gk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):jk&&(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 o=t;if(t instanceof mw){let{stack:n}=t,a={code:UG.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case hw.INVALID_PARAMETER:a.code=UG.INVALID_PARAMETER,a.message=t.message;break;case hw.INVALID_OPERATION:a.code=UG.INVALID_OPERATION;break;case hw.NOT_SUPPORTED:case hw.NOT_SUPPORTED_H264:a.code=UG.ENV_NOT_SUPPORTED,t.getCode()===hw.NOT_SUPPORTED_H264&&(a.extraCode=t.message.includes(hP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case hw.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case hw.SERVER_TIMEOUT:case hw.SWITCH_ROLE_FAILED:case hw.SWITCH_ROOM_FAILED:a.code=UG.SERVER_ERROR,a.extraCode=t.getExtraCode();break;case hw.API_CALL_ABORTED:a.code=UG.OPERATION_ABORT;break;case hw.DEVICE_NOT_FOUND:case hw.DEVICE_AUTO_RECOVER_FAILED:case hw.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 hw.VIDEO_ENCODE_FAILED:a.extraCode=5505;case hw.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=UG.OPERATION_FAILED;break;case hw.UNKNOWN:break;default:a.code=UG.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:UG.UNKNOWN_ERROR,fnName:i,originError:t})}return o}};var WG=HG;function GG(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function jG(e){return e===xG.QOS_PREFERENCE_CLEAR?"detail":e===xG.QOS_PREFERENCE_SMOOTH?"motion":""}function zG(e,t){let i=t?$w:Qw;return qN(e)?Qb(Qb({},i),e):Xw[e]?Xw[e]:i}var KG={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}}},qG={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}}},YG={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(zD(e)&&!document.getElementById(e))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},JG={name:"userId",required:!0,type:"string"},XG={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 QG(e,t){if(!e)throw new WG({code:UG.INVALID_OPERATION,extraCode:5101,fnName:t})}function $G(e,t,i){if(!e)throw new WG({code:UG.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function ZG(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function ej(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function tj(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!tL())return eM.warn("small stream is not supported"),void delete e.option.small;let i=zG(e.option.profile),r=zG(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:(eM.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 ij={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 WG({code:UG.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(zD(e.roomId))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});ZG(e.roomId,i,t)}else{if(!e.strRoomId)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5015,fnName:i});ej(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:YG,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:KG},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&tj(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:$b(Qb({},YG),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:KG},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&tj(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:XG},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:XG}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:YG,publish:{type:"boolean"},option:qG},validate(e,t,i,r,o){var n;if(null==(n=null==e?void 0:e.option)||!n.videoTrack){if(xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201});if(!GP())throw new WG({code:UG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:YG,publish:{type:"boolean"},option:qG}},muteRemoteAudio:[JG,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[JG,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:YG,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){QG(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if($G(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new WG({code:UG.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:$b(Qb({},YG),{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){QG(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if($G(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new WG({code:UG.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&&jD(e.streamType))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){QG(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(!EL)throw new WG({code:UG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new WG({code:UG.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});QG(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 WG({code:UG.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 WG({code:UG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(QG(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new WG({code:UG.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(QG(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new WG({code:UG.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 WG({code:UG.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)ZG(e.roomId,i,t);else{if(!e.strRoomId)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5015,fnName:i});ej(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}}}},rj={TRTC:ij},oj=class extends Error{};function nj(e,t){let i=pN(e);for(let r=0;r<t.length;r++)hN(i[r],t[r]);return i}function aj(e){this._resolve=Promise.resolve(e)}function sj(e){this._reject=Promise.reject(e)}var lj=class e{constructor(t,i){this.instance=t,this.group=i,rw(this,"started",!1),rw(this,"ops",[]),rw(this,"startSame",(()=>!0)),rw(this,"mergeUpdate",nj);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),o=[];return r&&r.forEach(((e,t)=>{i.test(t)&&o.push(e)})),o}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},o=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new oj("start failed")),null==(r=this.currentOp)||r.action(),t},n={type:e,action:()=>t(...n.args).then(r,o),args:i,resolve:aj,reject:sj};try{switch(this.state){case 1:if(0===e)throw new oj("already started");break;case 4:if(2===e)throw new oj("not started");break;default:return this.cacheOp(n)}}catch(dM){return Promise.reject(dM)}return this.ops.push(n),n.promise=t(...n.args).then(r,o)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new oj("already start");break;case 3:switch(e.type){case 2:throw new oj("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new oj("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new oj("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 oj("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new oj("start not allowed after update");case 0:throw new oj("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new oj("keep start")),new oj("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}};rw(lj,"instances",new WeakMap);var cj=lj,dj=new WeakMap,uj=(e,t)=>{if(t instanceof oj){let{stack:i}=t;t=new WG({code:UG.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function hj(e,t){return OU(((i,r)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let s=cj.get(this,"string"==typeof e?e:e.call(this,...n));return s?(t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),n).catch(uj.bind(null,r))):i.apply(this,n)}))}function pj(e,t){let{merge:i,debounce:r}=t||{};return OU(((t,o)=>function(){for(var n=arguments.length,a=new Array(n),s=0;s<n;s++)a[s]=arguments[s];let l=cj.get(this,"string"==typeof e?e:e.call(this,...a));if(!l)return t.apply(this,a);if(i&&(l.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:e,getKey:i}=r;return new Promise(((r,n)=>{var s,c;let d=null==(s=dj.get(this))?void 0:s.get(i(...a));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===l.state||4===l.state)return r();l.action(2,t.bind(this),a).catch(uj.bind(null,o)).then(r,n)}),e);dj.has(this)?null==(c=dj.get(this))||c.set(i(...a),{timeoutId:u,resolve:r}):dj.set(this,new Map([[i(...a),{timeoutId:u,resolve:r}]]))}))}return l.action(2,t.bind(this),a).catch(uj.bind(null,o))}))}function mj(e){return OU(((t,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a="function"==typeof e?e.call(this,...o):e;if(a instanceof RegExp)return Promise.all(cj.gets(this,a).map((e=>e.action(3,(()=>Promise.resolve()),o)))).then((()=>t.call(this,...o)));let s=cj.get(this,a);return s?s.action(3,t.bind(this),o).catch(uj.bind(null,i)):t.apply(this,o)}))}function fj(){return function(e,t,i){return e.prototype[t]=function(){let e=this._log||console,i='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(Lw,"/en/TRTC.html#.").concat(t);e.warn(i)},i}}var _j={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"},gj=new Set([_j.AUDIO_VOLUME,_j.AUDIO_FRAME,_j.NETWORK_QUALITY,_j.STATISTICS,_j.SEI_MESSAGE,_j.CUSTOM_MESSAGE,_j.LAYER_DATA]),Ej={};ew(Ej,{ScheduleRequestType:()=>wj,getAbilityConfig:()=>Dj,getScheduleDomain:()=>Nj,isNeedToSchedule:()=>Ij,scheduleProxy:()=>Rj,sendScheduleRequest:()=>Sj,setIsNeedToSchedule:()=>Aj,setScheduleProxy:()=>bj});var vj=null,yj=0,Tj=1728e5,Ij=!0;function Aj(e){qD(e)&&e!==Ij&&(Ij=e,eM.info("setIsNeedToSchedule ".concat(e)),e||(yj=Date.now()+Tj))}function Sj(e){return nw(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:o,userSig:n,version:a,frameWorkType:s,role:l,latencyLevel:c}=e;return function*(){var e;if(!Ij&&vj&&yj>Date.now())return{isCached:!0,result:vj};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(o)),u.append("sdkVersion",a),u.append("userSig",String(n));let h=(null==(e=yield UO())?void 0:e.model)||BO();h&&u.append("model",h);let p=zO();p&&u.append("osString",p),l&&u.append("role",String(l)),c&&u.append("latencyLevel",String(c)),s&&u.append("frameWorkType",String(s));let m=oN(),f=yield function(e,t,i){return new Promise(((r,o)=>{let n=null;rN([Oj((e=>t.count[0]=e+1),(e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[0]=r.message,n||(a>=1&&(s[0]=Cj(i,"config",eC.MAIN,!0)),o())}))(Cj(i,"config",eC.MAIN),e,{get timeout(){return 1e3*BD(2+t.count[0])}}),Oj((e=>t.count[1]=e+1),(e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[1]=r.message,n||(a>=2&&(s[0]=Cj(i,"config",eC.BACKUP,!0)),o())}))(Cj(i,"config",eC.BACKUP),e,{get timeout(){return 1e3*BD(2+t.count[1])}})]).then((e=>{n=e,r(n)})).catch(o)}))}(u,d,i);f.config&&(f.config.loggerDomain&&Nw(f.config.loggerDomain),qD(f.config.scheduleCache)&&Aj(!f.config.scheduleCache)),d.delta=oN()-m;let _=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),n=Cj(e,"config",eC.MAIN),a=Cj(e,"config",eC.BACKUP);for(let e of o)if(e.startTime>=i&&(e.name===n||e.name===a)&&e.transferSize>0){let i=e.name===n?eC.MAIN:eC.BACKUP,o=Math.round(e.duration),a=Math.round(e.domainLookupStart-e.startTime),s=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,l=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,c=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=[c,d,u,h,p];rx.uploadEvent({log:"stat-schedule-net:".concat(o,"(").concat(a,"(").concat(s,"->").concat(l,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=$b(Qb({},r),{totalCost:o,local:a,dns:c,tcp:u,tls:d,request:h,response:p});break}}catch(n){eM.error("getScheduleDetailCost error",n)}return r}(Number(i),t,m);return vj=f,{isCached:!1,result:f,detailCost:_}}catch(nM){let t=JD(nM)?nM[0]:nM,i=KD(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),o=new mw({code:hw.SCHEDULE_FAILED,extraCode:i,message:fP({key:uP.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw eM.error(r,i),o}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(GC).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),JO.on("28",(()=>Aj(!0))),JO.on("63",(()=>Aj(!0))),JO.on("84",(()=>Aj(!0))),JO.on("201",(e=>{"RECONNECTING"===e.state&&Aj(!0)})),JO.on("202",(e=>{"RECONNECTING"===e.state&&Aj(!0)}));var Rj={main:"",backup:""};function bj(e){JD(e)?(Rj.main=e[0],Rj.backup=e[1]):Rj.main=e}var wj=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(wj||{});function Cj(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eC.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(Rj[i]||Nj(e,i,r),"/api/v1/").concat(t)}function Dj(e,t,i){let r=Cj(e,t),o=Cj(e,t,eC.BACKUP),n=new URLSearchParams(i).toString(),a=fetch("".concat(r,"?").concat(n)).then((e=>e.json())),s=fetch("".concat(o,"?").concat(n)).then((e=>e.json()));return rN([a,s])}function Nj(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=AD(e)?r?i===eC.MAIN?GC.MAIN_OVERSEA_BACKUP:GC.BACKUP_OVERSEA:i===eC.MAIN?GC.MAIN_OVERSEA:GC.BACKUP_OVERSEA:i===eC.MAIN?GC.MAIN:GC.BACKUP,t}function kj(e,t,i){return new Promise(((r,o)=>{HN({url:e,body:t,timeout:i.timeout,priority:"high"}).then((e=>{0===e.data.code?r(e.data.data):o({code:e.data.code,message:e.data.msg})})).catch(o)}))}var Oj=(e,t)=>YN({retryFunction:kj,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var Mj=class{constructor(){rw(this,"_log"),this._log=eM.createLogger({id:"fd"})}download(e,t){return nw(this,null,(function*(){let{type:i="blob"}=t||{};e=bN(e);try{let t,r=oN();if(t=GD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let o=oN()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(o,"ms")),CP.addSuccessEvent({key:522700,cost:oN()-r}),t.data}catch(cM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(cM)),CP.addFailedEvent({key:522700,error:cM}),cM}}))}downloadWithFetch(e,t){return nw(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(CC){throw CC}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType=t,o.onload=()=>{if(200===o.status||0===o.status&&o.response)i({data:o.response});else{let e=new Error("XHR failed, status: ".concat(o.status));e.status=o.status,r(e)}},o.onerror=r,o.send(null)}))}loadWasm(e,t){return nw(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=oN(),r=null,o=null;if(GD(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&GD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Rw){o=Rw}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Rw){o=Rw}if(r){let t=oN()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),CP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(o)),CP.addFailedEvent({key:522701,error:o}),o}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=oN();return new Promise(((i,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(oN()-t,"ms")),CP.addSuccessEvent({key:522702,cost:oN()-t,split:1e3}),i(o)},o.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),CP.addFailedEvent({key:522702}),r(t)},o.crossOrigin="anonymous",o.src=e,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)}))}};iw([nx({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))}})],Mj.prototype,"download",1),iw([nx({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],Mj.prototype,"loadScript",1);var Pj=new Mj;function Lj(e){let[t,i]=e,r=i.byteLength,o=parseInt(String(r/255),10),n=r%255,a=[];a.push(0,0,0,1,6,t);for(let l=0;l<o;l++)a.push(255);a.push(n);let s=new DataView(i);return a.push(...new Uint8Array(s.buffer)),a.push(128),new hB(new DataView(new Uint8Array(a).buffer),!0)}function xj(e){return"empty"===e.type||0===e.data.byteLength}function Uj(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let e=dB(t,i);if(0===e){i+=1;continue}let r=i+e;if(r<t.byteLength&&6==(31&t.getUint8(r)))return!0;i+=e+1}return!1}function Vj(e){let t=0,i=0,r=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function Fj(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-Vj(t.data);if(r<=0)return t;let o=i.splice(0,r).reverse().map(Lj),n=o.reduce(((e,t)=>e+t.dataView.byteLength),0),a=new ArrayBuffer(n+t.data.byteLength),s=new DataView(a),l=new DataView(t.data),c=0;for(let d=0;d<o.length;d++)for(let e=0;e<o[d].dataView.byteLength;e++)s.setInt8(c++,o[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)s.setInt8(c++,l.getInt8(d));return t.data=a,t}function Bj(e){let{frame:t,onSEI:i}=e;try{if(xj(t)||!Uj(t.data))return t;let e=uB(t.data,!1).filter((e=>e.isSEI));null==i||i(e.reverse())}catch(Sw){}return t}function Hj(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:o}=e;return new TransformStream({transform(e,n){let a=e;i?audioEncodePipeline.forEach((e=>{a=e({frame:a,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:""})}})})):videoEncodePipeline.forEach((e=>{a=e({frame:a,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:"",streamType:o?"main":"auxiliary"})}})})),n.enqueue(a)}})}function Wj(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(e,o){let n=e;r?(audioDecodePipeline.forEach((e=>{n=e({frame:n,onAudioFrameNTPTime:e=>{self.postMessage({type:"audio-ntp",data:e,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t})}})})),o.enqueue(n)):videoDecodePipeline.forEach((e=>{n=e({frame:n,onSEI:e=>{e.forEach((e=>{self.postMessage({type:"sei",seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t,streamType:i})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t,streamType:i})}})})),o.enqueue(n)}})}function Gj(e){let t=[hB],i=[Vj,xj,uB,Uj,Lj,Hj,Wj,LN,PN],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(),"];"),o="(()=>{".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=o=>{switch(o.data.type){case"sei":o.data.isMain?(e.push(o.data.data),o.data.small&&i.push(o.data.data)):t.push(o.data.data);break;case"ntp-offset":r=o.data.data}},self.onrtctransform=o=>{let{options:n}=o.transformer,a=n.isReceiver?Wj({userId:n.userId,streamType:n.streamType,isAudio:n.isAudio}):Hj({getNtpTime:()=>Date.now()+r,isAudio:n.isAudio,isMain:n.isMain,seiMessageList:n.isMain?n.small?i:e:t});o.transformer.readable.pipeThrough(a).pipeTo(o.transformer.writable)}}),")();").concat(r,"})()"),n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),s=new Worker(a);return URL.revokeObjectURL(a),s}var jj,zj=!1;function Kj(e){var t=this;let{TRTC:i,room:r,errorModule:o,assetsPath:n}=e;return{TRTC:i,LocalMixVideoTrack:WB,LocalVideoTrack:fB,LocalScreenTrack:zB,room:r,assetsPath:n,fileDownloader:Pj,innerEmitter:JO,INNER_EVENT:QO,constants:yw,environment:XN,utils:_B,eventLogger:rx,log:this.room.getLogger(),loggerManager:eM,errorModule:o,kvStatManager:CP,rtcDectection:rM,trtc:this,rx:HU,enums:oM,schedule:Ej,getDevices:uU,initVisionTaskRegistry:function(e,i){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/mediapipe/vision.js";return nw(t,null,(function*(){!window.VisionTaskRegistry&&!zj&&(zj=!0,jj=Pj.loadScript("".concat(e,"/").concat(r).replace(/([^:]\/)\/+/g,"$1"))),yield jj,yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels(i)}))},audioContext:qx(),deviceDetector:cU,AudioPlayer:yU,RemoteAudioPlayer:IU,VideoPlayer:Ox,showAutoPlayDialog:Nx,Timer:QL,clearStarted:(e,t)=>{let i=e.getAlias(),r=cj.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:YB,createAudioNode:eU,getNetworkTimeOffset:fw,validateSourceNode:()=>{var e;if(pk&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new WG({code:UG.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."})},createScriptTransformWorker:Gj}}var qj=new WeakMap;var Yj="5.15.0-wasm.1";function Jj(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{Qj.call(this,t,o,i,this._name)}catch(cM){return Promise.reject(cM)}return e.apply(this,o)}))}function Xj(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{Qj.call(this,t,o,i,this._name)}catch(cM){throw cM}return e.apply(this,o)}))}function Qj(e,t,i,r){if(JD(e))for(let o=0;o<e.length;o++)$j.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else $j.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function $j(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;function a(e){return{code:UG.INVALID_PARAMETER,extraCode:e,fnName:o,messageParams:{key:r,rule:t,value:i}}}if(jD(i)){if(t.required)throw new WG(a(5001));if(jD(t.defaultValue))return void(GD(t.validate)&&t.validate.call(this,i,r,o,n,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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),zD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5002,fnName:o,messageParams:{key:r,rule:{type:t.type.map((e=>ZD(e)?eN(e):zD(e)?e:WD(e)))},value:i}})}else if(!jD(t.type)&&WD(i)!==t.type)throw new WG(a(5002));if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),t=zD(i)&&""===i.trim();if(e||t)throw new WG(a(5003))}if(t.notLessThanZero&&KD(i)&&i<0)throw new WG(a(5006));if(!jD(t.min)&&KD(i)&&i<t.min)throw new WG(a(5007));if(!jD(t.max)&&KD(i)&&i>t.max)throw new WG(a(5008));if(zD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new WG(a(5004))}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new WG(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new WG(a(5005));let{properties:s}=t;FD(s)&&YD(i)&&Object.keys(s).forEach((e=>{$j.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:o,className:n})}));let{arrayItem:l}=t;FD(l)&&JD(i)&&i.forEach(((e,t)=>{$j.call(this,{rule:l,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})})),GD(t.validate)&&t.validate.call(this,i,r,o,n,this)}var Zj=0;function ez(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:n}=e;return OU(((e,a)=>function(){for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...l);if(l[e.argIndex]===t)return e.value}if(t===l||e in l)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(WD(t)):t instanceof MediaStreamTrack?wN(t):(JSON.stringify(t),t)}catch(o){return"type:".concat(WD(t))}}let m=(null==this?void 0:this._log)||eM,f=++Zj;if(null!=o&&o(...l))return e.apply(this,l);l.length>0?m.info("".concat(a,"() ").concat(f," ").concat(JSON.stringify(l,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(a,"() ").concat(f));let _=r?r(...l):TP[a],g=(null==n?void 0:n(...l))||!1;try{let i=e.apply(this,l),r=oN();if($D(i)){let e="".concat(a.includes("Plugin")?"".concat((null==(u=(d=l[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then((i=>(m.info("".concat(a,"() success ").concat(f," ").concat(e).concat(t.call(this,...l))),CP.addSuccessEvent({key:_,cost:oN()-r}),i))).catch((i=>{var r;let o=(i=WG.convertFrom.call(this,i,a,1===l.length?l[0]:l)).extraCode||i.code,n=null!=(r=i.message)&&r.includes(o)?"":" code:".concat(o),s=(null==i?void 0:i.code)===UG.OPERATION_ABORT;throw g||m[s?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(e).concat(t.call(this,...l)," ").concat(i).concat(n," params: ").concat(JSON.stringify(l,p))),CP.addFailedEvent({key:_,error:i}),i}))}return CP.addSuccessEvent({key:_}),i}catch(E){let e=(E=WG.convertFrom.call(this,E,a)).extraCode||E.code,t=null!=(h=E.message)&&h.includes(e)?"":" code:".concat(e),i=(null==E?void 0:E.code)===UG.OPERATION_ABORT;throw g||m[i?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(E).concat(t," params: ").concat(JSON.stringify(l,p))),CP.addFailedEvent({key:_,error:E}),E}}))}var tz,iz=e=>OU(((t,i)=>function(r,o){return nw(this,null,(function*(){let n=this._plugins.get(r);if(!n)throw this._log.error("plugin ".concat(String(r)," is not found")),new WG({code:UG.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(GD(n.constructor.isSupported)&&!n.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new WG({code:UG.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return Qj.call(this,n.getValidateRule(e),[o],i,"TRTC"),t.call(this,n,o)}))})),rz=0,oz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"customAudioReferenceMap",new Map),rw(this,"audioRefId",0),rw(this,"audioContext",qx()),rw(this,"localAudioWorkletNode"),rw(this,"screenAudioWorkletNode"),rw(this,"mixNode"),rw(this,"silentNode"),rz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(rz)}),this.log.info("created id=".concat(this.getAlias()).concat(rz)),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,o){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new WG({code:UG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return tz||(tz=this.doPreload(e)),tz}doPreload(e){return nw(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Mx(this.audioContext,i)}catch(cM){this.log.error("preload audioProcessor failed. ".concat(cM))}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 nw(this,null,(function*(){var t,i,r,o;let{room:n}=this.core,{sdkAppId:a,userId:s,userSig:l,assetsPath:c=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,!c)throw new WG({code:UG.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(c,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",a,s,i,e,t,n)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",a,s,i,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==(i=this.screenAudioWorkletNode)||i.port.postMessage({type:"enable"}),n.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),jD(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++)})})),jD(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),jD(h)||null==(o=this.localAudioWorkletNode)||o.port.postMessage({type:"dump",data:{enable:h}})}))}update(e){return nw(this,null,(function*(){var t,i,r;let{audioReference:o,enableDump:n,processLevel:a}=e;jD(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++)})}))),jD(a)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),jD(n)||(null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:n}}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:n}}))}))}stop(){return nw(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 nw(this,null,(function*(){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:s}=yield function(e){return nw(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:o}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC.MAIN;return"https://".concat(Rj[t]||Nj(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(o),n=yield fetch(e),{data:{errCode:a,errMsg:s,sign:l,status:c}}=yield n.json();if("1"===c)return{auth:!0,sign:l,status:c,message:s};let d=AD(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:c,message:s?"".concat(u," Reason: ").concat(s,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}({sdkAppId:e,userSig:i,userId:t,timestamp:r});if(!o)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(o,". Message: ").concat(s)),new WG({code:UG.INVALID_PARAMETER,message:s});return{sign:n,status:a,timestamp:r}}))}initWorkletNode(e,t,i,r,o,n,a,s){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:o,sign:n,status:a}}),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(Ew(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 JO.emit("265",{room:s,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(e){return nw(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(CC){this.log.warn("audio processor auto start failed, error: ".concat(CC))}}))}handleLocalAudioStopped(e){return nw(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(oz,"updateValidateRule",{type:"object"}),rw(oz,"stopValidateRule",{type:"object"}),rw(oz,"Name","AudioProcessor");var nz=oz;var az=0,sz=class{constructor(e,t){rw(this,"audioObjectURL"),rw(this,"player"),rw(this,"publisher"),rw(this,"mixInput"),this.mixInput=new Qx(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&&(jD(e.volume)||(this.volume=e.volume),jD(e.loop)||(this.loop=e.loop),jD(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 nw(this,null,(function*(){if(e.url){let t=yield Pj.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 lz(e,t){if(t&&"function"!=typeof t)throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var cz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"mixedMusicMap",new Map),rw(this,"cacheMusicMap",new Map),az+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(az)}),this.log.info("created id=".concat(this.getAlias()).concat(az))}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 nw(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 o=this.cacheMusicMap.get(i);o?e.url?o.reset():(o.mixInput.replaceSource(e.track),o.mixInput.connect()):(o=new sz(e,t.audioManager),this.cacheMusicMap.set(i,o)),o.updateListener(e),o.updateSettings(e);try{yield o.play()}catch(Rw){yield this.handleAutoPlayFailed(o,e,Rw)}this.mixedMusicMap.set(i,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),CP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}handleAutoPlayFailed(e,t,i){return nw(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((()=>{JO.off("154",t,this)}))};JO.on("154",t,this),Nx()}else this.core.trtc.emit(_j.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>nw(this,null,(function*(){return e.play()}))})}}))}update(e){return nw(this,null,(function*(){let{id:t,operation:i,seekFrom:r,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),jD(i)||n.setOperation(i),jD(r)||n.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return nw(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:o,operation:n,seekFrom:a,onTimeUpdate:s,onDurationChange:l,onEnded:c}=e;t&&CP.addCount({key:502009}),i&&CP.addCount({key:502001}),r&&CP.addCount({key:502002}),o&&CP.addCount({key:502003}),n&&CP.addCount({key:502004}),a&&CP.addCount({key:502005}),"function"!=typeof s&&CP.addCount({key:502007}),"function"!=typeof c&&CP.addCount({key:502008}),"function"!=typeof l&&CP.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(cz,"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"],o=t.split(".").pop(),n=r.indexOf(o)>=0,a=t.startsWith("blob"),s=t.startsWith("data");if(!(n||a||s))throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});lz("onTimeUpdate",e.onTimeUpdate),lz("onEnded",e.onEnded),lz("onDurationChange",e.onDurationChange)}}),rw(cz,"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){lz("onTimeUpdate",e.onTimeUpdate),lz("onEnded",e.onEnded),lz("onDurationChange",e.onDurationChange)}}),rw(cz,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),rw(cz,"Name","AudioMixer");var dz,uz=cz,hz=0,pz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"audioContext",qx()),rw(this,"workletNode"),rw(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),hz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(hz)}),this.log.info("created id=".concat(this.getAlias()).concat(hz))}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,o){if(!e.room.audioManager.hasAudioTrack)throw new WG({code:UG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return dz||(dz=this.doPreload(e)),dz}doPreload(e){return nw(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Mx(this.audioContext,i)}catch(cM){throw this.log.error("load worklet failed",cM),cM}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 nw(this,null,(function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new WG({code:UG.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(AL()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield function(e,t){return nw(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:n,timestamp:a}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:s,status:l}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:n,timestamp:a});if("1"===l)return{auth:!0,sign:s,status:l,message:o};let c=AD(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(c);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(c);break;case 5:u="Your packages is expired. Refer to: ".concat(c);break;case 6:u="Your version is not supported."}return{auth:!1,status:l,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)}}}()}))}(i,$b(Qb({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(a)),new WG({code:UG.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: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(Ew(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 nw(this,null,(function*(){this.updateConfig(e)}))}stop(){return nw(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;jD(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),jD(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(pz,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),rw(pz,"stopValidateRule",{type:"object"}),rw(pz,"Name","AIDenoiser");var mz=pz;var fz=tw(aw(),1),_z=class extends fz.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 nw(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!ck&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Sw){rx.uploadEvent({log:"stat-pressure-detector-start-failed",error:Sw})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&eM.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(CC){rx.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:CC})}}},gz=new _z,Ez=0,vz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_subStreamSeiMessageList",[]),Ez++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Ez)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Ez)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return Fj({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(CC){this.log.warn(CC)}return t}decode(e){let{frame:t,track:i}=e;return Bj({frame:t,onSEI:e=>{e.forEach((e=>{null!=i&&i.userId?this.core.trtc.emit(_j.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:e})}))}})}destroy(){this.log.debug("destroy"),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:_L?this.encode:Fj,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:_L?this.decode:Bj,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 o=[i.seiPayloadType,t],n=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(o):(this._seiMessageList.push(o),n&&this._smallSeiMessageList.push(o)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:o,isMain:!i.toSubStream,small:n})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};rw(vz,"autoStart",!0),rw(vz,"Name","SEI");var yz,Tz=vz,Iz=0,Az=class e{constructor(e){this.core=e,rw(this,"_core"),rw(this,"log"),rw(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++Iz)}),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 nw(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())}))}update(e){return nw(this,arguments,(function(e){var t=this;let{visible:i}=e;return function*(){i?yield t.openDebugDiaLog():t.closeDebugDiaLog()}()}))}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return nw(this,null,(function*(){var e;if(!this.dialog)try{if(yz)yield yz;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(Iw,"/assets/debug-dialog.js");yz=this._core.fileDownloader.loadScript(t),yield yz}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(Sw){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Sw))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};rw(Az,"Name","Debug"),rw(Az,"autoStart",!0);var Sz=Az,Rz=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},bz=class{constructor(e,t,i){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:r,trtc:o}=e;this.config=i.config,this.trackDoneOB=OV(t,zL.INIT),this.stopOB=vV(),this.startOB=vV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let n=vV();$U(this.startOB,mV(0),kF((e=>{let i=this.pipe(t);return n.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),$U(i,eF(this.stopOB),tB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:Rz(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),$U(i,ZV(1),XF(jV))})),eF(this.stopOB),tB((()=>{t.player.setOutput(),n.next("STARTED")}),(e=>{n.next("FAILED")}),(()=>{r.addSuccessEvent({key:Rz(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 aV()((t=>nw(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(cM){e.log.error(cM),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"}))}},wz={type:"object"},Cz=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 wz}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 o=new bz(this.core,r,e);return $U(o.trackDoneOB,ZV(1),tB((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,o),o.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 bz(this.core,e.track,e))}}};rw(Cz,"Name","TRTCAudioDecoder");var Dz=Cz,Nz=class{constructor(){rw(this,"log"),this.log=eM.createLogger({id:"exp"})}call(e,t){return nw(this,null,(function*(){return GD(this[e])?this[e](t):Promise.reject(new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return nw(this,null,(function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=e,{audioManager:s}=t.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:c}=s;if(c.set(r,{enable:i,sampleRate:o,channelCount:n,port:a}),i)if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(l.get(e.userId))return;let i=s.getPCM((e=>{t.emit(_j.AUDIO_FRAME,e)}),e.userId);l.set(e.userId,i)}}));else{if(l.get(r))return;let e=s.getPCM((e=>{t.emit(_j.AUDIO_FRAME,e)}),r);l.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=l.get(t);null==i||i.abort("disable"),l.delete(t)}}));else{let e=l.get(r);null==e||e.abort("disable"),l.delete(r)}}))}resumeRemotePlayer(e){return nw(this,null,(function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach((i=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=i;e.streamType?"main"===e.streamType?(r.isAvailable&&t.push(r.player.resume()),o.isAvailable&&t.push(o.player.resume())):n.isAvailable&&t.push(n.player.resume()):(r.isAvailable&&t.push(r.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:i,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=t;e.streamType?"main"===e.streamType?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1)):o.isAvailable&&o.player.pause(!1):(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1),o.isAvailable&&o.player.pause(!1))}));else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}};iw([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return nH.call(this,t,o,i,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"}}})],Nz.prototype,"enableAudioFrameEvent",1);var kz=new Nz,Oz=tw(aw(),1),Mz=class extends Oz.EventEmitter{constructor(){super(),rw(this,"states",{}),rw(this,"permissionChangeHandler"),rw(this,"log"),this.log=eM.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 nw(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 nw(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(CC){return this.log.error("get ".concat(e," permission failed, error: ").concat(CC instanceof Error?CC.message:CC)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},Pz=new Mz,Lz=0,xz=new Set,Uz=null;Aw(Yj),iM.checkStorage();var Vz=class e extends OG.EventEmitter{constructor(t,i){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",eM.createLogger({id:"t".concat(++Lz)})),rw(this,"_plugins",new Map),rw(this,"_networkQuality",null),rw(this,"_speakerId"),rw(this,"enterRoomParams"),rw(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(Qb({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,qD(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(uz,i.assetsPath),this._use(nz,i.assetsPath),this._use(mz,i.assetsPath),this._use(Dz,i.assetsPath),this._use(Sz),i.enableSEI&&EL&&this._use(Tz),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(_j.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new WG({code:UG.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,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{return i.apply(e,o)}catch(cM){let i=fP({key:uP.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return eM.warn("".concat(i,"\n\n").concat(cM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(LG){LG=!1,5!==eM.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("******************************************************************************")),eM.info("TRTC Web SDK Version:",Iw),NO||eM.debug("Build Time:","2025-12-26 15:00:05");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(VO());if(sk&&window.screen&&(window.screen.width||window.screen.height)){let e="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);t+=", screen: ".concat(e)}let i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),eM.info(t),eM.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),UO().then((e=>{e&&eM.info(xO)}))}}();let r=new e(t,i||{});return xz.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tx(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(_j.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{let{userId:t,reason:i}=e;this.emit(_j.REMOTE_USER_EXIT,{userId:t,reason:i})})).add("banned",(e=>{Aj(!0),this._exitRoom().finally((()=>{this.emit(_j.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(_j.ERROR,WG.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(_j.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=$b(Qb({},e),{uplinkRTT:Math.min(e.uplinkRTT,tD),downlinkRTT:Math.min(e.downlinkRTT,tD)});this.emit(_j.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{tx(t,t).add("player-state-changed",(i=>{let r=$b(Qb({},i),{userId:e.userId});t.kind===eC.VIDEO&&(r.streamType=GG(t.streamType)),this.emit(t.kind===eC.AUDIO?_j.AUDIO_PLAY_STATE_CHANGED:_j.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===hw.PLAY_NOT_ALLOWED&&this.emit(_j.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{ix(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,o=t.audioAvailable,n=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=i;a||this._remoteAudioConfigMap.delete(r),s||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==s&&(s?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(s?_j.REMOTE_VIDEO_AVAILABLE:_j.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(a?_j.REMOTE_AUDIO_AVAILABLE:_j.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?_j.REMOTE_VIDEO_AVAILABLE:_j.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(_j.SEI_MESSAGE,$b(Qb({},e),{streamType:GG(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,o,n,a,s;let l={2:"big",3:"small",7:"sub"},c={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,tD),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)/XM},video:e.msg_up_stream_info.msg_video_status.filter((e=>l[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:l[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)/XM,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:l[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(_j.STATISTICS,c)})).add("custom-message",(e=>{this.emit(_j.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(_j.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},e),{streamType:GG(e.streamType)}))})).add("audio-frame",(e=>{this.emit(_j.AUDIO_FRAME,e)})),tx(this,cU).add("audioInputAdded",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>nw(this,null,(function*(){if(this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Uz&&Uz.deviceId===YC){let e=(yield fU()).find((e=>e.deviceId===YC));e&&Uz.groupId!==e.groupId&&(Uz=e,this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>nw(this,null,(function*(){this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield fU())[0];if(!t||!Uz||Uz.groupId===t.groupId)return;let i=Uz.deviceId===e.deviceId,r=Uz.deviceId===YC&&Uz.deviceId===t.deviceId;(i||r)&&(Uz=t,this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),tx(this,Pz).add("permission-state-change",(e=>{this.emit(_j.PERMISSION_STATE_CHANGE,e)})),this.room.enableSEI&&this.on(_j.SEI_MESSAGE,(e=>{var t;let i=null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteVideoTrack;i&&i.updateAlphaRenderInfo(e)}))}getNetworkTime(){return _w()}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 o=new t(Kj.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:WG,ErrorCode:UG,CoreErrorCode:hw,ErrorCodeDictionary:VG}}));return this._plugins.set(t.Name,o),o.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),o}enterRoom(t){return nw(this,null,(function*(){var i,r;this.enterRoomParams=t;let{scene:o="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:a=!0,autoReceiveVideo:s=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!zD(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=a,this._room.autoReceiveVideo=s,qD(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let l={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||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(l,o,e.frameWorkType),this._checkTrackToPublish(),gz.start()}))}exitRoom(){return nw(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return nw(this,null,(function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(CC){if(!(CC instanceof pw)||CC.code!==hw.API_CALL_TIMEOUT&&CC.code!==hw.SWITCH_ROOM_FAILED)throw CC;this._log.warn("switchRoom ".concat(CC.code===hw.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)}))}_rejoinRoom(e){return nw(this,null,(function*(){yield this.exitRoom();let t=Qb(Qb({},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=qj.get(e);t&&(t.forEach((e=>clearTimeout(e))),qj.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{ix(e.remoteAudioTrack),ix(e.remoteVideoTrack),ix(e.remoteAuxiliaryTrack)}))}switchRole(e,t){return nw(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(),ix(this),this.removeAllListeners(),this._room.destroy(),xz.delete(this),0===xz.size&&gz.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),JO.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return nw(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:o}=t,n=new cB(e._room.audioManager),a={},s={muted:!0};o&&(jD(o.microphoneId)?jD(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&KD(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),jD(o.profile)||(zD(o.profile)?Jw[o.profile]&&n.setProfile(Jw[o.profile]):n.setProfile(o.profile)),KD(o.earMonitorVolume)&&(s.muted=!(o.earMonitorVolume>0),s.volume=o.earMonitorVolume),jD(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),jD(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),jD(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl),qD(e._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),n.on("5",(t=>{e.emit(_j.ERROR,new WG({code:UG.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),n.on("6",(()=>{})),e._listenOutputTrackChanged(n),e._speakerId&&n.setAudioOutput(e._speakerId),yield n.capture(a),jD(r)||n.setMute(r),tx(n,n).add("player-state-changed",(t=>{e.emit(_j.AUDIO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=$b(Qb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:s,track:n}),JO.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return nw(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,o={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):jD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),jD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),jD(r.earMonitorVolume)||(o.muted=!(r.earMonitorVolume>0),o.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!jD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),jD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),hN(this._localAudioConfig,e)}))}stopLocalAudio(){return nw(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),JO.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ix(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return nw(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:o=!0,capture:n=!0,mute:a,option:s}=t,l=new fB(e._room.videoManager),c={},d={};s&&(qD(s.avoidCropping)&&(l.avoidCropping=s.avoidCropping),s.cameraId?c.deviceId=s.cameraId:jD(s.useFrontCamera)?jD(s.videoTrack)||(c.customSource=s.videoTrack):c.facingMode=s.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT,jD(s.retryWhenExactFailed)||(c.retryWhenExactFailed=s.retryWhenExactFailed),s.qosPreference&&(c.contentHint=jG(s.qosPreference)),jD(s.profile)||(zD(s.profile)?Xw[s.profile]&&l.setProfile(Xw[s.profile]):l.setProfile(s.profile)),jD(s.fillMode)||(d.objectFit=s.fillMode),jD(s.mirror)||(d.mirror=s.mirror),jD(s.small)||(jD(s.smallMode)||(e._room.smallMode=s.smallMode),qD(s.small)&&!1===s.small?l.stopSmall():l.updateSmallConfig(zG(s.small,!0))),jD(s.rotation)||l.setRotation(s.rotation),qD(e._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",(t=>{e.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},t),{streamType:GG(t.streamType)}))})),l.on("5",(t=>{e.emit(_j.ERROR,new WG({code:UG.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),l.on("2",(t=>{e.emit(_j.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),l.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),l.on("6",(()=>{})),e._listenOutputTrackChanged(l),n?yield l.capture(c):null==(i=l.manager)||i.changeInput(l),jD(a)||(yield l.setMute(a)),tx(l,l).add("player-state-changed",(t=>{e.emit(_j.VIDEO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:"",streamType:"main"}))})).add("video-size-changed",(t=>{e.emit(_j.VIDEO_SIZE_CHANGED,$b(Qb({},t),{streamType:GG(t.streamType)}))})),o&&e._room.isJoined&&e._room.publish(l).catch((()=>{})),e._localVideoTrack=l,e._localVideoConfig=$b(Qb({},t),{view:r,publish:o,capture:n}),yield e._updateVideoPlayOption({view:r,playOption:d,track:l})}()}))}updateLocalVideo(e){return nw(this,null,(function*(){var t,i,r;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:o,publish:n,mute:a,capture:s,option:l}=e,c={};if(this._localVideoConfig.capture)!1!==s?null!=l&&l.cameraId?yield this._localVideoTrack.switchDevice(null==l?void 0:l.cameraId):jD(null==l?void 0:l.useFrontCamera)?jD(null==l?void 0:l.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==l?void 0:l.videoTrack)):yield this._localVideoTrack.switchDevice(null!=l&&l.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(s){let e={};e.deviceId=(null==l?void 0:l.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=l&&l.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT,e.customSource=(null==l?void 0:l.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}l&&(jD(l.profile)||(zD(l.profile)?Xw[l.profile]&&this._localVideoTrack.setProfile(Xw[l.profile]):this._localVideoTrack.setProfile(l.profile),(!l.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(l.cameraId))&&jD(l.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),jD(l.fillMode)||(c.objectFit=l.fillMode),jD(l.mirror)||(c.mirror=l.mirror),jD(l.rotation)||this._localVideoTrack.setRotation(l.rotation),l.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(jG(l.qosPreference)),jD(l.small)||(qD(l.small)&&!l.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(zG(l.small,!0)))),this._room.isJoined&&jD(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((()=>{}))),jD(a)||(yield this._localVideoTrack.setMute(a)),yield this._updateVideoPlayOption({view:o,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),hN(this._localVideoConfig,e)}))}stopLocalVideo(){return nw(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),ix(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return nw(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:o=null,publish:n=!0,muteSystemAudio:a,option:s}=t,l=new zB(e._room.videoManager);l.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),l.once("first-video-frame",(t=>{e.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},t),{streamType:GG(t.streamType)}))})),e._listenOutputTrackChanged(l),"main"===t.streamType&&(l.mediaType=4);let c=null,d={},u={};s&&(jD(s.profile)||(zD(s.profile)?Zw[s.profile]&&l.setProfile(Zw[s.profile]):l.setProfile(s.profile)),s.systemAudio&&(d.systemAudio=!0,d.echoCancellation=s.echoCancellation,d.noiseSuppression=s.noiseSuppression,d.autoGainControl=s.autoGainControl),jD(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=jG(s.qosPreference)));let h=yield l.capture(d);if(l.mediaTrack.addEventListener(eC.ENDED,(()=>{e._stopScreenShare(),e.emit(_j.SCREEN_SHARE_STOPPED)})),h.getAudioTracks()[0]){c=new qB(e._room.audioManager);let o=h.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(c.sourceTrack=o),yield c.setInputMediaStreamTrack(o),qD(a)&&c.mediaTrack&&(c.mediaTrack.enabled=!a),e._speakerId&&c.setAudioOutput(e._speakerId)}if(tx(l,l).add("player-state-changed",(t=>{e.emit(_j.VIDEO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[l];c&&(t.push(c),e._checkScreenAudioEchoCancellation(l,c)),t.forEach((t=>e._room.publish(t).catch((()=>{}))))}e._localScreenTrack=l,e._localScreenAudioTrack=c,e._localScreenConfig=$b(Qb({},t),{view:o,publish:n}),yield e._updateVideoPlayOption({view:o,playOption:u,track:l})}()}))}updateScreenShare(e){return nw(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,publish:r,muteSystemAudio:o,option:n}=e,a={};if(n&&(jD(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let e=jG(n.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!jD(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&&qD(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:i,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),hN(this._localScreenConfig,e)}))}stopScreenShare(){return nw(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return nw(this,null,(function*(){let{view:t,userId:i,streamType:r,option:o}=e,n="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(n))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let a=this._room.remotePublishedUserMap.get(i);if(!a)return;let s={},l="main"===r?a.remoteVideoTrack:a.remoteAuxiliaryTrack;l.on("decode-failed",(e=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),l.on("video-size-changed",(e=>{this.emit(_j.VIDEO_SIZE_CHANGED,$b(Qb({},e),{streamType:GG(e.streamType)}))})),this._listenOutputTrackChanged(l),o&&(jD(o.fillMode)||(s.objectFit=o.fillMode),jD(o.mirror)||(s.mirror=o.mirror),jD(o.poster)||(s.poster=o.poster),s.canvasRender=o.canvasRender,"main"===r&&!jD(o.small)&&(!a.remoteVideoTrack.isSubscribing&&!a.remoteVideoTrack.isSubscribed&&a.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user)),jD(o.draggable)||l.setDraggable(o.draggable)),yield this._room.subscribe(l),yield this._enableVideoDecodeFallback(l,r),yield this._updateVideoPlayOption({view:t,playOption:s,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(n,{config:e}),o&&!jD(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:null==o?void 0:o.viewRoot})}))}updateRemoteVideo(e){return nw(this,null,(function*(){var t,i;let{view:r,userId:o,streamType:n,option:a,mute:s}=e,l="".concat(o,"_").concat(n),c=this._remoteVideoConfigMap.get(l);if(!c||!this._room.remotePublishedUserMap.has(o))return;let d={};a&&(jD(a.fillMode)||(d.objectFit=a.fillMode),jD(a.mirror)||(d.mirror=a.mirror));let u=null,h=this._room.remotePublishedUserMap.get(o);if("main"===n&&null!=h&&h.muteState.hasVideo&&(u=h.remoteVideoTrack),"sub"===n&&null!=h&&h.muteState.hasAuxiliary&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:p}=c;"main"===n&&a&&!jD(a.small)&&this._room.changeType(a.small,u.user),a&&!jD(a.draggable)&&u.setDraggable(a.draggable),a&&(qD(a.pictureInPicture)&&(a.pictureInPicture?yield u.player.enterPictureInPicture():yield u.player.exitPictureInPicture()),qD(a.fullScreen)&&(a.fullScreen?yield u.player.enterFullscreen():yield u.player.exitFullscreen())),qD(s)&&(u.ignoreUpdatePlayingState=!0,s?(yield u.player.pause(),yield this.room.unsubscribe(u)):(yield this.room.subscribe(u),yield u.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:d,track:u,prevConfig:p}),hN(p,e);let m=jD(null==a?void 0:a.receiveWhenViewVisible)?null==(t=p.option)?void 0:t.receiveWhenViewVisible:a.receiveWhenViewVisible,f=jD(r)?p.view:r,_=jD(null==a?void 0:a.viewRoot)?null==(i=p.option)?void 0:i.viewRoot:a.viewRoot;this._observeView({remoteTrack:u,view:f,receiveWhenViewVisible:m,viewRoot:_})}))}stopRemoteVideo(e){return nw(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nw(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=r;"main"===e.streamType&&(o.stop(),t.hasVideo&&i.push(o)),"sub"===e.streamType&&(n.stop(),t.hasAuxiliary&&i.push(n))}for(let e of i)t&&(delete e.ignoreUpdatePlayingState,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 nw(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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(cM){throw cM.code!==UG.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),cM}}))}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 nw(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return nw(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return nw(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(_j.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{gj.has(e)||this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(cM){}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",o=!1;if(zD(t)?e=t:(e=t.userId,o=!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?o&&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,o=null;if(""===t)"main"===i&&this._localVideoTrack&&(o=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(o=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(o="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return o?r&&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: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 nw(this,null,(function*(){(yield fU()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),Uz=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: '.concat(Lw,"/en/TRTC.html#.setCurrentSpeaker"))}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return nw(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 o={},n=r.remoteAudioTrack;n.on("decode-failed",(e=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))})),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),a=KD(r)?r:100;o.volume=a,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(n),$U(OV(n,"decode-failed"),eF(OV(n,zL.INIT)),tB((()=>{this.startPlugin(Dz.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:o,track:n}),JO.emit("115",{userId:i,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:"ra-".concat(i)})}catch(hM){throw this._remoteAudioConfigMap.delete(i),hM}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nw(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)),JO.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),$U(OV(e,"decode-failed"),eF(OV(e,zL.INIT)),iB((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),MF(OV(e,"decode-downgrade-state-changed")),tB((r=>{i=r.state,this.emit(_j.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,$b(Qb({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return nw(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:o}=e;return function*(){if(r.setMirror(i.mirror),jD(t)&&o&&o.view&&!lN(i)){let e=mN(o.view);e.length>0&&(yield r.play(e,i))}if(!jD(t)){let e=mN(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return nw(this,arguments,(function(e){var t=this;let{playOption:i={},track:r,prevConfig:o}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(Rw){}if(jD(i.muted)||r.setPlayerMute(i.muted),jD(i.volume)||r.setAudioVolume(i.volume/100),r instanceof cB&&r.mediaTrack){let e=!1===i.muted&&!jD(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof $B){let e=i.muted?0:i.volume;if(jD(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(_j.TRACK,{userId:i,streamType:GG(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,viewRoot:o}=e;if(jD(i)||jD(r))return;let n=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(GG(t.streamType)));if(!n)return;let a=n.observer||void 0;if(null===i||JD(i)&&0===i.length||!r)return null==a||a.disconnect(),void(t.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",t.userId,t.strMediaType),this._room.subscribe(t).catch((()=>{}))));let s=n.visibleViewMap||new Map,l=-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(l),l=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 c=new Set(mN(i));s.forEach(((e,t)=>{c.has(t)||(a.unobserve(t),s.delete(t))})),c.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 nw(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()}))}_stopScreenShare(){return nw(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),ix(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return nw(this,null,(function*(){var i,r;if(!e||!t)return;let o=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.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(dM){this._log.warn("start audioProcessor plugin failed: ",dM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!Uz||dU(Uz))&&(this._initActiveSpeaker(),JO.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return nw(this,null,(function*(){if(Uz&&!dU(Uz))this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:Uz});else{let e=yield fU();e[0]&&!dU(e[0])?(Uz=e[0],this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):JO.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:$b(Qb({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),CP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),CP.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return nw(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),kz.call(e,Qb({trtcInstance:this},t))}))}static setLogLevel(e,t){eM.setLogLevel(e),jD(t)||(t?eM.enableUploadLog():eM.disableUploadLog())}static isSupported(){return HP(e.frameWorkType)}static getPermissions(e){return nw(this,arguments,(function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield Pz.request(i).catch((e=>{var t;return eM.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,r]=yield Promise.all([Pz.get("camera"),Pz.get("microphone")]);return{camera:e,microphone:r}}()}))}static getCameraList(){return pU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return hU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return fU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return nw(this,null,(function*(){if(!ck||t!==xG.SPEAKER&&t!==xG.HEADSET)(yield fU()).forEach((e=>{e.deviceId===t&&(xz.forEach((i=>{i._setCurrentSpeaker(t),i.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),Uz=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;xz.forEach((e=>nw(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:o,useUV:n,version:a,max:s}=e;switch(a&&(wP.version=a),t){case"count":wP.addCount({key:i,useUV:n});break;case"enum":wP.addEnum({key:i,value:r,useUV:n});break;case"number":wP.addNumber({key:i,value:r,split:o,max:s})}}};rw(Vz,"VERSION",Yj),rw(Vz,"_loggerManager",eM),rw(Vz,"EVENT",_j),rw(Vz,"ERROR_CODE",UG),rw(Vz,"TYPE",xG),rw(Vz,"frameWorkType",30),iw([ez({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"}})})],Vz.prototype,"use",1),iw([Jj(rj.TRTC.enterRoom),hj("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})),OU((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),ez()],Vz.prototype,"enterRoom",1),iw([ez()],Vz.prototype,"exitRoom",1),iw([Jj(rj.TRTC.switchRoom),ez(),VU()],Vz.prototype,"switchRoom",1),iw([Jj(rj.TRTC.switchRole),pj("room",{merge:(e,t)=>t}),ez()],Vz.prototype,"switchRole",1),iw([ez()],Vz.prototype,"destroy",1),iw([Jj(rj.TRTC.startLocalAudio),hj("audio",((e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.microphoneId)===(null==(n=null==r?void 0:r.option)?void 0:n.microphoneId)})),ez()],Vz.prototype,"startLocalAudio",1),iw([Jj(rj.TRTC.updateLocalAudio),pj("audio",{debounce:{delay:200,getKey:()=>"".concat(Lz,"-localAudio"),isNeedToDebounce:e=>{var t;return!jD(null==(t=e.option)?void 0:t.captureVolume)}}}),ez()],Vz.prototype,"updateLocalAudio",1),iw([mj("audio"),ez()],Vz.prototype,"stopLocalAudio",1),iw([Jj(rj.TRTC.startLocalVideo),hj("video",((e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.cameraId)===(null==(n=null==r?void 0:r.option)?void 0:n.cameraId)})),ez()],Vz.prototype,"startLocalVideo",1),iw([Jj(rj.TRTC.updateLocalVideo),pj("video"),ez()],Vz.prototype,"updateLocalVideo",1),iw([mj("video"),ez()],Vz.prototype,"stopLocalVideo",1),iw([Jj(rj.TRTC.startScreenShare),hj("screen",(()=>!0)),ez()],Vz.prototype,"startScreenShare",1),iw([Jj(rj.TRTC.updateScreenShare),pj("screen"),ez()],Vz.prototype,"updateScreenShare",1),iw([ez()],Vz.prototype,"stopScreenShare",1),iw([Jj(rj.TRTC.startRemoteVideo),hj((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"startRemoteVideo",1),iw([Jj(rj.TRTC.updateRemoteVideo),pj((e=>"v".concat(e.userId).concat(e.streamType))),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"updateRemoteVideo",1),iw([Jj(rj.TRTC.stopRemoteVideo),OU((e=>function(t){return nw(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)}))})),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"stopRemoteVideo",1),iw([mj((e=>"v".concat(e.userId).concat(e.streamType)))],Vz.prototype,"_stopRemoteVideo",1),iw([Jj(...rj.TRTC.muteRemoteAudio),ez({getRemoteId:e=>e})],Vz.prototype,"muteRemoteAudio",1),iw([Xj(...rj.TRTC.setRemoteAudioVolume),function(e,t){return OU(((i,r)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a=qj.get(this);a||(a=new Map,qj.set(this,a));let s=t(...o),l=a.get(s);if(!l||l<=0){i.apply(this,o);let t=setTimeout((()=>{var e;null==(e=qj.get(this))||e.delete(s)}),e);a.set(s,t)}else{clearTimeout(l);let t=window.setTimeout((()=>{var e;i.apply(this,o),null==(e=qj.get(this))||e.delete(s)}),e);a.set(s,t)}}))}(200,(e=>e)),ez({getRemoteId:e=>e})],Vz.prototype,"setRemoteAudioVolume",1),iw([iz("start"),kU((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),hj(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>IP[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],Vz.prototype,"startPlugin",1),iw([iz("update"),pj(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(hN(e[1],t[1]),e)}),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>AP[e.getName()]})],Vz.prototype,"updatePlugin",1),iw([iz("stop"),mj(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>SP[e.getName()]})],Vz.prototype,"stopPlugin",1),iw([Xj(...rj.TRTC.enableAudioVolumeEvaluation)],Vz.prototype,"enableAudioVolumeEvaluation",1),iw([ez()],Vz.prototype,"getVideoSnapshot",1),iw([ez()],Vz.prototype,"_setCurrentSpeaker",1),iw([hj((e=>"a".concat(e.userId)),(()=>!0))],Vz.prototype,"_startRemoteAudio",1),iw([OU((e=>function(t){return nw(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio($b(Qb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),mj((e=>"a".concat(e.userId)))],Vz.prototype,"_stopRemoteAudio",1),iw([mj("room")],Vz.prototype,"_exitRoom",1),iw([mj("screen")],Vz.prototype,"_stopScreenShare",1),iw([Jj(...rj.TRTC.sendSEIMessage),MG({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}})],Vz.prototype,"sendSEIMessage",1),iw([Jj(rj.TRTC.sendCustomMessage),MG({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Vz.prototype,"sendCustomMessage",1),iw([fj()],Vz,"create",1),iw([Jj(rj.TRTC.create)],Vz,"_create",1),iw([fj()],Vz,"setLogLevel",1),iw([fj()],Vz,"isSupported",1),iw([fj(),ez()],Vz,"getPermissions",1),iw([fj()],Vz,"getCameraList",1),iw([fj()],Vz,"getMicrophoneList",1),iw([fj()],Vz,"getSpeakerList",1);var Fz=Vz,Bz=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 $B(e,this),this.remoteVideoTrack=new eH(e,this),this.remoteAuxiliaryTrack=new tH(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 cN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){if(e===this._flag)return;let t,i=this.muteState;this._flag=e;let r=this.muteState;for(t in r)i[t]!=r[t]&&console.log(this.userId,t,i[t],"->",r[t]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}},Hz=class{constructor(){rw(this,"_set",new Set),JO.on(QO.LEAVE_SUCCESS,this.delete,this),JO.on(QO.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:o}=e;return"rtc"!==o.scene&&this._set.has(this.getKey(t,i,r,o.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 Wz(){return nw(this,null,(function*(){let e,t;try{let t=yield hU();e=t&&t.length}catch(_P){}try{let e=yield pU();t=e&&e.length}catch(_P){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:n,isVp8DecodeSupported:a,isH265EncodeSupported:s,isH265DecodeSupported:l}=this.checkSystemResult.detail,c=rM.basis(),d={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:n,vp8Encode:o,vp8Decode:a,h265Encode:s,h265Decode:l},u={browser:c.browser,os:c.os,trtc:d,devices:i},h={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};rx.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),rx.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),OL()}))}var Gz=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=eM.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&GD(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];let n=t.apply(i,r);return $D(n)?n.catch((e=>eM.error("".concat(t.name,"() error observed ").concat(e)))):n}catch(CC){eM.error("".concat(t.name,"() error observed ").concat(CC))}}}({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:Iw,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,UO().then((()=>{this._basicInfo.string_os_version=zO(),this._basicInfo.string_device_name=FO()||this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),JO.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(QO.JOIN_START,this.handleJoinStart).addEvent(QO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(QO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(QO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(QO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(QO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(QO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(QO.JOIN_FAILED,this.handleJoinFailed).addEvent(QO.LEAVE_START,this.handleLeaveStart).addEvent(QO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(QO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(QO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(QO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(QO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(QO.PUBLISH_START,this.handlePublishStart).addEvent(QO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(QO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(QO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(QO.PLAY_TRACK_START,this.handlePlayStart).addEvent(QO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(QO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===eC.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(QO.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(QO.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(QO.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(QO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(QO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(QO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let o=i.hasAudio||i.hasVideo||i.hasSmall,n=i.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,s=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!n&&s&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(QO.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)=>JO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),QL.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&&(jD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),jD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),jD(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:o,tls:n,request:a,response:s}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,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: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 mw?Number(i.getExtraCode()||i.getCode()):hw.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=oN()-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 mw?Number(i.getExtraCode()||i.getCode()):hw.UNKNOWN)}}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){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(Qb({},zz),{msg_user_info:new Kz({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};o.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,o)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:o}=e;if(!this.hitTest(t))return;let{userId:n,tinyId:a,role:s}=i,l=new Kz({userId:n,tinyId:a,role:"anchor"===s?20:21}),c=Date.now(),d="".concat(n,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=c),"main"===r?(i.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:n,sendSubscribeCMDTime:c}),i.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:n,sendSubscribeCMDTime:c})):i.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:c})}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),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=i-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,CP.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:o,audioDelay:n}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=t,a.totalLoss+=i,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,l;o&&(a=o,s=1),n&&(e=n,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:l,videoDelayCount:s})}})))}handleHeartbeatStats(e){var t;if(this.hitTest(e.room)){let{msg_device_info:i,msg_up_stream_info:r,msg_down_stream_info:o}=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/XM*100)>0&&(this._localStreamStat.totalAudioLevel+=e/XM,this._localStreamStat.audioLevelCount++)}o.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,o=t.str_identifier,n=this._room.remotePublishedUserMap.get(o);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(o,"_").concat(t?"main":"auxiliary"),a=this._remoteStreamStatMap.get(r);if(a&&(t&&null!=n&&n.remoteVideoTrack.isSubscribed||i&&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 i=t?n.remoteVideoTrack:n.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*Jb(10,6)))}})),!lN(i)){let e="".concat(o,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=n&&n.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,n.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=n.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/XM*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/XM,t.audioLevelCount++),i.uint32_audio_block_time&&(t.statsToReport.uint32_audio_block_time+=i.uint32_audio_block_time))}})),i.uint32_audio_capture_cost&&(this._captureCostSum+=i.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===i.uint32_audio_capture_cost&&!1===(null==(t=this._room.audioManager.localAudioTrack)?void 0:t.muted)&&(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 mw?i.getExtraCode()||i.getCode():hw.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&oC))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&sC))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&aC))>=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:o,videoDelayCount:n,totalAudioDelay:a,totalVideoDelay:s}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),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,eC.AUDIO),e.statsToReport.uint32_video_play_time=o.getDuration(t,eC.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,jz));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:s}=n.getDataFreezeDuration(t),{renderFreeze:l}=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(l,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),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>jz&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+jz):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>jz&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+jz):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>jz&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+jz)}getReportData(){this._basicInfo.uint32_networkType=kD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Kz({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:uN(this._signalInfo.relayIp),uint32_client_ip:uN(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Jb(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:uN(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 AN(e),e}report(){return nw(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(lM){this._log.warn(lM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return nw(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=$O.enable?MN(e,2001,t):yield WN(e),r=i instanceof ArrayBuffer,o="".concat(SD(t,Ww.KEY_POINT),"&gzip=").concat(+r),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,i));let a=[this.uploadKVStat(CP),this.uploadKVStat(wP)];n||a.push(HN({url:o,body:i,priority:"low"})),yield Promise.all(a)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return nw(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(Qb({},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=$O.enable?MN(t,2003,this._room.sdkAppId):yield WN(t),r=i instanceof ArrayBuffer,o="".concat(SD(+this._room.sdkAppId,Ww.KV_STAT),"&gzip=").concat(+r),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,i)),n||HN({url:o,body:i})}))}};iw([nx({settings:{timeout:500,retries:3}})],Gz.prototype,"upload",1);var jz=5e3,zz={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},Kz=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}},qz=Gz,Yz=class{constructor(){rw(this,"_startTime"),rw(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=oN())}stop(){0===this._endTime&&(this._endTime=oN())}getDuration(){return 0===this._endTime?oN()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Jz=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(QO.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(QO.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var o;let{userId:n}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(n,"_main"),eC.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(n,"_main"),eC.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(n,"_auxiliary"),eC.VIDEO);let a=null==(o=this._room)?void 0:o.remotePublishedUserMap.get(n);a&&(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,eC.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,eC.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,eC.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>JO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>JO.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:o}=t;t.isSubscribed?this.addDuractionItem(i,o,r):this.stopDurationItem("".concat(i,"_").concat(r),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,i){let r="".concat(e,"_").concat(i),o=new Yz,n=this._durationMap.get(r);n?this.isRecording(n[t])||n[t].push(o):this._durationMap.set(r,{userId:e,type:i,audio:t===eC.AUDIO?[o]:[],video:t===eC.AUDIO?[]:[o]})}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()}},Xz=class{constructor(){rw(this,"renderFreezeMap",new Map),rw(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?"data"===t?r:i:(EO||pk)&&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()}},Qz=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 Xz),rw(this,"_eventMap",new Map),rw(this,"_videoEncodeFailedCount",0),rw(this,"_audioEncodeFailedCount",0),rw(this,"_encodeFailedThreshold",3),rw(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),rw(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),rw(this,"_videoAbnormalTimestampMap",new Map),rw(this,"_remoteVideoAbnormalTimestampMap",new Map),rw(this,"_audioAbnormalTimestampMap",new Map),rw(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(QO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(QO.PLAY_TRACK_START,this.onPlayTrackStart).set(QO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:o}=r,n="".concat(o,"_").concat(i);this.stopDataFreeze({key:n,userId:o,type:i})})).set(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:o}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}})).set(QO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:o}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&o===eC.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===eC.MUTE?this.onVideoTrackMuted(t):r===eC.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(QO.HEARTBEAT_REPORT,this.onHearBeatReport).set(QO.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(QO.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach(((e,t)=>JO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>JO.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),o=this._dataFreezeMap.get(r),n=new Yz;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:t,type:i,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:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&(this.localMediaTrackDetector(i),this.remoteMediaTrackDetector(i))}remoteMediaTrackDetector(e){e.msg_down_stream_info.length>0&&e.msg_down_stream_info.forEach((e=>{var t;if(0===e.msg_video_status.length)return;let i=e.msg_user_info.str_identifier,r=null==(t=this._room.remotePublishedUserMap.get(i))?void 0:t.remoteVideoTrack;e.msg_video_status.forEach((e=>{let t=oN();if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>0&&0===e.uint32_video_receive_fps&&null!=r&&r.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-decode"))){let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-decode"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&(rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-decode")))}if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>5e5&&void 0!==e.uint32_video_dec_fps&&e.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-hardware"))){let r=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));if(r&&t-r>this.ABNORMAL_TIME_LOWER_LIMIT/2&&t-r<2*this.ABNORMAL_TIME_UPPER_LIMIT){rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_HARDWARE_DECODE_FAILED)});let t=this._room.remotePublishedUserMap.get(i);if(t){let i=2===e.uint32_video_stream_type?t.remoteVideoTrack:t.remoteAuxiliaryTrack;i&&(i.log.warn("decode failed during call"),i.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-hardware"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));e&&t-e>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-hardware")))}}))}))}localMediaTrackDetector(e){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,i=Array.from(this._room.localTracks).find((e=>"video"===e.kind&&!e.isScreen)),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;t.forEach((e=>{let t=oN();if(2===e.uint32_video_stream_type)if(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=i&&i.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",t);else{let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}}))}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,i=Array.from(this._room.localTracks).find((e=>"audio"===e.kind)),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;let o=oN();if(0===t.uint32_audio_codec_bitrate&&null!=i&&i.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>this.ABNORMAL_TIME_LOWER_LIMIT&&o-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.AUDIO_ENCODE_FAILED_DURING_CALL)})}else this._audioAbnormalTimestampMap.set("local-encode",o);else{let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(e){let{key:t,userId:i,type:r}=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();if(a>VC){let e=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:e?e.duration+a:a},"data")}else o.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!==eC.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()<VC&&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(!CL())return;let o=0,n=()=>{document.hidden||(o=0)};document.addEventListener("visibilitychange",n);let a=(e,r)=>{var n;if(o){let e=t.decodeFPS,i=e>0&&e<=5?600+1e3/e:600,n=r.presentationTime-o;if(n>i){n=Math.min(n,5e3);let e="".concat(t.userId,"_").concat(t.streamType),i=this._monitorFreezeData.get(e,"render");i?i.duration+=n:this._monitorFreezeData.set(e,{userId:t.userId,type:t.streamType,duration:n},"render");let r=this._renderFreezeMap.get(e);r?(r.totalDuration+=n,r.count+=1):this._renderFreezeMap.set(e,{userId:t.userId,type:t.streamType,totalDuration:n,count:1})}}o=r.presentationTime,null==(n=i.element)||n.requestVideoFrameCallback(a)};null==(r=i.element)||r.requestVideoFrameCallback(a),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:n})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},$z=tw(aw(),1),Zz=class{constructor(e,t,i,r,o){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,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,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?CP.addSuccessEvent({key:r.key}):CP.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,o=t.originX,n=t.originY,a=t.width,s=t.height;1===this.vbMode?this.dualStageCropping(i,r,o,n,a,s):2===this.vbMode&&this.movingPortrait(i,r,o,n,a,s)}catch(pM){this.logger.error(pM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let o,n;return e>t/2?(o=t-i-r,n=i-o):(o=i,n=0),{min:o,offset:n}}calculateTargetPosition(e,t,i,r,o,n){let a,s,l=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,c=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(c,o,e,i),{min:p,offset:m}=this.calculateBoundary(d,n,t,r);return a=2*u+i,s=2*p+r,a/s>this.originalAspect?(a=s*this.originalAspect,h=c-a/2):(s=a/this.originalAspect,m=d-s/2),i/o>l&&(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,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),o=this.positionDistance(this.animationState.current,e),n=this.animationState.current.cropWidth/t;r>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=Qb({},e),void(this.animationState.target=Qb({},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)),KD(this.animationState.current.scaleOffsetX)&&KD(this.animationState.target.scaleOffsetX)&&KD(this.animationState.current.scaleOffsetY)&&KD(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(Jb(e.sx-t.sx,2)+Jb(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,o,n){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let s=this.calculateTargetPosition(i,r,o,n,e,t);this.processFacePositionCrop(s,e,t),o*n/s.cropWidth/s.cropHeight>a&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,o,n){var a,s,l,c,d,u,h,p,m,f,_,g;let E={sx:i+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(s=null==(a=this.animationState.current)?void 0:a.scaleRatio)?s:1,scaleOffsetX:null!=(c=null==(l=this.animationState.current)?void 0:l.scaleOffsetX)?c: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+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}},eK=class extends NB{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 mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return nw(this,null,(function*(){var t,i,r;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!=(i=e.enableEffectOptimization)&&i,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:i,width:r,height:o}=e.waterMark;this.wasm.setWaterMark(t,i,r,o)}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),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:LO()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(r=this._postProcessing)||r.init(n,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)}))}initVisionTasks(e){return nw(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 Zz(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(CC){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(),DN(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:o}=i;if(DN(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,o]=[o,r]),0===r||0===o||!this.available)return!1;i.width=r,i.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===r&&this.height===o&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,o),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,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,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(hM){this._onAbort&&this._onAbort(hM)}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:o=1,scaleOffsetX:n=0,scaleOffsetY:a=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+n,a,0]),this._mat4.scale(r,r,[o,o,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){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+r)/a,0]),this._mat4.scale(s,s,[i/n,r/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()}},tK=class extends yB{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 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)}},iK=(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 rK=0,oK=class{constructor(e){rw(this,"id",rK++),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:i}=e;if(this.stateChangeOB=vV(),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=OV(t.availableState,zL.OFF),this.stopOB=vV(),"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),$U(this.stateChangeOB,IF(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),eF(this.stopOB),tB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=$U(this.pipe(this.track),eF(this.stopOB),aV());$U(t,tB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),CP.addFailedEvent({key:iK(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),CP.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")),CP.addSuccessEvent({key:iK(this.type,this.renderer)}),CP.addSuccessEvent({key:514704})}))),$U(t,ZV(1),tB((()=>{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&&!UP()&&(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 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==(i=this.decoder)?void 0:i.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=oN()}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=>nw(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:o,type:n}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(n){case"wasm":i=this.createDecoder(n,this.wasmOption);break;case"webCodecs":i=this.createDecoder(n);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"===n?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===n&&"webgl"===o){this.videoContext=new LB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(LB.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new tK(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"===o){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 xB({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(o){delete this.goodType,e.log.error(o),t.error(11)}}));let o=new SB(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(o),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(dM){e.log.error(dM),t.error("webCodecs"===n?2:6)}}))}},nK=Promise.resolve(),aK=class extends $z.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"),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",nK),rw(this,"_updateFlag",!1),this.log=eM.createLogger({parent:null==e?void 0:e.getLogger(),id:"vm",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.smallVideoContext=new xB({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 DN(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new xB({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 LB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(gO<=22),this._glVideoContext.on(LB.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(Sw){this.emit("error",Sw)}}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=QL.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(),QL.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vO||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?CP.addFailedEvent({key:t,error:e}):CP.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 LB({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 wB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(LB.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:o}=i;vO&&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(r,e),i.setOutputMediaStreamTrack(n)}catch(cM){this.log.error("set main output failed",cM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nw(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(yB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===RO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof NB?(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 NB?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 bB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(yB.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 eK(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 HB(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 FB(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,o,n;if(e instanceof zB)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof fB)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof eH){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 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 zB?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof fB?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 eH?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 nw(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 nw(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 mw({code:hw.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((i=>{let{image:o,x:n,y:a,width:s,height:l,fillVideo:c}=i,d=c&&e||s,u=c&&t||l,h=c?0:n,p=c?0:a;r.drawImage(o,h,p,d,u)})),TN(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&&t.fillVideo===e.fillVideo))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return nw(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return nw(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return nw(this,null,(function*(){let t;try{t=yield TN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(nM){throw new mw({code:hw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:o=t.width,height:n=t.height,type:a="watermark",zIndex:s=2,fillVideo:l=!1}=e;this.watermarkImageList.some((e=>e.type===a))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==a)),this.pushWaterMarkImageList({x:i,y:r,width:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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 nw(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 nw(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 nw(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 TN(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 mw({code:hw.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 nw(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 oK(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}};iw([function(e){return OU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return nw(this,null,(function*(){try{return yield t.apply(this,r)}catch(cM){e.call(this,cM)}}))}))}((function(e){this.log.error("update failed",e)})),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){this._updateFlag||(this._updateFlag=!0,yield nK,this.updated=new Promise(((t,r)=>{e.apply(this,i).then(t,r),setTimeout(r,5e3,new mw({code:hw.API_CALL_TIMEOUT,message:"update timeout"}))})),this._updateFlag=!1,yield this.updated)}))}))],aK.prototype,"update",1);var sK=0,lK=class extends zL{constructor(e){super("room"),rw(this,"seq",++sK),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"),rw(this,"_joinedTimestamp",0),rw(this,"_sdkType"),rw(this,"heartbeatReport"),rw(this,"heartbeatCount",0),rw(this,"quality"),rw(this,"enableSEI"),rw(this,"isDestroyed",!1),this._log=eM.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,qD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),qD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),qD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new qz({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Jz({room:this}),this.badCaseDetector=new Qz({room:this}),this.audioManager=new JB(this),this.videoManager=new aK(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 nw(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return nw(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return nw(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(zD(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(FD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:o,unifiedProxy:n}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=n,n?(bj([n,n]),Nw("https://".concat(n))):(r&&Nw(r),o&&bj(o))}JO.once(QO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:Rj.main,sched_back_domain:Rj.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return nw(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return nw(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 nw(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 mw({code:hw.INVALID_OPERATION,message:fP({key:uP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(hP.INVALID_DESTROY),new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.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,JO.emit(QO.ROOM_DESTROY,{room:this})}schedule(e,t){return nw(this,null,(function*(){var i,r,o,n;let a=oN();try{let{isCached:s,result:l,detailCost:c}=yield Sj({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Iw,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(gN(l,{keysToExclude:["username","credential"]}))),s&&JO.once(QO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=Qb(Qb({},this.scheduleResult),l),KD(null==(i=l.config)?void 0:i.retryCount)&&bC(l.config.retryCount),zD(null==(r=l.config)?void 0:r.loggerDomain)&&Nw(l.config.loggerDomain),this.videoDecodeFallbackType=(null==(o=l.config)?void 0:o.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(n=l.config)?void 0:n.smallMode)||this.smallMode,JO.emit(QO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),CP.addSuccessEvent({key:521700,cost:oN()-a})}catch(aM){throw CP.addFailedEvent({key:521700,error:aM}),aM}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var cK={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},dK="__INLINE__WORKER__",uK="__INLINE__WASM__",{debug:hK}=console;cK.debug||(console.debug=()=>{});var pK,mK=!dK.startsWith("__"),fK=!uK.startsWith("__");function _K(){let e=bN("".concat(cK.assetsPath?"".concat(cK.assetsPath,"/"):"","worker.js"));return mK?URL.createObjectURL(new Blob([atob(dK)],{type:"application/javascript"})):e.startsWith("http")?fetch(e).then((e=>e.blob().then((e=>URL.createObjectURL(e))))):e}function gK(){return nw(this,null,(function*(){let e=cK.assetsPath?"".concat(cK.assetsPath,"/"):"";return pK||(pK=fK?(new TextEncoder).encode(atob(uK)).buffer:yield fetch(bN("".concat(e,"av_processing.wasm"))).then((e=>e.arrayBuffer())),pK)}))}var EK=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 nw(this,null,(function*(){let e=qx(),t=_K();try{yield e.audioWorklet.addModule("string"==typeof t?t:yield t),eM.info("global audio player worklet addModule success",t)}catch(CC){throw eM.error("global audio player worklet addModule failed:",CC),CC}return this.worklet=new AudioWorkletNode(e,"global-audio-player",{processorOptions:{wasm:yield gK(),flag:cK},numberOfInputs:2}),eM.info("global audio player worklet created",e.state),this.playPort=this.worklet.port,this.playPort}))}playAudio(e){return nw(this,null,(function*(){var t;yield this.init();let i=new MessageChannel;null==(t=this.playPort)||t.postMessage(null,[i.port1]),e(i.port2)}))}},vK="undefined"!=typeof self&&(!("top"in self)||self===top)&&"showOpenFilePicker"in self&&"showOpenFilePicker";vK?Promise.resolve().then((function(){return AK})):Promise.resolve().then((function(){return DK})),vK?Promise.resolve().then((function(){return wK})):Promise.resolve().then((function(){return NK}));var yK=vK?Promise.resolve().then((function(){return CK})):Promise.resolve().then((function(){return kK}));function TK(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){return(yield yK).default(...t)}))}var IK=e=>nw(void 0,null,(function*(){let t=yield e.getFile();return t.handle=e,t})),AK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{t[i]={description:e.description||"Files",accept:{}},e.mimeTypes?e.mimeTypes.map((r=>{t[i].accept[r]=e.extensions||[]})):t[i].accept["*/*"]=e.extensions||[]}));let i=yield window.showOpenFilePicker({id:e[0].id,startIn:e[0].startIn,types:t,multiple:e[0].multiple||!1,excludeAcceptAllOption:e[0].excludeAcceptAllOption||!1}),r=yield Promise.all(i.map(IK));return e[0].multiple?r:r[0]}()}))}};function SK(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 SK=function(e){this.s=e,this.n=e.next},SK.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new SK(e)}var RK,bK=function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return nw(void 0,[e,t,...r],(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.name,r=arguments.length>3?arguments[3]:void 0;return function*(){let o=[],n=[];var a,s=!1,l=!1;try{for(var c,d=function(e){var t,i,r,o=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,r=Symbol.iterator);o--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new SK(t.call(e));i="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(e.values());s=!(c=yield d.next()).done;s=!1){let a=c.value,s="".concat(i,"/").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||r&&r(a)||o.push(bK(a,t,s,r))}}catch(u){l=!0,a=u}finally{try{s&&null!=d.return&&(yield d.return())}finally{if(l)throw a}}return[...(yield Promise.all(o)).flat(),...yield Promise.all(n)]}()}))},wK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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 bK(t,e.recursive,void 0,e.skipDirectory)}()}))}},CK={__proto__:null,default:function(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 nw(void 0,[e,...i],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[{}],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=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((i=>{n[t].accept[i]=e.extensions||[]}))):a?n[t].accept[a]=e.extensions||[]:n[t].accept["*/*"]=e.extensions||[]})),i)try{yield i.getFile()}catch(c){if(i=null,r)throw c}let s=i||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:n,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!i&&o&&o(s);let l=yield s.createWritable();return"stream"in e?(yield e.stream().pipeTo(l),s):"body"in e?(yield e.body.pipeTo(l),s):(yield l.write(yield e),yield l.close(),s)}()}))}},DK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{let r=document.createElement("input");r.type="file";let o=[...e.map((e=>e.mimeTypes||[])),...e.map((e=>e.extensions||[]))].join();r.multiple=e[0].multiple||!1,r.accept=o||"",r.style.display="none",document.body.append(r);let n=e=>{"function"==typeof a&&a(),t(e)},a=e[0].legacySetup&&e[0].legacySetup(n,(()=>a(i)),r),s=()=>{window.removeEventListener("focus",s),r.remove()};r.addEventListener("click",(()=>{window.addEventListener("focus",s)})),r.addEventListener("change",(()=>{window.removeEventListener("focus",s),r.remove(),n(r.multiple?Array.from(r.files):r.files[0])})),"showPicker"in HTMLInputElement.prototype?r.showPicker():r.click()}))}()}))}},NK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{let r=document.createElement("input");r.type="file",r.webkitdirectory=!0;let o=e=>{"function"==typeof n&&n(),t(e)},n=e[0].legacySetup&&e[0].legacySetup(o,(()=>n(i)),r);r.addEventListener("change",(()=>{let t=Array.from(r.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?r.showPicker():r.click()}))}()}))}},kK={__proto__:null,default:function(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 nw(void 0,[e,...i],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){Array.isArray(t)&&(t=t[0]);let i=document.createElement("a"),r=e;"body"in e&&(r=yield function(e,t){return nw(this,null,(function*(){let i=e.getReader(),r=new ReadableStream({start:e=>function t(){return nw(this,null,(function*(){return i.read().then((i=>{let{done:r,value:o}=i;if(!r)return e.enqueue(o),t();e.close()}))}))}()}),o=new Response(r),n=yield o.blob();return i.releaseLock(),new Blob([n],{type:t})}))}(e.body,e.headers.get("content-type"))),i.download=t.fileName||"Untitled",i.href=URL.createObjectURL(yield r);let o=()=>{"function"==typeof n&&n()},n=t.legacySetup&&t.legacySetup(o,(()=>n()),i);return i.addEventListener("click",(()=>{setTimeout((()=>URL.revokeObjectURL(i.href)),3e4),o()})),i.click(),null}()}))}},OK=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 i;null==(i=this.worker)||i.postMessage(e,t)}create(e){return nw(this,null,(function*(){if(this.ready)return this.ready;e||(e=this.name),console.time("createWorker_".concat(e));let t=_K(),i=new Worker("string"==typeof t?t:yield t,{name:e});return this.worker=i,this.ready=new Promise(((t,r)=>nw(this,null,(function*(){i.onmessage=i=>{let{data:{id:o,type:n,payload:a}}=i;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),r(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(_N(),a.group,a.name,e,"👉",t)}break;case"log":console.log(a);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:a}))}},i.postMessage({wasm:yield gK(),flag:cK},this.ports)}))))}))}destroy(){var e;console.log("destroy worker",this.name),delete this.ready,null==(e=this.worker)||e.terminate()}},MK=class{constructor(e,t,i){this.worker=e,rw(this,"channel",new MessageChannel),rw(this,"ready"),this.ready=new Promise(((e,i)=>{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=i),e)))}postMessage(){this.channel.port1.postMessage(...arguments)}destroy(){0==--this.worker.sessionCount&&this.worker.destroy()}},PK=new class e extends OK{constructor(){super("main"),rw(this,"switchValue",new Map),rw(this,"extendChannel"),rw(this,"sessionCount",0)}setSwitchValue(e,t){var i;this.switchValue.set(e,t),null==(i=this.extendChannel)||i.port1.postMessage([e,t])}create(){return nw(this,null,(function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield ow(e.prototype,this,"create").call(this),this.switchValue.forEach(((e,t)=>{this.extendChannel.port1.postMessage([t,e])})),this)}))}},LK=-1;function xK(e){return console.log(e),RK.push(e.slice()),RK.length>1e3&&RK.shift(),e}function UK(e){return nw(this,null,(function*(){switch(LK){case 0:this.edpl.willDecodeAudio=xK;break;case 2:this.edpl.didEncodeAudio=xK}yield PK.create(),JO.emit(QO.JOIN_SEND_CMD,{room:this});let t=new MK(PK,e,(e=>{let i=e.data;if("string"==typeof i)this.onWorkerEvent(i);else if(null==i)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:e,payload:t}=i;this.onWorkerEvent(e,t)}})),{err:i,data:r}=yield t.ready;if("number"==typeof i){if(JO.emit(QO.JOIN_RECEIVED_CMD_RES,{room:this,code:i}),0===i)return Object.assign(this,r,{session:t});throw new mw({code:hw.JOIN_ROOM_FAILED,extraCode:Number(i),message:fP({key:uP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i,errorMsg:""}})})}throw i}))}function VK(e){return nw(this,null,(function*(){PK.setSwitchValue("useAINS",e)}))}function FK(e){return nw(this,null,(function*(){PK.setSwitchValue("useV2",e)}))}function BK(e){let t=new MediaStreamTrackGenerator({kind:"audio"});e.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:e.tinyId,writable:t.writable}},[t.writable])}function HK(e){return nw(this,null,(function*(){var t;this._log.info("pull video",e);let i=Date.now(),r=0,o=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:e.mediaType,tinyId:e.tinyId}},[o.port1]),(t=e.stat).framesReceived||(t.framesReceived=0),$U(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=Object.defineProperties(vV(),{postMessage:{value:e.postMessage.bind(e)},port:{get:()=>e,set(t){e.onmessage=WU,e.onmessageerror=WU,e=t,r()}}});function r(){e.onmessage=r=>{r.data?r.ports.length||t?i.next(r):i.next(r.data):(i.complete(),e.close())},e.onmessageerror=t=>{i.error(t),e.close()}}return r(),i}(o.port2),eF(OV(e,zL.INIT)),tB((t=>{let{data:o,packetsReceived:n}=t;e.stat.packetsReceived=n,e.stat.framesReceived++,r++;let a,s=31&o[4];if(r<=10){let e=Array.from(o.slice(0,10)).map((e=>e.toString(16).padStart(2,"0"))).join(" ");this._log.info("Frame ".concat(r," - Size: ").concat(o.length," bytes, Type: ").concat(s,", Timestamp: ").concat(Date.now()-i,"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()-i)}):console.warn("track is not available")}),(()=>{}),(()=>{o.port2.postMessage(null),o.port2.close()})))}))}Object.defineProperties(window,{useAINS:{set:VK},useWt:{set:function(e){return nw(this,null,(function*(){PK.setSwitchValue("useWt",e)}))}},enableDebug:{set(e){console.debug=e?hK:()=>{},PK.setSwitchValue("enableDebug",e)}},useV2:{set:FK},dump:{value(){if(LK=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,RK||(console.warn("dump audio will be activated at next time join room"),RK=[]),!RK.length)return void console.warn("no audio data to dump,try it later");let e=[];return RK.forEach((t=>{e.push(new Uint16Array([t.length])),e.push(t)})),TK(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,i=[],r=new Promise((r=>{let o=new MessageChannel;PK.extendChannel.port1.postMessage(["dump",e],[o.port1]),o.port2.onmessage=n=>{let{data:a}=n;console.log(a),i.push(a),i.length>t&&(o.port2.onmessage=null,PK.extendChannel.port1.postMessage(["dump",e]),o.port2.close(),r(new Blob(i)))}}));return TK(r,{fileName:e,extensions:[".pcm"]})}},hardDec:{set(e){switch(e){case!0:cK.useHardDecoder="prefer-hardware";break;case!1:cK.useHardDecoder="prefer-software";break;default:cK.useHardDecoder="no-preference"}}}});var WK=[];function GK(e){var t;let i=vV();if("joined"!==this.state)throw new Error("Room is not joined");if("publish"===e.state)return;for(let c=0;c<=WK.length;c++)if(!WK[c]){WK[c]=this,this.index=c;break}let r=e.profile;this._log.info("start push audio",this.index,r);let o=new MessageChannel,n=e.enableEncryptFrame?new MessageChannel:null;null==(t=this.session)||t.postMessage({cmd:"pushAudio",payload:Qb({index:this.index},r)},n?[o.port2,n.port2]:[o.port2]),o.port1.onmessage=t=>{null==t.data||("number"==typeof t.data?i.next(t.data):n&&n.port1.postMessage($b(Qb({},t.data),{data:new Uint8Array(e.encodeFrame({data:t.data.data.buffer,timestamp:t.data.timestamp}).data)})))};let a,s=new MediaStream,l=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=qx().createMediaStreamSource(s),a.connect(EK.worklet,0,this.index)};$U(OV(e,"output-media-track-changed"),eF(OV(e,"ready")),tB(l,console.error,(()=>{this._log.info("stop push audio",r),e.volume=0,a.disconnect(),WK[this.index]=null,n&&n.port1.postMessage(null),o.port1.postMessage(null)}))),$U(i,iB((t=>e.volume=t)),MF(IB(1e3)),tB((()=>{e.volume=0}))),l(e.outMediaTrack)}var jK=class{constructor(e,t,i,r){this.localTrack=e,this.type=t,this.config=i,this.port=r,rw(this,"track"),rw(this,"label"),rw(this,"insertKeyFrame",!0),rw(this,"session"),rw(this,"tsMap",new Map),rw(this,"startTime",0),rw(this,"startTimestamp",0),e._log.info("create Video Encoder",i)}trans(e,t,i){return nw(this,null,(function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});t.signal.addEventListener("abort",(()=>{r.encoder.close()}));let o=0;return e.pipeThrough(new TransformStream({transform:(e,t)=>{"configured"===r.encoder.state&&(this.tsMap.set(o,Date.now()),this.encode(e),o++,t.enqueue(e))}}),t)}))}encode(e){var t,i;null==(i=null==(t=this.session)?void 0:t.encoder)||i.encode(e,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(e,t,i){return nw(this,null,(function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=r;let o=0;e.pipeTo(new WritableStream({write:e=>{let t=Date.now();"configured"===r.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},r)),126===fO?this.tsMap.set(o,oN()):0===o&&(this.startTime=t,this.startTimestamp=e.timestamp),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),r.encoder.close()}))}))}recreate(e,t){return nw(this,null,(function*(){let i=0,r=new VideoEncoder({output:r=>{let o=126===fO?this.tsMap.get(i):(this.startTime+(r.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(126===fO&&this.tsMap.delete(i),i<10&&(0===i&&0===t.recreateCount&&JO.emit(QO.SEND_FIRST_VIDEO_FRAME,{room:e}),this.localTrack.log.info("encoded ".concat(this.label," track frame:"),i,Date.now(),r.timestamp)),i++,t.frameEncoded=i,!1===this.track.enabled)return;let n=null;if(this.localTrack.enableEncodeFrame){n=new Uint8Array(r.byteLength),r.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:r.type,timestamp:r.timestamp,data:n,duration:r.duration},timestamp:o},[n.buffer])):(this.localTrack.stat.bytesSent+=r.byteLength,this.port.postMessage({chunk:r,timestamp:o}))},error:i=>{this.localTrack.log.warn(i,this.config),t.recreateCount++,setTimeout((()=>this.recreate(e,t)),100)}});return t.encoder=r,yield this.configure(null,t),t}))}configure(e,t){return nw(this,null,(function*(){var i;e&&Object.assign(this.config,e),null==(i=t.encoder)||i.configure(this.config)}))}close(){this.port.postMessage(null),this.port.close()}};function zK(e,t){return nw(this,null,(function*(){let i=2===e.mediaType,r=i?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:cK.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 jK(e,t.type,o,n.port2);return n.port2.onmessage=e=>{if(260===e.data)a.insertKeyFrame=!0;else if(!i){let{bitrate:t}=e.data;UD({configureBr:[e.data.bitrate,t]}),a.session&&a.configure({bitrate:t},a.session)}},this._log.info("start push",r,t),a}))}function KK(e){return nw(this,null,(function*(){var t;let i=2===e.mediaType,r=i?"screen":"video",o={type:i?7:2,profile:e.profile,trackType:i?"screen":"camera",crypto:!(null==(t=e.manager)||!t.encodePipeline[0])};!i&&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 l=yield zK.call(this,e,o);this._log.info("VideoEncoder created",o);let c,d=t=>nw(this,null,(function*(){if(null==c||c.abort("track changed"),!t)return;c=new AbortController;let{width:i,height:o,displaySurface:a}=t.getSettings();i&&(l.config.width=i),o&&(l.config.height=o);let s,d=QN.match(/Chrome\/(\d+)/);"114"===(null==d?void 0:d[1])&&"browser"===a&&delete l.config.hardwareAcceleration,this._log.info("push",r,"track:",t.readyState,t.getSettings()),s="undefined"==typeof MediaStreamTrackProcessor||t instanceof CanvasCaptureMediaStreamTrack?new ReadableStream({start(t){e.on("render",(i=>{if(0!==e.player.mode||document.hidden)try{t.enqueue(new VideoFrame(i,{timestamp:1e3*performance.now()}))}catch(r){console.warn(r)}}))},pull(t){return nw(this,null,(function*(){if(0===e.player.mode&&CL()&&e.player.element)return new Promise((i=>{e.player.element.requestVideoFrameCallback(((r,o)=>{try{let i=new VideoFrame(e.player.element);t.enqueue(i)}catch(gP){console.warn(gP)}i()}))}))}))}}):new MediaStreamTrackProcessor({track:t}).readable;let u="small"in e&&e.small;return u?(this.smallEncoder||(this.smallEncoder=yield zK.call(this,e,{profile:u,type:3,trackType:n})),this.smallEncoder.track=t,this.smallEncoder.label="small",s=yield this.smallEncoder.trans(s,c,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),l.track=t,l.label=r,l.start(s,c,this)}));return $U(OV(e,"output-media-track-changed"),eF(OV(e,"ready")),tB(d,console.error,(()=>{var e;this._log.info("stop push",r,o),c.abort("unpublish"),l.close(),null==(e=this.smallEncoder)||e.close()}))),d(e.outMediaTrack)}))}var qK=class e extends zL{constructor(t){var i,r;super(null!=(r=null==(i=t.roomid)?void 0:i.toString())?r:t.name,"volumeEvaluation"),this.room=t,rw(this,"enableInBackground",!1),rw(this,"interval",400),t.on("joined",(()=>{this.emit(e.INTERVALCHANGED,this.interval)})),$U(OV(this,e.INTERVALCHANGED),kF((e=>"joined"===this.room.state?this.room.fromWorker("getAudioEnergy",e):$U((e=>t=>{let i=0,r=performance.now();$U(TB,RF((t=>(t-r)/e|0)),QV((e=>e!=i&&(i=e,!0))))(t)})(e),RF((()=>[]))))),tB((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==zL.ON&&this.room.emit("audio-volume",e)})))}start(t,i){this.interval=t,this.enableInBackground=i,this.emit(e.INTERVALCHANGED,this.interval)}stop(){}};rw(qK,"INTERVALCHANGED","intervalChanged"),iw([WL([zL.INIT,zL.OFF],zL.ON)],qK.prototype,"start",1),iw([WL([],zL.OFF)],qK.prototype,"stop",1);var YK=qK,JK=class extends lK{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 YK(this)),rw(this,"enableAIVoice",VK),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:KO(),uint32_device_type:0,str_os_verion:qO(),uint32_link_type:1,str_client_version:Iw,uint32_net_type:qw[vw.getNetworkType()],ua:navigator.userAgent,version:""}}),rw(this,"joinAbortController",new AbortController),rw(this,"smallAbortCtrl"),rw(this,"smallEncoder"),e.tinyId&&(this.tinyId=e.tinyId,FK(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return nw(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(((i,r)=>{"joined"!=this.state&&r("join room first");let o=new MessageChannel;this.postMessage({cmd:e,payload:t},[o.port1]),o.port2.onmessageerror=r,o.port2.onmessage=e=>{o.port2.close(),i(e.data)}}))}fromWorker(e,t){if("joined"!=this.state)throw"join room first";return i=>{var r;let o=new MessageChannel;o.port2.onmessage=e=>{e.data?i.next(e.data):i.complete()},o.port2.onmessageerror=e=>i.error(e),i.defer((()=>{o.port2.postMessage(null),o.port2.close()})),null==(r=this.session)||r.postMessage({cmd:e,payload:t},[o.port1])}}switchRole(e){return nw(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,i){return nw(this,null,(function*(){var r,o,n;let a=vw.getEnv(),s=kP(),l={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:i,params:e,proxy_wt:null==(r=this.proxy_wt)?void 0:r.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:WO(),browserInfo:kP(),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:Iw,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 UK.call(this,l),console.log(this),EK.playAudio((e=>this.postMessage({cmd:"setAudioWorkletPort"},[e]))),this.checkDestroy()}))}leave(){return nw(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 nw(this,null,(function*(){let e=eF(OV(this,"left")),t=this.audioManager.decodePipeline.some((e=>e));$U((e=>nw(this,null,(function*(){let i=new MessageChannel;i.port2.onmessage=t=>{t.data?e.next({data:t.data,port:i.port2}):e.complete()},i.port2.onmessageerror=t=>e.error(t),e.defer((()=>{i.port2.postMessage(null),i.port2.close()})),this.postMessage({cmd:"decodeAudio",payload:t},[i.port1])}))),e,tB((e=>{let{data:t,port:i}=e;var r;let o={data:t.data.buffer};for(let[n,a]of this.audioManager.decodePipeline.entries())if(a&&(o=a({frame:o,track:null==(r=this.remotePublishedUserMap.get(t.userId))?void 0:r.remoteAudioTrack}),!o))return;i.postMessage($b(Qb({},t),{data:new Uint8Array(o.data)}),[o.data])})))}))}onWorkerEvent(e,t){switch("network-quality"!==e&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(t)),e){case QO.RECEIVED_PUBLISHED_USER_LIST:return void JO.emit(e,Qb({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 i=new Bz(this,t);return this.remotePublishedUserMap.set(t.userId,i),void this.emit("remote-published",i);case"5":{let e=t,i=this.remotePublishedUserMap.get(e);i&&(i.remoteVideoTrack.close(),i.remoteAuxiliaryTrack.close(),i.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(e),this.emit("remote-unpublished",i))}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:i,flag:r}=t,o=this.remotePublishedUserMap.get(i.userId);if(!o)return void this.emit("remote-publish-state-changed",t);o.flag=r}return JO.emit(QO.REMOTE_PUBLISH_STATE_CHANGED,Qb({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=Qb({},t);let{uplinkLoss:r,uplinkRTT:o,uplinkInfo:n,downlinkInfo:a,msg_down_stream_info:s}=t,l={str_sdk_version:Iw,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:qw[bD()]},msg_event_msg:oH(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:n,msg_down_stream_info:s};JO.emit(QO.HEARTBEAT_REPORT,{room:this,report:l}),this.emit("heartbeat-report",l),JO.emit(QO.NETWORK_QUALITY,{room:this,uplink:{rtt:o,loss:r},downlinks:a}),delete t.downlinkInfo;break;case"signal-connection-state-changed":return void JO.emit(QO.SIGNAL_CONNECTION_STATE_CHANGED,Qb({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(e){return nw(this,null,(function*(){if(1===(yield this.sendMessage("publish",e.mediaType).then((e=>0!==e.err?Promise.reject(e.err):e)),tx(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))yield EK.init(),GK.call(this,e);else yield KK.call(this,e);e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})}))}unpublish(e){return nw(this,null,(function*(){ix(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){let e=t.reduce(((e,t)=>t.mediaType|e),0),{userId:i,tinyId:r,streamType:o}=t[0],n=this.remotePublishedUserMap.get(i),a=Qb({},n.subscribeState),s=Object.assign(new $M,a);s.mediaType|=e,JO.emit(QO.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:n,subscribeState:s});let l=yield this.sendMessage("subscribe",{mediaType:s.mediaType,userId:i,srctinyid:r,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",l),yield Promise.all(t.filter((e=>!e.isSubscribed)).map((e=>1===e.mediaType?BK.call(this,e):HK.call(this,e)))),JO.emit(QO.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:n})}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){let e=0;for(let i of t)e|=i.mediaType;if(t.length){let{userId:i,streamType:r,tinyId:o}=t[0];yield this.sendMessage("unSubscribe",{mediaType:e,srctinyid:o,userId:i});for(let e of t)e.unsubscribe();JO.emit(QO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:this.remotePublishedUserMap.get(i)})}}))}enableSmall(e){return nw(this,null,(function*(){var t;if(e){if(this.videoManager.smallTrack){let e=this.videoManager.cameraTrack;this.smallEncoder=yield zK.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 i=this.remotePublishedUserMap.get(t.userId);if(!i)return;let r=e?8:4;if(i.remoteVideoTrack.mediaType===r)return;let o={srctinyid:i.tinyId,mediaType:r,userId:t.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter((e=>r&e)).map((e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]})))}};i.remoteVideoTrack.mediaType=o.mediaType,this.postMessage("changetype",o)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};iw([kU(JK.prototype.afterJoin),WL(["left",zL.INIT],"joined"),OU((e=>{let t=new Hz;return function(i,r,o){return nw(this,null,(function*(){let n=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 mw({code:hw.INVALID_OPERATION,message:fP({key:uP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:n}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(n," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),JO.emit(QO.JOIN_START,{room:this,roomId:n,params:i});let a=vw.getEnv();a||(a=Gw.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(iC.OLD_CLOUD_LADDER)?a=Gw.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(iC.WEBRTC)&&(a=Gw.WEBRTC))),rx.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),rM.checkSystemRequirementsInternal(o).then((e=>{this.checkSystemResult=e,Wz.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vw.getEnv()&&(yield this.schedule(i,o));let t=yield e.call(this,i,r,o);return this.roomId=n,this._joinedTimestamp=vw.performanceNow(),JO.emit(QO.JOIN_SUCCESS,{room:this}),30===o&&!i.component&&rx.uploadEvent({log:"stat-conv-".concat(Number(NO),"-").concat(location.hostname),userId:this.userId}),t}catch(dM){throw t.delete({room:this,roomId:n}),JO.emit(QO.JOIN_FAILED,{room:this,error:dM}),dM}}))}}))],JK.prototype,"join",1),iw([WL("joined","left",{ignoreError:!0}),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){JO.emit(QO.LEAVE_START,{room:this}),yield e.call(this,...i),JO.emit(QO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))}))],JK.prototype,"leave",1),iw([FU((e=>e.mediaType)),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;JO.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map((e=>e.publish(this,t))))}))}))],JK.prototype,"publish",1),iw([FU((e=>e.mediaType)),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach((e=>e.unpublish())),o}))],JK.prototype,"unpublish",1),iw([FU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(o))),o}))],JK.prototype,"subscribe",1);var XK=JK;return Fz.frameWorkType=37,Fz.create=function(e){let t=Fz._create.call(this,XK,e);return t._use(kG,null==e?void 0:e.assetsPath),null!=e&&e.assetsPath&&(cK.assetsPath=null==e?void 0:e.assetsPath),console.log("trtc wasm sdk:",Iw,"created",cK),t},Object.assign(Fz.prototype,{_setCurrentSpeaker(e){let t=qx();return null!=t&&t.setSinkId?t.setSinkId(e):Promise.reject("not support")},_enableVideoDecodeFallback(e,t){return nw(this,null,(function*(){return this.startPlugin(kG.Name,{type:"webCodecs",renderer:"videoFrame",track:e,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise(((t,i)=>{$U(OV(e,"decode-downgrade-state-changed"),QV((e=>"STARTED"===e.state)),ZV(1),rB(1e4),eF(OV(e,zL.INIT)),tB(t,i))}))}))}}),wL(37),Fz}));
|
|
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},i=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")(),r={},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,l=Function.prototype.call,c=s?l.bind(l):function(){return l.apply(l,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,P=function(e){if(O(e))throw new M("Can't call method on "+e);return e},L=N,x=P,U=function(e){return L(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=i,G=F,j=function(e,t){return arguments.length<2?(i=W[e],G(i)?i:void 0):W[e]&&W[e][t];var i},z=T({}.isPrototypeOf),K=i.navigator,q=K&&K.userAgent,Y=q?String(q):"",J=i,X=Y,Q=J.process,$=J.Deno,Z=Q&&Q.versions||$&&$.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,ie=te,re=o,oe=i.String,ne=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol("symbol detection");return!oe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),ae=ne&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,se=j,le=F,ce=z,de=Object,ue=ae?function(e){return"symbol"==typeof e}:function(e){var t=se("Symbol");return le(t)&&ce(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 i=e[t];return ve(i)?void 0:Ee(i)},Te=c,Ie=F,Ae=H,Se=TypeError,Re={exports:{}},be=i,we=Object.defineProperty,Ce=function(e,t){try{we(be,e,{value:t,configurable:!0,writable:!0})}catch(i){be[e]=t}return t},De=i,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,Pe=Me,Le=function(e,t){return Pe[e]||(Pe[e]=t||{})},xe=P,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,Ge=0,je=Math.random(),ze=We(1..toString),Ke=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ze(++Ge+je,36)},qe=Le,Ye=He,Je=Ke,Xe=ne,Qe=ae,$e=i.Symbol,Ze=qe("wks"),et=Qe?$e.for||$e:$e&&$e.withoutSetter||Je,tt=function(e){return Ye(Ze,e)||(Ze[e]=Xe&&Ye($e,e)?$e[e]:et("Symbol."+e)),Ze[e]},it=c,rt=H,ot=ue,nt=ye,at=function(e,t){var i,r;if("string"===t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;if(Ie(i=e.valueOf)&&!Ae(r=Te(i,e)))return r;if("string"!==t&&Ie(i=e.toString)&&!Ae(r=Te(i,e)))return r;throw new Se("Can't convert object to primitive value")},st=TypeError,lt=tt("toPrimitive"),ct=function(e,t){if(!rt(e)||ot(e))return e;var i,r=nt(e,lt);if(r){if(void 0===t&&(t="default"),i=it(r,e,t),!rt(i)||ot(i))return i;throw new st("Can't convert object to primitive value")}return void 0===t&&(t="number"),at(e,t)},dt=ct,ut=ue,ht=function(e){var t=dt(e,"string");return ut(t)?t:t+""},pt=H,mt=i.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=c,Tt=d,It=_,At=U,St=ht,Rt=He,bt=Et,wt=Object.getOwnPropertyDescriptor;r.f=vt?wt:function(e,t){if(e=At(e),t=St(t),bt)try{return wt(e,t)}catch(i){}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")},Pt=n,Lt=Et,xt=Dt,Ut=Mt,Vt=ht,Ft=TypeError,Bt=Object.defineProperty,Ht=Object.getOwnPropertyDescriptor,Wt="enumerable",Gt="configurable",jt="writable";Ct.f=Pt?xt?function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),"function"==typeof e&&"prototype"===t&&"value"in i&&jt in i&&!i[jt]){var r=Ht(e,t);r&&r[jt]&&(e[t]=i.value,i={configurable:Gt in i?i[Gt]:r[Gt],enumerable:Wt in i?i[Wt]:r[Wt],writable:!1})}return Bt(e,t,i)}:Bt:function(e,t,i){if(Ut(e),t=Vt(t),Ut(i),Lt)try{return Bt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Ft("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var zt=Ct,Kt=_,qt=n?function(e,t,i){return zt.f(e,t,Kt(1,i))}:function(e,t,i){return e[t]=i,e},Yt={exports:{}},Jt=n,Xt=He,Qt=Function.prototype,$t=Jt&&Object.getOwnPropertyDescriptor,Zt=Xt(Qt,"name"),ei={EXISTS:Zt,PROPER:Zt&&"something"===function(){}.name,CONFIGURABLE:Zt&&(!Jt||Jt&&$t(Qt,"name").configurable)},ti=F,ii=Me,ri=T(Function.toString);ti(ii.inspectSource)||(ii.inspectSource=function(e){return ri(e)});var oi,ni,ai,si=ii.inspectSource,li=F,ci=i.WeakMap,di=li(ci)&&/native code/.test(String(ci)),ui=Ke,hi=Le("keys"),pi=function(e){return hi[e]||(hi[e]=ui(e))},mi={},fi=di,_i=i,gi=H,Ei=qt,vi=He,yi=Me,Ti=pi,Ii=mi,Ai="Object already initialized",Si=_i.TypeError,Ri=_i.WeakMap;if(fi||yi.state){var bi=yi.state||(yi.state=new Ri);bi.get=bi.get,bi.has=bi.has,bi.set=bi.set,oi=function(e,t){if(bi.has(e))throw new Si(Ai);return t.facade=e,bi.set(e,t),t},ni=function(e){return bi.get(e)||{}},ai=function(e){return bi.has(e)}}else{var wi=Ti("state");Ii[wi]=!0,oi=function(e,t){if(vi(e,wi))throw new Si(Ai);return t.facade=e,Ei(e,wi,t),t},ni=function(e){return vi(e,wi)?e[wi]:{}},ai=function(e){return vi(e,wi)}}var Ci={set:oi,get:ni,has:ai,enforce:function(e){return ai(e)?ni(e):oi(e,{})},getterFor:function(e){return function(t){var i;if(!gi(t)||(i=ni(t)).type!==e)throw new Si("Incompatible receiver, "+e+" required");return i}}},Di=T,Ni=o,ki=F,Oi=He,Mi=n,Pi=ei.CONFIGURABLE,Li=si,xi=Ci.enforce,Ui=Ci.get,Vi=String,Fi=Object.defineProperty,Bi=Di("".slice),Hi=Di("".replace),Wi=Di([].join),Gi=Mi&&!Ni((function(){return 8!==Fi((function(){}),"length",{value:8}).length})),ji=String(String).split("String"),zi=Yt.exports=function(e,t,i){"Symbol("===Bi(Vi(t),0,7)&&(t="["+Hi(Vi(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Oi(e,"name")||Pi&&e.name!==t)&&(Mi?Fi(e,"name",{value:t,configurable:!0}):e.name=t),Gi&&i&&Oi(i,"arity")&&e.length!==i.arity&&Fi(e,"length",{value:i.arity});try{i&&Oi(i,"constructor")&&i.constructor?Mi&&Fi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(o){}var r=xi(e);return Oi(r,"source")||(r.source=Wi(ji,"string"==typeof t?t:"")),e};Function.prototype.toString=zi((function(){return ki(this)&&Ui(this).source||Li(this)}),"toString");var Ki=Yt.exports,qi=F,Yi=Ct,Ji=Ki,Xi=Ce,Qi=function(e,t,i,r){r||(r={});var o=r.enumerable,n=void 0!==r.name?r.name:t;if(qi(i)&&Ji(i,n,r),r.global)o?e[t]=i:Xi(t,i);else{try{r.unsafe?e[t]&&(o=!0):delete e[t]}catch(a){}o?e[t]=i:Yi.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},$i={},Zi=Math.ceil,er=Math.floor,tr=Math.trunc||function(e){var t=+e;return(t>0?er:Zi)(t)},ir=tr,rr=function(e){var t=+e;return t!=t||0===t?0:ir(t)},or=rr,nr=Math.max,ar=Math.min,sr=function(e,t){var i=or(e);return i<0?nr(i+t,0):ar(i,t)},lr=rr,cr=Math.min,dr=function(e){var t=lr(e);return t>0?cr(t,9007199254740991):0},ur=dr,hr=function(e){return ur(e.length)},pr=U,mr=sr,fr=hr,_r=function(e){return function(t,i,r){var o=pr(t),n=fr(o);if(0===n)return!e&&-1;var a,s=mr(r,n);if(e&&i!=i){for(;n>s;)if((a=o[s++])!=a)return!0}else for(;n>s;s++)if((e||s in o)&&o[s]===i)return e||s||0;return!e&&-1}},gr={includes:_r(!0),indexOf:_r(!1)},Er=He,vr=U,yr=gr.indexOf,Tr=mi,Ir=T([].push),Ar=function(e,t){var i,r=vr(e),o=0,n=[];for(i in r)!Er(Tr,i)&&Er(r,i)&&Ir(n,i);for(;t.length>o;)Er(r,i=t[o++])&&(~yr(n,i)||Ir(n,i));return n},Sr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Rr=Ar,br=Sr.concat("length","prototype");$i.f=Object.getOwnPropertyNames||function(e){return Rr(e,br)};var wr={};wr.f=Object.getOwnPropertySymbols;var Cr=j,Dr=$i,Nr=wr,kr=Mt,Or=T([].concat),Mr=Cr("Reflect","ownKeys")||function(e){var t=Dr.f(kr(e)),i=Nr.f;return i?Or(t,i(e)):t},Pr=He,Lr=Mr,xr=r,Ur=Ct,Vr=function(e,t,i){for(var r=Lr(t),o=Ur.f,n=xr.f,a=0;a<r.length;a++){var s=r[a];Pr(e,s)||i&&Pr(i,s)||o(e,s,n(t,s))}},Fr=o,Br=F,Hr=/#|\.prototype\./,Wr=function(e,t){var i=jr[Gr(e)];return i===Kr||i!==zr&&(Br(t)?Fr(t):!!t)},Gr=Wr.normalize=function(e){return String(e).replace(Hr,".").toLowerCase()},jr=Wr.data={},zr=Wr.NATIVE="N",Kr=Wr.POLYFILL="P",qr=Wr,Yr=i,Jr=r.f,Xr=qt,Qr=Qi,$r=Ce,Zr=Vr,eo=qr,to=function(e,t){var i,r,o,n,a,s=e.target,l=e.global,c=e.stat;if(i=l?Yr:c?Yr[s]||$r(s,{}):Yr[s]&&Yr[s].prototype)for(r in t){if(n=t[r],o=e.dontCallGetSet?(a=Jr(i,r))&&a.value:i[r],!eo(l?r:s+(c?".":"#")+r,e.forced)&&void 0!==o){if(typeof n==typeof o)continue;Zr(n,o)}(e.sham||o&&o.sham)&&Xr(n,"sham",!0),Qr(i,r,n,e)}},io={};io[tt("toStringTag")]="z";var ro="[object z]"===String(io),oo=F,no=R,ao=tt("toStringTag"),so=Object,lo="Arguments"===no(function(){return arguments}()),co=ro?no: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=so(e),ao))?i:lo?no(t):"Object"===(r=no(t))&&oo(t.callee)?"Arguments":r},uo=co,ho=String,po=function(e){if("Symbol"===uo(e))throw new TypeError("Cannot convert a Symbol value to a string");return ho(e)},mo=Ki,fo=Ct,_o=function(e,t,i){return i.get&&mo(i.get,t,{getter:!0}),i.set&&mo(i.set,t,{setter:!0}),fo.f(e,t,i)},go=to,Eo=n,vo=T,yo=He,To=F,Io=z,Ao=po,So=_o,Ro=Vr,bo=i.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\((.*)\)[^)]+$/,Po=vo("".replace),Lo=vo("".slice);So(wo,"description",{configurable:!0,get:function(){var e=ko(this);if(yo(Co,e))return"";var t=Oo(e),i=No?Lo(t,7,-1):Po(t,Mo,"$1");return""===i?void 0:i}}),go({global:!0,constructor:!0,forced:!0},{Symbol:Do})}var xo=i,Uo={},Vo=tt;Uo.f=Vo;var Fo=xo,Bo=He,Ho=Uo,Wo=Ct.f,Go=function(e){var t=Fo.Symbol||(Fo.Symbol={});Bo(t,e)||Wo(t,e,{value:Ho.f(e)})};Go("asyncIterator");var jo=R,zo=Array.isArray||function(e){return"Array"===jo(e)},Ko=TypeError,qo=R,Yo=T,Jo=function(e){if("Function"===qo(e))return Yo(e)},Xo=ge,Qo=a,$o=Jo(Jo.bind),Zo=function(e,t){return Xo(e),void 0===t?e:Qo?$o(e,t):function(){return e.apply(t,arguments)}},en=zo,tn=hr,rn=function(e){if(e>9007199254740991)throw Ko("Maximum allowed index exceeded");return e},on=Zo,nn=function(e,t,i,r,o,n,a,s){for(var l,c,d=o,u=0,h=!!a&&on(a,s);u<r;)u in i&&(l=h?h(i[u],u,t):i[u],n>0&&en(l)?(c=tn(l),d=nn(e,t,l,c,d,n-1)-1):(rn(d+1),e[d]=l),d++),u++;return d},an=nn,sn=T,ln=o,cn=F,dn=co,un=si,hn=function(){},pn=j("Reflect","construct"),mn=/^\s*(?:class|function)\b/,fn=sn(mn.exec),_n=!mn.test(hn),gn=function(e){if(!cn(e))return!1;try{return pn(hn,[],e),!0}catch(t){return!1}},En=function(e){if(!cn(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||ln((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=hr,Nn=rr,kn=bn;to({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,t=Cn(this),i=Dn(t),r=kn(t,0);return r.length=wn(r,t,t,i,0,void 0===e?1:Nn(e)),r}});var On={},Mn=Ar,Pn=Sr,Ln=Object.keys||function(e){return Mn(e,Pn)},xn=n,Un=Dt,Vn=Ct,Fn=Mt,Bn=U,Hn=Ln;On.f=xn&&!Un?Object.defineProperties:function(e,t){Fn(e);for(var i,r=Bn(t),o=Hn(t),n=o.length,a=0;n>a;)Vn.f(e,i=o[a++],r[i]);return e};var Wn,Gn=j("document","documentElement"),jn=Mt,zn=On,Kn=Sr,qn=mi,Yn=Gn,Jn=_t,Xn="prototype",Qn="script",$n=pi("IE_PROTO"),Zn=function(){},ea=function(e){return"<"+Qn+">"+e+"</"+Qn+">"},ta=function(e){e.write(ea("")),e.close();var t=e.parentWindow.Object;return e=null,t},ia=function(){try{Wn=new ActiveXObject("htmlfile")}catch(t){}ia="undefined"!=typeof document?document.domain&&Wn?ta(Wn):function(){var e,t=Jn("iframe"),i="java"+Qn+":";return t.style.display="none",Yn.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(ea("document.F=Object")),e.close(),e.F}():ta(Wn);for(var e=Kn.length;e--;)delete ia[Xn][Kn[e]];return ia()};qn[$n]=!0;var ra=Object.create||function(e,t){var i;return null!==e?(Zn[Xn]=jn(e),i=new Zn,Zn[Xn]=null,i[$n]=e):i=ia(),void 0===t?i:zn.f(i,t)},oa=tt,na=ra,aa=Ct.f,sa=oa("unscopables"),la=Array.prototype;void 0===la[sa]&&aa(la,sa,{configurable:!0,value:na(null)});var ca=function(e){la[sa][e]=!0},da=gr.includes,ua=ca;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=pi("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 i=t.constructor;return Ea(i)&&t instanceof i?i.prototype:t instanceof Ia?Aa:null},Ra=o,ba=F,wa=H,Ca=Sa,Da=Qi,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},Pa=Ct.f,La=He,xa=tt("toStringTag"),Ua=function(e,t,i){e&&!i&&(e=e.prototype),e&&!La(e,xa)&&Pa(e,xa,{configurable:!0,value:t})},Va=Ma.IteratorPrototype,Fa=ra,Ba=_,Ha=Ua,Wa=fa,Ga=function(){return this},ja=function(e,t,i,r){var o=t+" Iterator";return e.prototype=Fa(Va,{next:Ba(+!r,i)}),Ha(e,o,!1),Wa[o]=Ga,e},za=T,Ka=ge,qa=H,Ya=function(e){return qa(e)||null===e},Ja=String,Xa=TypeError,Qa=function(e,t,i){try{return za(Ka(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},$a=H,Za=P,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,i={};try{(e=Qa(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return Za(i),es(r),$a(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0),is=to,rs=c,os=F,ns=ja,as=Sa,ss=ts,ls=Ua,cs=qt,ds=Qi,us=fa,hs=ei.PROPER,ps=ei.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,i,r,o,n,a){ns(i,t,r);var s,l,c,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 i(this,e)}}return function(){return new i(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)),ls(s,u,!0)),hs&&o===Es&&m&&m.name!==Es&&(ps?cs(p,"name",Es):(h=!0,f=function(){return rs(m,this)})),o)if(l={values:d(Es),keys:n?f:d(gs),entries:d(vs)},a)for(c in l)(fs||h||!(c in p))&&ds(p,c,l[c]);else is({target:t,proto:!0,forced:fs||h},l);return p[_s]!==f&&ds(p,_s,f,{name:o}),us[t]=f,l},Is=function(e,t){return{value:e,done:t}},As=U,Ss=ca,Rs=fa,bs=Ci,ws=Ct.f,Cs=Ts,Ds=Is,Ns=n,ks="Array Iterator",Os=bs.set,Ms=bs.getterFor(ks),Ps=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,i=e.index++;if(!t||i>=t.length)return e.target=null,Ds(void 0,!0);switch(e.kind){case"keys":return Ds(i,!1);case"values":return Ds(t[i],!1)}return Ds([i,t[i]],!1)}),"values"),Ls=Rs.Arguments=Rs.Array;if(Ss("keys"),Ss("values"),Ss("entries"),Ns&&"values"!==Ls.name)try{ws(Ls,"name",{value:"values"})}catch(QK){}var xs=ge,Us=Ve,Vs=N,Fs=hr,Bs=TypeError,Hs="Reduce of empty array with no initial value",Ws=function(e){return function(t,i,r,o){var n=Us(t),a=Vs(n),s=Fs(n);if(xs(i),0===s&&r<2)throw new Bs(Hs);var l=e?s-1:0,c=e?-1:1;if(r<2)for(;;){if(l in a){o=a[l],l+=c;break}if(l+=c,e?l<0:s<=l)throw new Bs(Hs)}for(;e?l>=0:s>l;l+=c)l in a&&(o=i(o,a[l],l,n));return o}},Gs={left:Ws(!1),right:Ws(!0)},js=o,zs=function(e,t){var i=[][e];return!!i&&js((function(){i.call(null,t||function(){return 1},1)}))},Ks=i,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",Qs="NODE"===Xs,$s=Gs.left;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduce")},{reduce:function(e){var t=arguments.length;return $s(this,e,t,t>1?arguments[1]:void 0)}});var Zs=Gs.right;to({target:"Array",proto:!0,forced:!Qs&&te>79&&te<83||!zs("reduceRight")},{reduceRight:function(e){return Zs(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var el=to,tl=zo,il=T([].reverse),rl=[1,2];el({target:"Array",proto:!0,forced:String(rl)===String(rl.reverse())},{reverse:function(){return tl(this)&&(this.length=this.length),il(this)}});var ol=pe,nl=TypeError,al=T([].slice),sl=al,ll=Math.floor,cl=function(e,t){var i=e.length;if(i<8)for(var r,o,n=1;n<i;){for(o=n,r=e[n];o&&t(e[o-1],r)>0;)e[o]=e[--o];o!==n++&&(e[o]=r)}else for(var a=ll(i/2),s=cl(sl(e,0,a),t),l=cl(sl(e,a),t),c=s.length,d=l.length,u=0,h=0;u<c||h<d;)e[u+h]=u<c&&h<d?t(s[u],l[h])<=0?s[u++]:l[h++]:u<c?s[u++]:l[h++];return e},dl=cl,ul=Y.match(/firefox\/(\d+)/i),hl=!!ul&&+ul[1],pl=/MSIE|Trident/.test(Y),ml=Y.match(/AppleWebKit\/(\d+)\./),fl=!!ml&&+ml[1],_l=to,gl=T,El=ge,vl=Ve,yl=hr,Tl=function(e,t){if(!delete e[t])throw new nl("Cannot delete property "+ol(t)+" of "+ol(e))},Il=po,Al=o,Sl=dl,Rl=zs,bl=hl,wl=pl,Cl=te,Dl=fl,Nl=[],kl=gl(Nl.sort),Ol=gl(Nl.push),Ml=Al((function(){Nl.sort(void 0)})),Pl=Al((function(){Nl.sort(null)})),Ll=Rl("sort"),xl=!Al((function(){if(Cl)return Cl<70;if(!(bl&&bl>3)){if(wl)return!0;if(Dl)return Dl<603;var e,t,i,r,o="";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++)Nl.push({k:t+r,v:i})}for(Nl.sort((function(e,t){return t.v-e.v})),r=0;r<Nl.length;r++)t=Nl[r].k.charAt(0),o.charAt(o.length-1)!==t&&(o+=t);return"DGBEFHACIJK"!==o}}));_l({target:"Array",proto:!0,forced:Ml||!Pl||!Ll||!xl},{sort:function(e){void 0!==e&&El(e);var t=vl(this);if(xl)return void 0===e?kl(t):kl(t,e);var i,r,o=[],n=yl(t);for(r=0;r<n;r++)r in t&&Ol(o,t[r]);for(Sl(o,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Il(t)>Il(i)?1:-1}}(e)),i=yl(o),r=0;r<i;)t[r]=o[r++];for(;r<n;)Tl(t,r++);return t}}),ca("flat");var Ul="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Vl=Qi,Fl=function(e,t,i){for(var r in t)Vl(e,r,t[r],i);return e},Bl=z,Hl=TypeError,Wl=function(e,t){if(Bl(t,e))return e;throw new Hl("Incorrect invocation")},Gl=rr,jl=dr,zl=RangeError,Kl=function(e){if(void 0===e)return 0;var t=Gl(e),i=jl(t);if(t!==i)throw new zl("Wrong length or index");return i},ql=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},Yl=4503599627370496,Jl=ql,Xl=function(e){return e+Yl-Yl},Ql=Math.abs,$l=function(e,t,i,r){var o=+e,n=Ql(o),a=Jl(o);if(n<r)return a*Xl(n/r/t)*r*t;var s=(1+t/2220446049250313e-31)*n,l=s-(s-n);return l>i||l!=l?Infinity*a:a*l},Zl=Math.fround||function(e){return $l(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},ec=Array,tc=Math.abs,ic=Math.pow,rc=Math.floor,oc=Math.log,nc=Math.LN2,ac={pack:function(e,t,i){var r,o,n,a=ec(i),s=8*i-t-1,l=(1<<s)-1,c=l>>1,d=23===t?ic(2,-24)-ic(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tc(e))!=e||Infinity===e?(o=e!=e?1:0,r=l):(r=rc(oc(e)/nc),e*(n=ic(2,-r))<1&&(r--,n*=2),(e+=r+c>=1?d/n:d*ic(2,1-c))*n>=2&&(r++,n/=2),r+c>=l?(o=0,r=l):r+c>=1?(o=(e*n-1)*ic(2,t),r+=c):(o=e*ic(2,c-1)*ic(2,t),r=0));t>=8;)a[h++]=255&o,o/=256,t-=8;for(r=r<<t|o,s+=t;s>0;)a[h++]=255&r,r/=256,s-=8;return a[h-1]|=128*u,a},unpack:function(e,t){var i,r=e.length,o=8*r-t-1,n=(1<<o)-1,a=n>>1,s=o-7,l=r-1,c=e[l--],d=127&c;for(c>>=7;s>0;)d=256*d+e[l--],s-=8;for(i=d&(1<<-s)-1,d>>=-s,s+=t;s>0;)i=256*i+e[l--],s-=8;if(0===d)d=1-a;else{if(d===n)return i?NaN:c?-Infinity:Infinity;i+=ic(2,t),d-=a}return(c?-1:1)*i*ic(2,d-t)}},sc=Ve,lc=sr,cc=hr,dc=function(e){for(var t=sc(this),i=cc(t),r=arguments.length,o=lc(r>1?arguments[1]:void 0,i),n=r>2?arguments[2]:void 0,a=void 0===n?i:lc(n,i);a>o;)t[o++]=e;return t},uc=F,hc=H,pc=ts,mc=function(e,t,i){var r,o;return pc&&uc(r=t.constructor)&&r!==i&&hc(o=r.prototype)&&o!==i.prototype&&pc(e,o),e},fc=i,_c=T,gc=n,Ec=Ul,vc=qt,yc=_o,Tc=Fl,Ic=o,Ac=Wl,Sc=rr,Rc=dr,bc=Kl,wc=Zl,Cc=ac,Dc=Sa,Nc=ts,kc=dc,Oc=al,Mc=mc,Pc=Vr,Lc=Ua,xc=Ci,Uc=ei.PROPER,Vc=ei.CONFIGURABLE,Fc="ArrayBuffer",Bc="DataView",Hc="prototype",Wc="Wrong index",Gc=xc.getterFor(Fc),jc=xc.getterFor(Bc),zc=xc.set,Kc=fc[Fc],qc=Kc,Yc=qc&&qc[Hc],Jc=fc[Bc],Xc=Jc&&Jc[Hc],Qc=Object.prototype,$c=fc.Array,Zc=fc.RangeError,ed=_c(kc),td=_c([].reverse),id=Cc.pack,rd=Cc.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]},ld=function(e){return id(wc(e),23,4)},cd=function(e){return id(e,52,8)},dd=function(e,t,i){yc(e[Hc],t,{configurable:!0,get:function(){return i(this)[t]}})},ud=function(e,t,i,r){var o=jc(e),n=bc(i),a=!!r;if(n+t>o.byteLength)throw new Zc(Wc);var s=o.bytes,l=n+o.byteOffset,c=Oc(s,l,l+t);return a?c:td(c)},hd=function(e,t,i,r,o,n){var a=jc(e),s=bc(i),l=r(+o),c=!!n;if(s+t>a.byteLength)throw new Zc(Wc);for(var d=a.bytes,u=s+a.byteOffset,h=0;h<t;h++)d[u+h]=l[c?h:t-h-1]};if(Ec){var pd=Uc&&Kc.name!==Fc;Ic((function(){Kc(1)}))&&Ic((function(){new Kc(-1)}))&&!Ic((function(){return new Kc,new Kc(1.5),new Kc(NaN),1!==Kc.length||pd&&!Vc}))?pd&&Vc&&vc(Kc,"name",Fc):((qc=function(e){return Ac(this,Yc),Mc(new Kc(bc(e)),this,qc)})[Hc]=Yc,Yc.constructor=qc,Pc(qc,Kc)),Nc&&Dc(Xc)!==Qc&&Nc(Xc,Qc);var md=new Jc(new qc(2)),fd=_c(Xc.setInt8);md.setInt8(0,2147483648),md.setInt8(1,2147483649),!md.getInt8(0)&&md.getInt8(1)||Tc(Xc,{setInt8:function(e,t){fd(this,e,t<<24>>24)},setUint8:function(e,t){fd(this,e,t<<24>>24)}},{unsafe:!0})}else Yc=(qc=function(e){Ac(this,Yc);var t=bc(e);zc(this,{type:Fc,bytes:ed($c(t),0),byteLength:t}),gc||(this.byteLength=t,this.detached=!1)})[Hc],Xc=(Jc=function(e,t,i){Ac(this,Xc),Ac(e,Yc);var r=Gc(e),o=r.byteLength,n=Sc(t);if(n<0||n>o)throw new Zc("Wrong offset");if(n+(i=void 0===i?o-n:Rc(i))>o)throw new Zc("Wrong length");zc(this,{type:Bc,buffer:e,byteLength:i,byteOffset:n,bytes:r.bytes}),gc||(this.buffer=e,this.byteLength=i,this.byteOffset=n)})[Hc],gc&&(dd(qc,"byteLength",Gc),dd(Jc,"buffer",jc),dd(Jc,"byteLength",jc),dd(Jc,"byteOffset",jc)),Tc(Xc,{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 rd(ud(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return rd(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,ld,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){hd(this,8,e,cd,t,arguments.length>2&&arguments[2])}});Lc(qc,Fc),Lc(Jc,Bc);var _d={ArrayBuffer:qc,DataView:Jc},gd=j,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:i[Ad]!==Sd},{ArrayBuffer:Sd}),Id(Ad);var Rd=to,bd=Jo,wd=o,Cd=Mt,Dd=sr,Nd=dr,kd=_d.ArrayBuffer,Od=_d.DataView,Md=Od.prototype,Pd=bd(kd.prototype.slice),Ld=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(Pd&&void 0===t)return Pd(Cd(this),e);for(var i=Cd(this).byteLength,r=Dd(e,i),o=Dd(void 0===t?i:t,i),n=new kd(Nd(o-r)),a=new Od(this),s=new Od(n),l=0;r<o;)xd(s,l++,Ld(a,r++));return n}});var Ud,Vd,Fd,Bd,Hd=vn,Wd=pe,Gd=TypeError,jd=function(e){if(Hd(e))return e;throw new Gd(Wd(e)+" is not a constructor")},zd=Mt,Kd=jd,qd=k,Yd=tt("species"),Jd=function(e,t){var i,r=zd(e).constructor;return void 0===r||qd(i=zd(r)[Yd])?t:Kd(i)},Xd=a,Qd=Function.prototype,$d=Qd.apply,Zd=Qd.call,eu="object"==typeof Reflect&&Reflect.apply||(Xd?Zd.bind($d):function(){return Zd.apply($d,arguments)}),tu=TypeError,iu=function(e,t){if(e<t)throw new tu("Not enough arguments");return e},ru=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ou=i,nu=eu,au=Zo,su=F,lu=He,cu=o,du=Gn,uu=al,hu=_t,pu=iu,mu=ru,fu=Qs,_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";cu((function(){Ud=ou.location}));var bu=function(e){if(lu(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),i=uu(arguments,1);return Su[++Au]=function(){nu(t,void 0,i)},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&&!cu(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=i,Ou=n,Mu=Object.getOwnPropertyDescriptor,Pu=function(e){if(!Ou)return ku[e];var t=Mu(ku,e);return t&&t.value},Lu=function(){this.head=null,this.tail=null};Lu.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 xu,Uu,Vu,Fu,Bu,Hu=Lu,Wu=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,Gu=/web0s(?!.*chrome)/i.test(Y),ju=i,zu=Pu,Ku=Zo,qu=Nu.set,Yu=Hu,Ju=ru,Xu=Wu,Qu=Gu,$u=Qs,Zu=ju.MutationObserver||ju.WebKitMutationObserver,eh=ju.document,th=ju.process,ih=ju.Promise,rh=zu("queueMicrotask");if(!rh){var oh=new Yu,nh=function(){var e,t;for($u&&(e=th.domain)&&e.exit();t=oh.get();)try{t()}catch(QK){throw oh.head&&xu(),QK}e&&e.enter()};Ju||$u||Qu||!Zu||!eh?!Xu&&ih&&ih.resolve?((Fu=ih.resolve(void 0)).constructor=ih,Bu=Ku(Fu.then,Fu),xu=function(){Bu(nh)}):$u?xu=function(){th.nextTick(nh)}:(qu=Ku(qu,ju),xu=function(){qu(nh)}):(Uu=!0,Vu=eh.createTextNode(""),new Zu(nh).observe(Vu,{characterData:!0}),xu=function(){Vu.data=Uu=!Uu}),rh=function(e){oh.head||xu(),oh.add(e)}}var ah=rh,sh=function(e){try{return{error:!1,value:e()}}catch(QK){return{error:!0,value:QK}}},lh=i.Promise,ch=i,dh=lh,uh=F,hh=qr,ph=si,mh=tt,fh=Xs,_h=te;dh&&dh.prototype;var gh=mh("species"),Eh=!1,vh=uh(ch.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 i=new dh((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[gh]=r,!(Eh=i.then((function(){}))instanceof r))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,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw new Sh("Bad Promise constructor");t=e,i=r})),this.resolve=Ah(t),this.reject=Ah(i)};Ih.f=function(e){return new Rh(e)};var bh,wh,Ch,Dh=to,Nh=Qs,kh=i,Oh=c,Mh=Qi,Ph=ts,Lh=Ua,xh=Td,Uh=ge,Vh=F,Fh=H,Bh=Wl,Hh=Jd,Wh=Nu.set,Gh=ah,jh=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(QK){}},zh=sh,Kh=Hu,qh=Ci,Yh=lh,Jh=Ih,Xh="Promise",Qh=Th.CONSTRUCTOR,$h=Th.REJECTION_EVENT,Zh=Th.SUBCLASSING,ep=qh.getterFor(Xh),tp=qh.set,ip=Yh&&Yh.prototype,rp=Yh,op=ip,np=kh.TypeError,ap=kh.document,sp=kh.process,lp=Jh.f,cp=lp,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 i,r,o,n=t.value,a=1===t.state,s=a?e.ok:e.fail,l=e.resolve,c=e.reject,d=e.domain;try{s?(a||(2===t.rejection&&Ep(t),t.rejection=1),!0===s?i=n:(d&&d.enter(),i=s(n),d&&(d.exit(),o=!0)),i===e.promise?c(new np("Promise-chain cycle")):(r=hp(i))?Oh(r,i,l,c):l(i)):c(n)}catch(QK){d&&!o&&d.exit(),c(QK)}},mp=function(e,t){e.notified||(e.notified=!0,Gh((function(){for(var i,r=e.reactions;i=r.get();)pp(i,e);e.notified=!1,t&&!e.rejection&&_p(e)})))},fp=function(e,t,i){var r,o;dp?((r=ap.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),kh.dispatchEvent(r)):r={promise:t,reason:i},!$h&&(o=kh["on"+e])?o(r):e===up&&jh("Unhandled promise rejection",i)},_p=function(e){Oh(Wh,kh,(function(){var t,i=e.facade,r=e.value;if(gp(e)&&(t=zh((function(){Nh?sp.emit("unhandledRejection",r,i):fp(up,i,r)})),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,i){return function(r){e(t,r,i)}},yp=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,mp(e,!0))},Tp=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new np("Promise can't be resolved itself");var r=hp(t);r?Gh((function(){var i={done:!1};try{Oh(r,t,vp(Tp,i,e),vp(yp,i,e))}catch(QK){yp(i,QK,e)}})):(e.value=t,e.state=1,mp(e,!1))}catch(QK){yp({done:!1},QK,e)}}};if(Qh&&(op=(rp=function(e){Bh(this,op),Uh(e),Oh(bh,this);var t=ep(this);try{e(vp(Tp,t),vp(yp,t))}catch(QK){yp(t,QK)}}).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 i=ep(this),r=lp(Hh(this,rp));return i.parent=!0,r.ok=!Vh(e)||e,r.fail=Vh(t)&&t,r.domain=Nh?sp.domain:void 0,0===i.state?i.reactions.add(r):Gh((function(){pp(r,i)})),r.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=lp=function(e){return e===rp||undefined===e?new wh(e):cp(e)},Vh(Yh)&&ip!==Object.prototype)){Ch=ip.then,Zh||Mh(ip,"then",(function(e,t){var i=this;return new rp((function(e,t){Oh(Ch,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete ip.constructor}catch(QK){}Ph&&Ph(ip,op)}Dh({global:!0,constructor:!0,wrap:!0,forced:Qh},{Promise:rp}),Lh(rp,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=co,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=c,Mp=ge,Pp=Mt,Lp=pe,xp=kp,Up=TypeError,Vp=function(e,t){var i=arguments.length<2?xp(e):t;if(Mp(i))return Pp(Op(i,e));throw new Up(Lp(e)+" is not iterable")},Fp=c,Bp=Mt,Hp=ye,Wp=function(e,t,i){var r,o;Bp(e);try{if(!(r=Hp(e,"return"))){if("throw"===t)throw i;return i}r=Fp(r,e)}catch(QK){o=!0,r=QK}if("throw"===t)throw i;if(o)throw r;return Bp(r),i},Gp=Zo,jp=c,zp=Mt,Kp=pe,qp=Rp,Yp=hr,Jp=z,Xp=Vp,Qp=kp,$p=Wp,Zp=TypeError,em=function(e,t){this.stopped=e,this.result=t},tm=em.prototype,im=function(e,t,i){var r,o,n,a,s,l,c,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),f=Gp(t,d),_=function(e){return r&&$p(r,"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)r=e.iterator;else if(p)r=e;else{if(!(o=Qp(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)}r=Xp(e,o)}for(l=h?e.next:r.next;!(c=jp(l,r)).done;){try{s=g(c.value)}catch(QK){$p(r,"throw",QK)}if("object"==typeof s&&s&&Jp(tm,s))return s}return new em(!1)},rm=tt("iterator"),om=!1;try{var nm=0,am={next:function(){return{done:!!nm++}},return:function(){om=!0}};am[rm]=function(){return this},Array.from(am,(function(){throw 2}))}catch(QK){}var sm=function(e,t){try{if(!t&&!om)return!1}catch(QK){return!1}var i=!1;try{var r={};r[rm]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(QK){}return i},lm=lh,cm=Th.CONSTRUCTOR||!sm((function(e){lm.all(e).then(void 0,(function(){}))})),dm=c,um=ge,hm=Ih,pm=sh,mm=im;to({target:"Promise",stat:!0,forced:cm},{all:function(e){var t=this,i=hm.f(t),r=i.resolve,o=i.reject,n=pm((function(){var i=um(t.resolve),n=[],a=0,s=1;mm(e,(function(e){var l=a++,c=!1;s++,dm(i,t,e).then((function(e){c||(c=!0,n[l]=e,--s||r(n))}),o)})),--s||r(n)}));return n.error&&o(n.value),i.promise}});var fm=to,_m=Th.CONSTRUCTOR,gm=lh,Em=j,vm=F,ym=Qi,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=c,Sm=ge,Rm=Ih,bm=sh,wm=im;to({target:"Promise",stat:!0,forced:cm},{race:function(e){var t=this,i=Rm.f(t),r=i.reject,o=bm((function(){var o=Sm(t.resolve);wm(e,(function(e){Am(o,t,e).then(i.resolve,r)}))}));return o.error&&r(o.value),i.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 i=km.f(e);return(0,i.resolve)(t),i.promise},Mm=to,Pm=Th.CONSTRUCTOR,Lm=Om;j("Promise"),Mm({target:"Promise",stat:!0,forced:Pm},{resolve:function(e){return Lm(this,e)}});var xm=to,Um=lh,Vm=o,Fm=j,Bm=F,Hm=Jd,Wm=Om,Gm=Qi,jm=Um&&Um.prototype;if(xm({target:"Promise",proto:!0,real:!0,forced:!!Um&&Vm((function(){jm.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Hm(this,Fm("Promise")),i=Bm(e);return this.then(i?function(i){return Wm(t,e()).then((function(){return i}))}:e,i?function(i){return Wm(t,e()).then((function(){throw i}))}:e)}}),Bm(Um)){var zm=Fm("Promise").prototype.finally;jm.finally!==zm&&Gm(jm,"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,Qm=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},$m=c,Zm=He,ef=z,tf=Qm,rf=RegExp.prototype,of=function(e){var t=e.flags;return void 0!==t||"flags"in rf||Zm(e,"flags")||!ef(rf,e)?t:$m(tf,e)},nf=o,af=i.RegExp,sf=nf((function(){var e=af("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),lf=sf||nf((function(){return!af("a","y").sticky})),cf=sf||nf((function(){var e=af("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),df={BROKEN_CARET:cf,MISSED_STICKY:lf,UNSUPPORTED_Y:sf},uf=Ct.f,hf=o,pf=i.RegExp,mf=hf((function(){var e=pf(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),ff=o,_f=i.RegExp,gf=ff((function(){var e=_f("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Ef=n,vf=i,yf=T,Tf=qr,If=mc,Af=qt,Sf=ra,Rf=$i.f,bf=z,wf=Jm,Cf=po,Df=of,Nf=df,kf=function(e,t,i){i in e||uf(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Of=Qi,Mf=o,Pf=He,Lf=Ci.enforce,xf=Td,Uf=mf,Vf=gf,Ff=tt("match"),Bf=vf.RegExp,Hf=Bf.prototype,Wf=vf.SyntaxError,Gf=yf(Hf.exec),jf=yf("".charAt),zf=yf("".replace),Kf=yf("".indexOf),qf=yf("".slice),Yf=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Jf=/a/g,Xf=/a/g,Qf=new Bf(Jf)!==Jf,$f=Nf.MISSED_STICKY,Zf=Nf.UNSUPPORTED_Y,e_=Ef&&(!Qf||$f||Uf||Vf||Mf((function(){return Xf[Ff]=!1,Bf(Jf)!==Jf||Bf(Xf)===Xf||"/a/i"!==String(Bf(Jf,"i"))})));if(Tf("RegExp",e_)){for(var t_=function(e,t){var i,r,o,n,a,s,l=bf(Hf,this),c=wf(e),d=void 0===t,u=[],h=e;if(!l&&c&&d&&e.constructor===t_)return e;if((c||bf(Hf,e))&&(e=e.source,d&&(t=Df(h))),e=void 0===e?"":Cf(e),t=void 0===t?"":Cf(t),h=e,Uf&&"dotAll"in Jf&&(r=!!t&&Kf(t,"s")>-1)&&(t=zf(t,/s/g,"")),i=t,$f&&"sticky"in Jf&&(o=!!t&&Kf(t,"y")>-1)&&Zf&&(t=zf(t,/y/g,"")),Vf&&(n=function(e){for(var t,i=e.length,r=0,o="",n=[],a=Sf(null),s=!1,l=!1,c=0,d="";r<=i;r++){if("\\"===(t=jf(e,r)))t+=jf(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:if(o+=t,"?:"===qf(e,r+1,r+3))continue;Gf(Yf,qf(e,r+1))&&(r+=2,l=!0),c++;continue;case">"===t&&l:if(""===d||Pf(a,d))throw new Wf("Invalid capture group name");a[d]=!0,n[n.length]=[d,c],l=!1,d="";continue}l?d+=t:o+=t}return[o,n]}(e),e=n[0],u=n[1]),a=If(Bf(e,t),l?this:Hf,t_),(r||o||u.length)&&(s=Lf(a),r&&(s.dotAll=!0,s.raw=t_(function(e){for(var t,i=e.length,r=0,o="",n=!1;r<=i;r++)"\\"!==(t=jf(e,r))?n||"."!==t?("["===t?n=!0:"]"===t&&(n=!1),o+=t):o+="[\\s\\S]":o+=t+jf(e,++r);return o}(e),i)),o&&(s.sticky=!0),u.length&&(s.groups=u)),e!==h)try{Af(a,"source",""===h?"(?:)":h)}catch(QK){}return a},i_=Rf(Bf),r_=0;i_.length>r_;)kf(t_,Bf,i_[r_++]);Hf.constructor=t_,t_.prototype=Hf,Of(vf,"RegExp",t_,{constructor:!0})}xf("RegExp");var o_=c,n_=T,a_=po,s_=Qm,l_=df,c_=ra,d_=Ci.get,u_=mf,h_=gf,p_=Le("native-string-replace",String.prototype.replace),m_=RegExp.prototype.exec,f_=m_,__=n_("".charAt),g_=n_("".indexOf),E_=n_("".replace),v_=n_("".slice),y_=function(){var e=/a/,t=/b*/g;return o_(m_,e,"a"),o_(m_,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),T_=l_.BROKEN_CARET,I_=void 0!==/()??/.exec("")[1];(y_||I_||T_||u_||h_)&&(f_=function(e){var t,i,r,o,n,a,s,l=this,c=d_(l),d=a_(e),u=c.raw;if(u)return u.lastIndex=l.lastIndex,t=o_(f_,u,d),l.lastIndex=u.lastIndex,t;var h=c.groups,p=T_&&l.sticky,m=o_(s_,l),f=l.source,_=0,g=d;if(p&&(m=E_(m,"y",""),-1===g_(m,"g")&&(m+="g"),g=v_(d,l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&"\n"!==__(d,l.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),i=new RegExp("^(?:"+f+")",m)),I_&&(i=new RegExp("^"+f+"$(?!\\s)",m)),y_&&(r=l.lastIndex),o=o_(m_,p?i:l,g),p?o?(o.input=v_(o.input,_),o[0]=v_(o[0],_),o.index=l.lastIndex,l.lastIndex+=o[0].length):l.lastIndex=0:y_&&o&&(l.lastIndex=l.global?o.index+o[0].length:r),I_&&o&&o.length>1&&o_(p_,o[0],i,(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 A_=f_;to({target:"RegExp",proto:!0,forced:/./.exec!==A_},{exec:A_});var S_=n,R_=_o,b_=Qm,w_=o,C_=i.RegExp,D_=C_.prototype,N_=S_&&w_((function(){var e=!0;try{C_(".","d")}catch(QK){e=!1}var t={},i="",r=e?"dgimsy":"gimsy",o=function(e,r){Object.defineProperty(t,e,{get:function(){return i+=r,!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(D_,"flags").get.call(t)!==r||i!==r}));N_&&R_(D_,"flags",{configurable:!0,get:b_});var k_=rr,O_=po,M_=P,P_=RangeError,L_=T,x_=dr,U_=po,V_=function(e){var t=O_(M_(this)),i="",r=k_(e);if(r<0||Infinity===r)throw new P_("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},F_=P,B_=L_(V_),H_=L_("".slice),W_=Math.ceil,G_=function(e){return function(t,i,r){var o,n,a=U_(F_(t)),s=x_(i),l=a.length,c=void 0===r?" ":U_(r);return s<=l||""===c?a:((n=B_(c,W_((o=s-l)/c.length))).length>o&&(n=H_(n,0,o)),e?a+n:n+a)}},j_={start:G_(!1),end:G_(!0)},z_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),K_=j_.start;to({target:"String",proto:!0,forced:z_},{padStart:function(e){return K_(this,e,arguments.length>1?arguments[1]:void 0)}});var q_=c,Y_=Qi,J_=A_,X_=o,Q_=tt,$_=qt,Z_=Q_("species"),eg=RegExp.prototype,tg=T,ig=rr,rg=po,og=P,ng=tg("".charAt),ag=tg("".charCodeAt),sg=tg("".slice),lg=function(e){return function(t,i){var r,o,n=rg(og(t)),a=ig(i),s=n.length;return a<0||a>=s?e?"":void 0:(r=ag(n,a))<55296||r>56319||a+1===s||(o=ag(n,a+1))<56320||o>57343?e?ng(n,a):r:e?sg(n,a,a+2):o-56320+(r-55296<<10)+65536}},cg={codeAt:lg(!1),charAt:lg(!0)},dg=cg.charAt,ug=T,hg=Ve,pg=Math.floor,mg=ug("".charAt),fg=ug("".replace),_g=ug("".slice),gg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Eg=/\$([$&'`]|\d{1,2})/g,vg=function(e,t,i,r,o,n){var a=i+e.length,s=r.length,l=Eg;return void 0!==o&&(o=hg(o),l=gg),fg(n,l,(function(n,l){var c;switch(mg(l,0)){case"$":return"$";case"&":return e;case"`":return _g(t,0,i);case"'":return _g(t,a);case"<":c=o[_g(l,1,-1)];break;default:var d=+l;if(0===d)return n;if(d>s){var u=pg(d/10);return 0===u?n:u<=s?void 0===r[u-1]?mg(l,1):r[u-1]+mg(l,1):n}c=r[d-1]}return void 0===c?"":c}))},yg=c,Tg=Mt,Ig=F,Ag=R,Sg=A_,Rg=TypeError,bg=eu,wg=c,Cg=T,Dg=function(e,t,i,r){var o=Q_(e),n=!X_((function(){var t={};return t[o]=function(){return 7},7!==""[e](t)})),a=n&&!X_((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Z_]=function(){return i},i.flags="",i[o]=/./[o]),i.exec=function(){return t=!0,null},i[o](""),!t}));if(!n||!a||i){var s=/./[o],l=t(o,""[e],(function(e,t,i,r,o){var a=t.exec;return a===J_||a===eg.exec?n&&!o?{done:!0,value:q_(s,t,i,r)}:{done:!0,value:q_(e,i,t,r)}:{done:!1}}));Y_(String.prototype,e,l[0]),Y_(eg,o,l[1])}r&&$_(eg[o],"sham",!0)},Ng=o,kg=Mt,Og=F,Mg=k,Pg=rr,Lg=dr,xg=po,Ug=P,Vg=function(e,t,i){return t+(i?dg(e,t).length:1)},Fg=ye,Bg=vg,Hg=function(e,t){var i=e.exec;if(Ig(i)){var r=yg(i,e,t);return null!==r&&Tg(r),r}if("RegExp"===Ag(e))return yg(Sg,e,t);throw new Rg("RegExp#exec called on incompatible receiver")},Wg=tt("replace"),Gg=Math.max,jg=Math.min,zg=Cg([].concat),Kg=Cg([].push),qg=Cg("".indexOf),Yg=Cg("".slice),Jg="$0"==="a".replace(/./,"$0"),Xg=!!/./[Wg]&&""===/./[Wg]("a","$0"),Qg=!Ng((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Dg("replace",(function(e,t,i){var r=Xg?"$":"$0";return[function(e,i){var r=Ug(this),o=Mg(e)?void 0:Fg(e,Wg);return o?wg(o,e,r,i):wg(t,xg(r),e,i)},function(e,o){var n=kg(this),a=xg(e);if("string"==typeof o&&-1===qg(o,r)&&-1===qg(o,"$<")){var s=i(t,n,a,o);if(s.done)return s.value}var l=Og(o);l||(o=xg(o));var c,d=n.global;d&&(c=n.unicode,n.lastIndex=0);for(var u,h=[];null!==(u=Hg(n,a))&&(Kg(h,u),d);){""===xg(u[0])&&(n.lastIndex=Vg(a,Lg(n.lastIndex),c))}for(var p,m="",f=0,_=0;_<h.length;_++){for(var g,E=xg((u=h[_])[0]),v=Gg(jg(Pg(u.index),a.length),0),y=[],T=1;T<u.length;T++)Kg(y,void 0===(p=u[T])?p:String(p));var I=u.groups;if(l){var A=zg([E],y,v,a);void 0!==I&&Kg(A,I),g=xg(bg(o,void 0,A))}else g=Bg(E,a,v,y,I,o);v>=f&&(m+=Yg(a,f,v)+g,f=v+E.length)}return m+Yg(a,f)}]}),!Qg||!Jg||Xg);var $g="\t\n\v\f\r \u2028\u2029\ufeff",Zg=P,eE=po,tE=$g,iE=T("".replace),rE=RegExp("^["+tE+"]+"),oE=RegExp("(^|[^"+tE+"])["+tE+"]+$"),nE=function(e){return function(t){var i=eE(Zg(t));return 1&e&&(i=iE(i,rE,"")),2&e&&(i=iE(i,oE,"$1")),i}},aE={start:nE(1),end:nE(2),trim:nE(3)},sE=ei.PROPER,lE=o,cE=$g,dE=aE.trim;to({target:"String",proto:!0,forced:function(e){return lE((function(){return!!cE[e]()||"
"!=="
"[e]()||sE&&cE[e].name!==e}))}("trim")},{trim:function(){return dE(this)}});var uE,hE,pE,mE={exports:{}},fE=Ul,_E=n,gE=i,EE=F,vE=H,yE=He,TE=co,IE=pe,AE=qt,SE=Qi,RE=_o,bE=z,wE=Sa,CE=ts,DE=tt,NE=Ke,kE=Ci.enforce,OE=Ci.get,ME=gE.Int8Array,PE=ME&&ME.prototype,LE=gE.Uint8ClampedArray,xE=LE&&LE.prototype,UE=ME&&wE(ME),VE=PE&&wE(PE),FE=Object.prototype,BE=gE.TypeError,HE=DE("toStringTag"),WE=NE("TYPED_ARRAY_TAG"),GE="TypedArrayConstructor",jE=fE&&!!CE&&"Opera"!==TE(gE.opera),zE=!1,KE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},qE={BigInt64Array:8,BigUint64Array:8},YE=function(e){var t=wE(e);if(vE(t)){var i=OE(t);return i&&yE(i,GE)?i[GE]:YE(t)}},JE=function(e){if(!vE(e))return!1;var t=TE(e);return yE(KE,t)||yE(qE,t)};for(uE in KE)(pE=(hE=gE[uE])&&hE.prototype)?kE(pE)[GE]=hE:jE=!1;for(uE in qE)(pE=(hE=gE[uE])&&hE.prototype)&&(kE(pE)[GE]=hE);if((!jE||!EE(UE)||UE===Function.prototype)&&(UE=function(){throw new BE("Incorrect invocation")},jE))for(uE in KE)gE[uE]&&CE(gE[uE],UE);if((!jE||!VE||VE===FE)&&(VE=UE.prototype,jE))for(uE in KE)gE[uE]&&CE(gE[uE].prototype,VE);if(jE&&wE(xE)!==VE&&CE(xE,VE),_E&&!yE(VE,HE))for(uE in zE=!0,RE(VE,HE,{configurable:!0,get:function(){return vE(this)?this[WE]:void 0}}),KE)gE[uE]&&AE(gE[uE],WE,uE);var XE={NATIVE_ARRAY_BUFFER_VIEWS:jE,TYPED_ARRAY_TAG:zE&&WE,aTypedArray:function(e){if(JE(e))return e;throw new BE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(EE(e)&&(!CE||bE(UE,e)))return e;throw new BE(IE(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(_E){if(i)for(var o in KE){var n=gE[o];if(n&&yE(n.prototype,e))try{delete n.prototype[e]}catch(QK){try{n.prototype[e]=t}catch(a){}}}VE[e]&&!i||SE(VE,e,i?t:jE&&PE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,o;if(_E){if(CE){if(i)for(r in KE)if((o=gE[r])&&yE(o,e))try{delete o[e]}catch(QK){}if(UE[e]&&!i)return;try{return SE(UE,e,i?t:jE&&UE[e]||t)}catch(QK){}}for(r in KE)!(o=gE[r])||o[e]&&!i||SE(o,e,t)}},getTypedArrayConstructor:YE,isView:function(e){if(!vE(e))return!1;var t=TE(e);return"DataView"===t||yE(KE,t)||yE(qE,t)},isTypedArray:JE,TypedArray:UE,TypedArrayPrototype:VE},QE=i,$E=o,ZE=sm,ev=XE.NATIVE_ARRAY_BUFFER_VIEWS,tv=QE.ArrayBuffer,iv=QE.Int8Array,rv=!ev||!$E((function(){iv(1)}))||!$E((function(){new iv(-1)}))||!ZE((function(e){new iv,new iv(null),new iv(1.5),new iv(e)}),!0)||$E((function(){return 1!==new iv(new tv(2),1,void 0).length})),ov=H,nv=Math.floor,av=Number.isInteger||function(e){return!ov(e)&&isFinite(e)&&nv(e)===e},sv=rr,lv=RangeError,cv=function(e){var t=sv(e);if(t<0)throw new lv("The argument can't be less than 0");return t},dv=RangeError,uv=function(e,t){var i=cv(e);if(i%t)throw new dv("Wrong offset");return i},hv=Math.round,pv=co,mv=ct,fv=TypeError,_v=function(e){var t=mv(e,"number");if("number"==typeof t)throw new fv("Can't convert number to bigint");return BigInt(t)},gv=Zo,Ev=c,vv=jd,yv=Ve,Tv=hr,Iv=Vp,Av=kp,Sv=Rp,Rv=function(e){var t=pv(e);return"BigInt64Array"===t||"BigUint64Array"===t},bv=XE.aTypedArrayConstructor,wv=_v,Cv=Zo,Dv=N,Nv=Ve,kv=hr,Ov=bn,Mv=T([].push),Pv=function(e){var t=1===e,i=2===e,r=3===e,o=4===e,n=6===e,a=7===e,s=5===e||n;return function(l,c,d,u){for(var h,p,m=Nv(l),f=Dv(m),_=kv(f),g=Cv(c,d),E=0,v=u||Ov,y=t?v(l,_):i||a?v(l,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:Mv(y,h)}else switch(e){case 4:return!1;case 7:Mv(y,h)}return n?-1:r||o?o:y}},Lv={forEach:Pv(0),map:Pv(1),filter:Pv(2),some:Pv(3),every:Pv(4),find:Pv(5),findIndex:Pv(6),filterReject:Pv(7)},xv=hr,Uv=to,Vv=i,Fv=c,Bv=n,Hv=rv,Wv=XE,Gv=_d,jv=Wl,zv=_,Kv=qt,qv=av,Yv=dr,Jv=Kl,Xv=uv,Qv=function(e){var t=hv(e);return t<0?0:t>255?255:255&t},$v=ht,Zv=He,ey=co,ty=H,iy=ue,ry=ra,oy=z,ny=ts,ay=$i.f,sy=function(e){var t,i,r,o,n,a,s,l,c=vv(this),d=yv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Av(d);if(m&&!Sv(m))for(l=(s=Iv(d,m)).next,d=[];!(a=Ev(l,s)).done;)d.push(a.value);for(p&&u>2&&(h=gv(h,arguments[2])),i=Tv(d),r=new(bv(c))(i),o=Rv(r),t=0;i>t;t++)n=p?h(d[t],t):d[t],r[t]=o?wv(n):+n;return r},ly=Lv.forEach,cy=Td,dy=_o,uy=Ct,hy=r,py=function(e,t,i){for(var r=0,o=arguments.length>2?i:xv(t),n=new e(o);o>r;)n[r]=t[r++];return n},my=mc,fy=Ci.get,_y=Ci.set,gy=Ci.enforce,Ey=uy.f,vy=hy.f,yy=Vv.RangeError,Ty=Gv.ArrayBuffer,Iy=Ty.prototype,Ay=Gv.DataView,Sy=Wv.NATIVE_ARRAY_BUFFER_VIEWS,Ry=Wv.TYPED_ARRAY_TAG,by=Wv.TypedArray,wy=Wv.TypedArrayPrototype,Cy=Wv.isTypedArray,Dy="BYTES_PER_ELEMENT",Ny="Wrong length",ky=function(e,t){dy(e,t,{configurable:!0,get:function(){return fy(this)[t]}})},Oy=function(e){var t;return oy(Iy,e)||"ArrayBuffer"===(t=ey(e))||"SharedArrayBuffer"===t},My=function(e,t){return Cy(e)&&!iy(t)&&t in e&&qv(+t)&&t>=0},Py=function(e,t){return t=$v(t),My(e,t)?zv(2,e[t]):vy(e,t)},Ly=function(e,t,i){return t=$v(t),!(My(e,t)&&ty(i)&&Zv(i,"value"))||Zv(i,"get")||Zv(i,"set")||i.configurable||Zv(i,"writable")&&!i.writable||Zv(i,"enumerable")&&!i.enumerable?Ey(e,t,i):(e[t]=i.value,e)};Bv?(Sy||(hy.f=Py,uy.f=Ly,ky(wy,"buffer"),ky(wy,"byteOffset"),ky(wy,"byteLength"),ky(wy,"length")),Uv({target:"Object",stat:!0,forced:!Sy},{getOwnPropertyDescriptor:Py,defineProperty:Ly}),mE.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,o=e+(i?"Clamped":"")+"Array",n="get"+e,a="set"+e,s=Vv[o],l=s,c=l&&l.prototype,d={},u=function(e,t){Ey(e,t,{get:function(){return function(e,t){var i=fy(e);return i.view[n](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,o){var n=fy(e);n.view[a](t*r+n.byteOffset,i?Qv(o):o,!0)}(this,t,e)},enumerable:!0})};Sy?Hv&&(l=t((function(e,t,i,o){return jv(e,c),my(ty(t)?Oy(t)?void 0!==o?new s(t,Xv(i,r),o):void 0!==i?new s(t,Xv(i,r)):new s(t):Cy(t)?py(l,t):Fv(sy,l,t):new s(Jv(t)),e,l)})),ny&&ny(l,by),ly(ay(s),(function(e){e in l||Kv(l,e,s[e])})),l.prototype=c):(l=t((function(e,t,i,o){jv(e,c);var n,a,s,d=0,h=0;if(ty(t)){if(!Oy(t))return Cy(t)?py(l,t):Fv(sy,l,t);n=t,h=Xv(i,r);var p=t.byteLength;if(void 0===o){if(p%r)throw new yy(Ny);if((a=p-h)<0)throw new yy(Ny)}else if((a=Yv(o)*r)+h>p)throw new yy(Ny);s=a/r}else s=Jv(t),n=new Ty(a=s*r);for(_y(e,{buffer:n,byteOffset:h,byteLength:a,length:s,view:new Ay(n)});d<s;)u(e,d++)})),ny&&ny(l,by),c=l.prototype=ry(wy)),c.constructor!==l&&Kv(c,"constructor",l),gy(c).TypedArrayConstructor=l,Ry&&Kv(c,Ry,o);var h=l!==s;d[o]=l,Uv({global:!0,constructor:!0,forced:h,sham:!Sy},d),Dy in l||Kv(l,Dy,r),Dy in c||Kv(c,Dy,r),cy(o)}):mE.exports=function(){};var xy=mE.exports;xy("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Float64",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int8",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int16",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Int32",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}),!0),xy("Uint16",(function(e){return function(t,i,r){return e(this,t,i,r)}})),xy("Uint32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var Uy=dc,Vy=_v,Fy=co,By=c,Hy=o,Wy=XE.aTypedArray,Gy=XE.exportTypedArrayMethod,jy=T("".slice);Gy("fill",(function(e){var t=arguments.length;Wy(this);var i="Big"===jy(Fy(this),0,3)?Vy(e):+e;return By(Uy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),Hy((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var zy=i,Ky=c,qy=XE,Yy=hr,Jy=uv,Xy=Ve,Qy=o,$y=zy.RangeError,Zy=zy.Int8Array,eT=Zy&&Zy.prototype,tT=eT&&eT.set,iT=qy.aTypedArray,rT=qy.exportTypedArrayMethod,oT=!Qy((function(){var e=new Uint8ClampedArray(2);return Ky(tT,e,{length:1,0:3},1),3!==e[1]})),nT=oT&&qy.NATIVE_ARRAY_BUFFER_VIEWS&&Qy((function(){var e=new Zy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));rT("set",(function(e){iT(this);var t=Jy(arguments.length>1?arguments[1]:void 0,1),i=Xy(e);if(oT)return Ky(tT,this,i,t);var r=this.length,o=Yy(i),n=0;if(o+t>r)throw new $y("Wrong length");for(;n<o;)this[t+n]=i[n++]}),!oT||nT);var aT=Jo,sT=o,lT=ge,cT=dl,dT=hl,uT=pl,hT=te,pT=fl,mT=XE.aTypedArray,fT=XE.exportTypedArrayMethod,_T=i.Uint16Array,gT=_T&&aT(_T.prototype.sort),ET=!(!gT||sT((function(){gT(new _T(2),null)}))&&sT((function(){gT(new _T(2),{})}))),vT=!!gT&&!sT((function(){if(hT)return hT<74;if(dT)return dT<67;if(uT)return!0;if(pT)return pT<602;var e,t,i=new _T(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(gT(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));fT("sort",(function(e){return void 0!==e&&lT(e),vT?gT(this,e):cT(mT(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))}),!vT||ET);var yT=to,TT=c,IT=T,AT=P,ST=F,RT=k,bT=Jm,wT=po,CT=ye,DT=of,NT=vg,kT=tt("replace"),OT=TypeError,MT=IT("".indexOf);IT("".replace);var PT=IT("".slice),LT=Math.max;yT({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,o,n,a,s,l,c,d,u=AT(this),h=0,p="";if(!RT(e)){if(bT(e)&&(i=wT(AT(DT(e))),!~MT(i,"g")))throw new OT("`.replaceAll` does not allow non-global regexes");if(r=CT(e,kT))return TT(r,e,u,t)}for(o=wT(u),n=wT(e),(a=ST(t))||(t=wT(t)),s=n.length,l=LT(1,s),c=MT(o,n);-1!==c;)d=a?wT(t(n,c,o)):NT(n,o,c,[],void 0,t),p+=PT(o,h,c)+d,h=c+s,c=c+l>o.length?-1:MT(o,n,c+l);return h<o.length&&(p+=PT(o,h)),p}});var xT={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},UT=_t("span").classList,VT=UT&&UT.constructor&&UT.constructor.prototype,FT=VT===Object.prototype?void 0:VT,BT=Lv.forEach,HT=zs("forEach")?[].forEach:function(e){return BT(this,e,arguments.length>1?arguments[1]:void 0)},WT=i,GT=xT,jT=FT,zT=HT,KT=qt,qT=function(e){if(e&&e.forEach!==zT)try{KT(e,"forEach",zT)}catch(QK){e.forEach=zT}};for(var YT in GT)GT[YT]&&qT(WT[YT]&&WT[YT].prototype);qT(jT);var JT=i,XT=xT,QT=FT,$T=Ps,ZT=qt,eI=Ua,tI=tt("iterator"),iI=$T.values,rI=function(e,t){if(e){if(e[tI]!==iI)try{ZT(e,tI,iI)}catch(QK){e[tI]=iI}if(eI(e,t,!0),XT[t])for(var i in $T)if(e[i]!==$T[i])try{ZT(e,i,$T[i])}catch(QK){e[i]=$T[i]}}};for(var oI in XT)rI(JT[oI]&&JT[oI].prototype,oI);rI(QT,"DOMTokenList");var nI=Nu.clear;to({global:!0,bind:!0,enumerable:!0,forced:i.clearImmediate!==nI},{clearImmediate:nI});var aI=i,sI=eu,lI=F,cI=Xs,dI=Y,uI=al,hI=iu,pI=aI.Function,mI=/MSIE .\./.test(dI)||"BUN"===cI&&function(){var e=aI.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),fI=to,_I=i,gI=Nu.set,EI=function(e,t){var i=t?2:1;return mI?function(r,o){var n=hI(arguments.length,1)>i,a=lI(r)?r:pI(r),s=n?uI(arguments,i):[],l=n?function(){sI(a,this,s)}:a;return t?e(l,o):e(l)}:e},vI=_I.setImmediate?EI(gI,!1):gI;fI({global:!0,bind:!0,enumerable:!0,forced:_I.setImmediate!==vI},{setImmediate:vI});var yI=cg.charAt,TI=po,II=Ci,AI=Ts,SI=Is,RI="String Iterator",bI=II.set,wI=II.getterFor(RI);AI(String,"String",(function(e){bI(this,{type:RI,string:TI(e),index:0})}),(function(){var e,t=wI(this),i=t.string,r=t.index;return r>=i.length?SI(void 0,!0):(e=yI(i,r),t.index+=e.length,SI(e,!1))}));var CI=o,DI=n,NI=tt("iterator"),kI=!CI((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&&!DI||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[NI]||"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})),OI=n,MI=T,PI=c,LI=o,xI=Ln,UI=wr,VI=d,FI=Ve,BI=N,HI=Object.assign,WI=Object.defineProperty,GI=MI([].concat),jI=!HI||LI((function(){if(OI&&1!==HI({b:1},HI(WI({},"a",{enumerable:!0,get:function(){WI(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!==HI({},e)[i]||xI(HI({},t)).join("")!==r}))?function(e,t){for(var i=FI(e),r=arguments.length,o=1,n=UI.f,a=VI.f;r>o;)for(var s,l=BI(arguments[o++]),c=n?GI(xI(l),n(l)):xI(l),d=c.length,u=0;d>u;)s=c[u++],OI&&!PI(a,l,s)||(i[s]=l[s]);return i}:HI,zI=Mt,KI=Wp,qI=n,YI=Ct,JI=_,XI=Zo,QI=c,$I=Ve,ZI=function(e,t,i,r){try{return r?t(zI(i)[0],i[1]):t(i)}catch(QK){KI(e,"throw",QK)}},eA=Rp,tA=vn,iA=hr,rA=function(e,t,i){qI?YI.f(e,t,JI(0,i)):e[t]=i},oA=Vp,nA=kp,aA=Array,sA=T,lA=2147483647,cA=/[^\0-\u007E]/,dA=/[.\u3002\uFF0E\uFF61]/g,uA="Overflow: input needs wider integers to process",hA=RangeError,pA=sA(dA.exec),mA=Math.floor,fA=String.fromCharCode,_A=sA("".charCodeAt),gA=sA([].join),EA=sA([].push),vA=sA("".replace),yA=sA("".split),TA=sA("".toLowerCase),IA=function(e){return e+22+75*(e<26)},AA=function(e,t,i){var r=0;for(e=i?mA(e/700):e>>1,e+=mA(e/t);e>455;)e=mA(e/35),r+=36;return mA(r+36*e/(e+38))},SA=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var o=_A(e,i++);if(o>=55296&&o<=56319&&i<r){var n=_A(e,i++);56320==(64512&n)?EA(t,((1023&o)<<10)+(1023&n)+65536):(EA(t,o),i--)}else EA(t,o)}return t}(e);var i,r,o=e.length,n=128,a=0,s=72;for(i=0;i<e.length;i++)(r=e[i])<128&&EA(t,fA(r));var l=t.length,c=l;for(l&&EA(t,"-");c<o;){var d=lA;for(i=0;i<e.length;i++)(r=e[i])>=n&&r<d&&(d=r);var u=c+1;if(d-n>mA((lA-a)/u))throw new hA(uA);for(a+=(d-n)*u,n=d,i=0;i<e.length;i++){if((r=e[i])<n&&++a>lA)throw new hA(uA);if(r===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;EA(t,fA(IA(m+f%_))),h=mA(f/_),p+=36}EA(t,fA(IA(h))),s=AA(a,u,c===l),a=0,c++}}a++,n++}return gA(t,"")},RA=to,bA=T,wA=sr,CA=RangeError,DA=String.fromCharCode,NA=String.fromCodePoint,kA=bA([].join);RA({target:"String",stat:!0,arity:1,forced:!!NA&&1!==NA.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,o=0;r>o;){if(t=+arguments[o++],wA(t,1114111)!==t)throw new CA(t+" is not a valid code point");i[o]=t<65536?DA(t):DA(55296+((t-=65536)>>10),t%1024+56320)}return kA(i,"")}});var OA=to,MA=i,PA=Pu,LA=j,xA=c,UA=T,VA=n,FA=kI,BA=Qi,HA=_o,WA=Fl,GA=Ua,jA=ja,zA=Ci,KA=Wl,qA=F,YA=He,JA=Zo,XA=co,QA=Mt,$A=H,ZA=po,eS=ra,tS=_,iS=Vp,rS=kp,oS=Is,nS=iu,aS=dl,sS=tt("iterator"),lS="URLSearchParams",cS=lS+"Iterator",dS=zA.set,uS=zA.getterFor(lS),hS=zA.getterFor(cS),pS=PA("fetch"),mS=PA("Request"),fS=PA("Headers"),_S=mS&&mS.prototype,gS=fS&&fS.prototype,ES=MA.TypeError,vS=MA.encodeURIComponent,yS=String.fromCharCode,TS=LA("String","fromCodePoint"),IS=parseInt,AS=UA("".charAt),SS=UA([].join),RS=UA([].push),bS=UA("".replace),wS=UA([].shift),CS=UA([].splice),DS=UA("".split),NS=UA("".slice),kS=UA(/./.exec),OS=/\+/g,MS=/^[0-9a-f]+$/i,PS=function(e,t){var i=NS(e,t,t+2);return kS(MS,i)?IS(i,16):NaN},LS=function(e){for(var t=0,i=128;i>0&&e&i;i>>=1)t++;return t},xS=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},US=function(e){for(var t=(e=bS(e,OS," ")).length,i="",r=0;r<t;){var o=AS(e,r);if("%"===o){if("%"===AS(e,r+1)||r+3>t){i+="%",r++;continue}var n=PS(e,r+1);if(n!=n){i+=o,r++;continue}r+=2;var a=LS(n);if(0===a)o=yS(n);else{if(1===a||a>4){i+="�",r++;continue}for(var s=[n],l=1;l<a&&!(++r+3>t||"%"!==AS(e,r));){var c=PS(e,r+1);if(c!=c){r+=3;break}if(c>191||c<128)break;RS(s,c),r+=2,l++}if(s.length!==a){i+="�";continue}var d=xS(s);null===d?i+="�":o=TS(d)}}i+=o,r++}return i},VS=/[!'()~]|%20/g,FS={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},BS=function(e){return FS[e]},HS=function(e){return bS(vS(e),VS,BS)},WS=jA((function(e,t){dS(this,{type:cS,target:uS(e).entries,index:0,kind:t})}),lS,(function(){var e=hS(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,oS(void 0,!0);var r=t[i];switch(e.kind){case"keys":return oS(r.key,!1);case"values":return oS(r.value,!1)}return oS([r.key,r.value],!1)}),!0),GS=function(e){this.entries=[],this.url=null,void 0!==e&&($A(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===AS(e,0)?NS(e,1):e:ZA(e)))};GS.prototype={type:lS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,o,n,a,s,l=this.entries,c=rS(e);if(c)for(i=(t=iS(e,c)).next;!(r=xA(i,t)).done;){if(n=(o=iS(QA(r.value))).next,(a=xA(n,o)).done||(s=xA(n,o)).done||!xA(n,o).done)throw new ES("Expected sequence with length 2");RS(l,{key:ZA(a.value),value:ZA(s.value)})}else for(var d in e)YA(e,d)&&RS(l,{key:d,value:ZA(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,o=DS(e,"&"),n=0;n<o.length;)(t=o[n++]).length&&(i=DS(t,"="),RS(r,{key:US(wS(i)),value:US(SS(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],RS(i,HS(e.key)+"="+HS(e.value));return SS(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var jS=function(){KA(this,zS);var e=dS(this,new GS(arguments.length>0?arguments[0]:void 0));VA||(this.size=e.entries.length)},zS=jS.prototype;if(WA(zS,{append:function(e,t){var i=uS(this);nS(arguments.length,2),RS(i.entries,{key:ZA(e),value:ZA(t)}),VA||this.length++,i.updateURL()},delete:function(e){for(var t=uS(this),i=nS(arguments.length,1),r=t.entries,o=ZA(e),n=i<2?void 0:arguments[1],a=void 0===n?n:ZA(n),s=0;s<r.length;){var l=r[s];if(l.key!==o||void 0!==a&&l.value!==a)s++;else if(CS(r,s,1),void 0!==a)break}VA||(this.size=r.length),t.updateURL()},get:function(e){var t=uS(this).entries;nS(arguments.length,1);for(var i=ZA(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=uS(this).entries;nS(arguments.length,1);for(var i=ZA(e),r=[],o=0;o<t.length;o++)t[o].key===i&&RS(r,t[o].value);return r},has:function(e){for(var t=uS(this).entries,i=nS(arguments.length,1),r=ZA(e),o=i<2?void 0:arguments[1],n=void 0===o?o:ZA(o),a=0;a<t.length;){var s=t[a++];if(s.key===r&&(void 0===n||s.value===n))return!0}return!1},set:function(e,t){var i=uS(this);nS(arguments.length,1);for(var r,o=i.entries,n=!1,a=ZA(e),s=ZA(t),l=0;l<o.length;l++)(r=o[l]).key===a&&(n?CS(o,l--,1):(n=!0,r.value=s));n||RS(o,{key:a,value:s}),VA||(this.size=o.length),i.updateURL()},sort:function(){var e=uS(this);aS(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=uS(this).entries,r=JA(e,arguments.length>1?arguments[1]:void 0),o=0;o<i.length;)r((t=i[o++]).value,t.key,this)},keys:function(){return new WS(this,"keys")},values:function(){return new WS(this,"values")},entries:function(){return new WS(this,"entries")}},{enumerable:!0}),BA(zS,sS,zS.entries,{name:"entries"}),BA(zS,"toString",(function(){return uS(this).serialize()}),{enumerable:!0}),VA&&HA(zS,"size",{get:function(){return uS(this).entries.length},configurable:!0,enumerable:!0}),GA(jS,lS),OA({global:!0,constructor:!0,forced:!FA},{URLSearchParams:jS}),!FA&&qA(fS)){var KS=UA(gS.has),qS=UA(gS.set),YS=function(e){if($A(e)){var t,i=e.body;if(XA(i)===lS)return t=e.headers?new fS(e.headers):new fS,KS(t,"content-type")||qS(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),eS(e,{body:tS(0,ZA(i)),headers:tS(0,t)})}return e};if(qA(pS)&&OA({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return pS(e,arguments.length>1?YS(arguments[1]):{})}}),qA(mS)){var JS=function(e){return KA(this,_S),new mS(e,arguments.length>1?YS(arguments[1]):{})};_S.constructor=JS,JS.prototype=_S,OA({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:JS})}}var XS,QS=to,$S=n,ZS=kI,eR=i,tR=Zo,iR=T,rR=Qi,oR=_o,nR=Wl,aR=He,sR=jI,lR=function(e){var t=$I(e),i=tA(this),r=arguments.length,o=r>1?arguments[1]:void 0,n=void 0!==o;n&&(o=XI(o,r>2?arguments[2]:void 0));var a,s,l,c,d,u,h=nA(t),p=0;if(!h||this===aA&&eA(h))for(a=iA(t),s=i?new this(a):aA(a);a>p;p++)u=n?o(t[p],p):t[p],rA(s,p,u);else for(s=i?new this:[],d=(c=oA(t,h)).next;!(l=QI(d,c)).done;p++)u=n?ZI(c,o,[l.value,p],!0):l.value,rA(s,p,u);return s.length=p,s},cR=al,dR=cg.codeAt,uR=function(e){var t,i,r=[],o=yA(vA(TA(e),dA,"."),".");for(t=0;t<o.length;t++)i=o[t],EA(r,pA(cA,i)?"xn--"+SA(i):i);return gA(r,".")},hR=po,pR=Ua,mR=iu,fR={URLSearchParams:jS,getState:uS},_R=Ci,gR=_R.set,ER=_R.getterFor("URL"),vR=fR.URLSearchParams,yR=fR.getState,TR=eR.URL,IR=eR.TypeError,AR=eR.parseInt,SR=Math.floor,RR=Math.pow,bR=iR("".charAt),wR=iR(/./.exec),CR=iR([].join),DR=iR(1..toString),NR=iR([].pop),kR=iR([].push),OR=iR("".replace),MR=iR([].shift),PR=iR("".split),LR=iR("".slice),xR=iR("".toLowerCase),UR=iR([].unshift),VR="Invalid scheme",FR="Invalid host",BR="Invalid port",HR=/[a-z]/i,WR=/[\d+-.a-z]/i,GR=/\d/,jR=/^0x/i,zR=/^[0-7]+$/,KR=/^\d+$/,qR=/^[\da-f]+$/i,YR=/[\0\t\n\r #%/:<>?@[\\\]^|]/,JR=/[\0\t\n\r #/:<>?@[\\\]^|]/,XR=/^[\u0000-\u0020]+/,QR=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,$R=/[\t\n\r]/g,ZR=function(e){var t,i,r,o;if("number"==typeof e){for(t=[],i=0;i<4;i++)UR(t,e%256),e=SR(e/256);return CR(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,o=0,n=0;n<8;n++)0!==e[n]?(o>i&&(t=r,i=o),r=null,o=0):(null===r&&(r=n),++o);return o>i?r:t}(e),i=0;i<8;i++)o&&0===e[i]||(o&&(o=!1),r===i?(t+=i?":":"::",o=!0):(t+=DR(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},eb={},tb=sR({},eb,{" ":1,'"':1,"<":1,">":1,"`":1}),ib=sR({},tb,{"#":1,"?":1,"{":1,"}":1}),rb=sR({},ib,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ob=function(e,t){var i=dR(e,0);return i>32&&i<127&&!aR(t,e)?e:encodeURIComponent(e)},nb={ftp:21,file:null,http:80,https:443,ws:80,wss:443},ab=function(e,t){var i;return 2===e.length&&wR(HR,bR(e,0))&&(":"===(i=bR(e,1))||!t&&"|"===i)},sb=function(e){var t;return e.length>1&&ab(LR(e,0,2))&&(2===e.length||"/"===(t=bR(e,2))||"\\"===t||"?"===t||"#"===t)},lb=function(e){return"."===e||"%2e"===xR(e)},cb={},db={},ub={},hb={},pb={},mb={},fb={},_b={},gb={},Eb={},vb={},yb={},Tb={},Ib={},Ab={},Sb={},Rb={},bb={},wb={},Cb={},Db={},Nb=function(e,t,i){var r,o,n,a=hR(e);if(t){if(o=this.parse(a))throw new IR(o);this.searchParams=null}else{if(void 0!==i&&(r=new Nb(i,!0)),o=this.parse(a,null,r))throw new IR(o);(n=yR(new vR)).bindURL(this),this.searchParams=n}};Nb.prototype={type:"URL",parse:function(e,t,i){var r,o,n,a,s,l=this,c=t||cb,d=0,u="",h=!1,p=!1,m=!1;for(e=hR(e),t||(l.scheme="",l.username="",l.password="",l.host=null,l.port=null,l.path=[],l.query=null,l.fragment=null,l.cannotBeABaseURL=!1,e=OR(e,XR,""),e=OR(e,QR,"$1")),e=OR(e,$R,""),r=lR(e);d<=r.length;){switch(o=r[d],c){case cb:if(!o||!wR(HR,o)){if(t)return VR;c=ub;continue}u+=xR(o),c=db;break;case db:if(o&&(wR(WR,o)||"+"===o||"-"===o||"."===o))u+=xR(o);else{if(":"!==o){if(t)return VR;u="",c=ub,d=0;continue}if(t&&(l.isSpecial()!==aR(nb,u)||"file"===u&&(l.includesCredentials()||null!==l.port)||"file"===l.scheme&&!l.host))return;if(l.scheme=u,t)return void(l.isSpecial()&&nb[l.scheme]===l.port&&(l.port=null));u="","file"===l.scheme?c=Ib:l.isSpecial()&&i&&i.scheme===l.scheme?c=hb:l.isSpecial()?c=_b:"/"===r[d+1]?(c=pb,d++):(l.cannotBeABaseURL=!0,kR(l.path,""),c=wb)}break;case ub:if(!i||i.cannotBeABaseURL&&"#"!==o)return VR;if(i.cannotBeABaseURL&&"#"===o){l.scheme=i.scheme,l.path=cR(i.path),l.query=i.query,l.fragment="",l.cannotBeABaseURL=!0,c=Db;break}c="file"===i.scheme?Ib:mb;continue;case hb:if("/"!==o||"/"!==r[d+1]){c=mb;continue}c=gb,d++;break;case pb:if("/"===o){c=Eb;break}c=bb;continue;case mb:if(l.scheme=i.scheme,o===XS)l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query=i.query;else if("/"===o||"\\"===o&&l.isSpecial())c=fb;else if("?"===o)l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query="",c=Cb;else{if("#"!==o){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.path.length--,c=bb;continue}l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=cR(i.path),l.query=i.query,l.fragment="",c=Db}break;case fb:if(!l.isSpecial()||"/"!==o&&"\\"!==o){if("/"!==o){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,c=bb;continue}c=Eb}else c=gb;break;case _b:if(c=gb,"/"!==o||"/"!==bR(u,d+1))continue;d++;break;case gb:if("/"!==o&&"\\"!==o){c=Eb;continue}break;case Eb:if("@"===o){h&&(u="%40"+u),h=!0,n=lR(u);for(var f=0;f<n.length;f++){var _=n[f];if(":"!==_||m){var g=ob(_,rb);m?l.password+=g:l.username+=g}else m=!0}u=""}else if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()){if(h&&""===u)return"Invalid authority";d-=lR(u).length+1,u="",c=vb}else u+=o;break;case vb:case yb:if(t&&"file"===l.scheme){c=Sb;continue}if(":"!==o||p){if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()){if(l.isSpecial()&&""===u)return FR;if(t&&""===u&&(l.includesCredentials()||null!==l.port))return;if(a=l.parseHost(u))return a;if(u="",c=Rb,t)return;continue}"["===o?p=!0:"]"===o&&(p=!1),u+=o}else{if(""===u)return FR;if(a=l.parseHost(u))return a;if(u="",c=Tb,t===yb)return}break;case Tb:if(!wR(GR,o)){if(o===XS||"/"===o||"?"===o||"#"===o||"\\"===o&&l.isSpecial()||t){if(""!==u){var E=AR(u,10);if(E>65535)return BR;l.port=l.isSpecial()&&E===nb[l.scheme]?null:E,u=""}if(t)return;c=Rb;continue}return BR}u+=o;break;case Ib:if(l.scheme="file","/"===o||"\\"===o)c=Ab;else{if(!i||"file"!==i.scheme){c=bb;continue}switch(o){case XS:l.host=i.host,l.path=cR(i.path),l.query=i.query;break;case"?":l.host=i.host,l.path=cR(i.path),l.query="",c=Cb;break;case"#":l.host=i.host,l.path=cR(i.path),l.query=i.query,l.fragment="",c=Db;break;default:sb(CR(cR(r,d),""))||(l.host=i.host,l.path=cR(i.path),l.shortenPath()),c=bb;continue}}break;case Ab:if("/"===o||"\\"===o){c=Sb;break}i&&"file"===i.scheme&&!sb(CR(cR(r,d),""))&&(ab(i.path[0],!0)?kR(l.path,i.path[0]):l.host=i.host),c=bb;continue;case Sb:if(o===XS||"/"===o||"\\"===o||"?"===o||"#"===o){if(!t&&ab(u))c=bb;else if(""===u){if(l.host="",t)return;c=Rb}else{if(a=l.parseHost(u))return a;if("localhost"===l.host&&(l.host=""),t)return;u="",c=Rb}continue}u+=o;break;case Rb:if(l.isSpecial()){if(c=bb,"/"!==o&&"\\"!==o)continue}else if(t||"?"!==o)if(t||"#"!==o){if(o!==XS&&(c=bb,"/"!==o))continue}else l.fragment="",c=Db;else l.query="",c=Cb;break;case bb:if(o===XS||"/"===o||"\\"===o&&l.isSpecial()||!t&&("?"===o||"#"===o)){if(".."===(s=xR(s=u))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(l.shortenPath(),"/"===o||"\\"===o&&l.isSpecial()||kR(l.path,"")):lb(u)?"/"===o||"\\"===o&&l.isSpecial()||kR(l.path,""):("file"===l.scheme&&!l.path.length&&ab(u)&&(l.host&&(l.host=""),u=bR(u,0)+":"),kR(l.path,u)),u="","file"===l.scheme&&(o===XS||"?"===o||"#"===o))for(;l.path.length>1&&""===l.path[0];)MR(l.path);"?"===o?(l.query="",c=Cb):"#"===o&&(l.fragment="",c=Db)}else u+=ob(o,ib);break;case wb:"?"===o?(l.query="",c=Cb):"#"===o?(l.fragment="",c=Db):o!==XS&&(l.path[0]+=ob(o,eb));break;case Cb:t||"#"!==o?o!==XS&&("'"===o&&l.isSpecial()?l.query+="%27":l.query+="#"===o?"%23":ob(o,eb)):(l.fragment="",c=Db);break;case Db:o!==XS&&(l.fragment+=ob(o,tb))}d++}},parseHost:function(e){var t,i,r;if("["===bR(e,0)){if("]"!==bR(e,e.length-1))return FR;if(t=function(e){var t,i,r,o,n,a,s,l=[0,0,0,0,0,0,0,0],c=0,d=null,u=0,h=function(){return bR(e,u)};if(":"===h()){if(":"!==bR(e,1))return;u+=2,d=++c}for(;h();){if(8===c)return;if(":"!==h()){for(t=i=0;i<4&&wR(qR,h());)t=16*t+AR(h(),16),u++,i++;if("."===h()){if(0===i)return;if(u-=i,c>6)return;for(r=0;h();){if(o=null,r>0){if(!("."===h()&&r<4))return;u++}if(!wR(GR,h()))return;for(;wR(GR,h());){if(n=AR(h(),10),null===o)o=n;else{if(0===o)return;o=10*o+n}if(o>255)return;u++}l[c]=256*l[c]+o,2!=++r&&4!==r||c++}if(4!==r)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;l[c++]=t}else{if(null!==d)return;u++,d=++c}}if(null!==d)for(a=c-d,c=7;0!==c&&a>0;)s=l[c],l[c--]=l[d+a-1],l[d+--a]=s;else if(8!==c)return;return l}(LR(e,1,-1)),!t)return FR;this.host=t}else if(this.isSpecial()){if(e=uR(e),wR(YR,e))return FR;if(t=function(e){var t,i,r,o,n,a,s,l=PR(e,".");if(l.length&&""===l[l.length-1]&&l.length--,(t=l.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(o=l[r]))return e;if(n=10,o.length>1&&"0"===bR(o,0)&&(n=wR(jR,o)?16:8,o=LR(o,8===n?1:2)),""===o)a=0;else{if(!wR(10===n?KR:8===n?zR:qR,o))return e;a=AR(o,n)}kR(i,a)}for(r=0;r<t;r++)if(a=i[r],r===t-1){if(a>=RR(256,5-t))return null}else if(a>255)return null;for(s=NR(i),r=0;r<i.length;r++)s+=i[r]*RR(256,3-r);return s}(e),null===t)return FR;this.host=t}else{if(wR(JR,e))return FR;for(t="",i=lR(e),r=0;r<i.length;r++)t+=ob(i[r],eb);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return aR(nb,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&ab(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,o=e.host,n=e.port,a=e.path,s=e.query,l=e.fragment,c=t+":";return null!==o?(c+="//",e.includesCredentials()&&(c+=i+(r?":"+r:"")+"@"),c+=ZR(o),null!==n&&(c+=":"+n)):"file"===t&&(c+="//"),c+=e.cannotBeABaseURL?a[0]:a.length?"/"+CR(a,"/"):"",null!==s&&(c+="?"+s),null!==l&&(c+="#"+l),c},setHref:function(e){var t=this.parse(e);if(t)throw new IR(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new kb(e.path[0]).origin}catch(QK){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+ZR(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(hR(e)+":",cb)},getUsername:function(){return this.username},setUsername:function(e){var t=lR(hR(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ob(t[i],rb)}},getPassword:function(){return this.password},setPassword:function(e){var t=lR(hR(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ob(t[i],rb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?ZR(e):ZR(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,vb)},getHostname:function(){var e=this.host;return null===e?"":ZR(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,yb)},getPort:function(){var e=this.port;return null===e?"":hR(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=hR(e))?this.port=null:this.parse(e,Tb))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+CR(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Rb))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=hR(e))?this.query=null:("?"===bR(e,0)&&(e=LR(e,1)),this.query="",this.parse(e,Cb)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=hR(e))?("#"===bR(e,0)&&(e=LR(e,1)),this.fragment="",this.parse(e,Db)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var kb=function(e){var t=nR(this,Ob),i=mR(arguments.length,1)>1?arguments[1]:void 0,r=gR(t,new Nb(e,!1,i));$S||(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())},Ob=kb.prototype,Mb=function(e,t){return{get:function(){return ER(this)[e]()},set:t&&function(e){return ER(this)[t](e)},configurable:!0,enumerable:!0}};if($S&&(oR(Ob,"href",Mb("serialize","setHref")),oR(Ob,"origin",Mb("getOrigin")),oR(Ob,"protocol",Mb("getProtocol","setProtocol")),oR(Ob,"username",Mb("getUsername","setUsername")),oR(Ob,"password",Mb("getPassword","setPassword")),oR(Ob,"host",Mb("getHost","setHost")),oR(Ob,"hostname",Mb("getHostname","setHostname")),oR(Ob,"port",Mb("getPort","setPort")),oR(Ob,"pathname",Mb("getPathname","setPathname")),oR(Ob,"search",Mb("getSearch","setSearch")),oR(Ob,"searchParams",Mb("getSearchParams")),oR(Ob,"hash",Mb("getHash","setHash"))),rR(Ob,"toJSON",(function(){return ER(this).serialize()}),{enumerable:!0}),rR(Ob,"toString",(function(){return ER(this).serialize()}),{enumerable:!0}),TR){var Pb=TR.createObjectURL,Lb=TR.revokeObjectURL;Pb&&rR(kb,"createObjectURL",tR(Pb,TR)),Lb&&rR(kb,"revokeObjectURL",tR(Lb,TR))}pR(kb,"URL"),QS({global:!0,constructor:!0,forced:!ZS,sham:!$S},{URL:kb});var xb=c;to({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return xb(URL.prototype.toString,this)}});var Ub,Vb=Object.create,Fb=Object.defineProperty,Bb=Object.defineProperties,Hb=Object.getOwnPropertyDescriptor,Wb=Object.getOwnPropertyDescriptors,Gb=Object.getOwnPropertyNames,jb=Object.getOwnPropertySymbols,zb=Object.getPrototypeOf,Kb=Object.prototype.hasOwnProperty,qb=Object.prototype.propertyIsEnumerable,Yb=Reflect.get,Jb=Math.pow,Xb=(e,t,i)=>t in e?Fb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Qb=(e,t)=>{for(var i in t||(t={}))Kb.call(t,i)&&Xb(e,i,t[i]);if(jb)for(var i of jb(t))qb.call(t,i)&&Xb(e,i,t[i]);return e},$b=(e,t)=>Bb(e,Wb(t)),Zb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ew=(e,t)=>{for(var i in t)Fb(e,i,{get:t[i],enumerable:!0})},tw=(e,t,i)=>(i=null!=e?Vb(zb(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of Gb(t))!Kb.call(e,o)&&o!==i&&Fb(e,o,{get:()=>t[o],enumerable:!(r=Hb(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:Fb(i,"default",{value:e,enumerable:!0}),e)),iw=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?Hb(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&Fb(t,i,n),n},rw=(e,t,i)=>Xb(e,"symbol"!=typeof t?t+"":t,i),ow=(e,t,i)=>Yb(zb(e),i,t),nw=(e,t,i)=>new Promise(((r,o)=>{var n=e=>{try{s(i.next(e))}catch(aM){o(aM)}},a=e=>{try{s(i.throw(e))}catch(aM){o(aM)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(n,a);s((i=i.apply(e,t)).next())})),aw=Zb(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,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,i),!0;case 4:return d.fn.call(d.context,t,i,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+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)&&(!i||a.context===i)&&s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)})),sw=Zb(((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")}))}))})),lw=Zb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var o=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:o&&!i[e.name]&&(i[e.name]={});var n=e.push?{}:o?i[e.name]:i;(function(e,i,r,o){if(o&&!r)i[o]=t(e[1]);else for(var n=0;n<r.length;n+=1)null!=e[n+1]&&(i[r[n]]=t(e[n+1]))})(r.match(e.reg),n,e.names,e.name),e.push&&i[e.push].push(n)},r=sw(),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<(r[t]||[]).length;s+=1){var l=r[t][s];if(l.reg.test(o))return i(l,a,o)}})),t.media=n,t};var n=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(n,{})},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),o=0;o<r.length;o+=3)i.push({component:r[o],ip:r[o+1],port:r[o+2]});return i},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 i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),cw=Zb(((e,t)=>{var i=sw(),r=/%[sdv%]/g,o=function(e){var t=1,i=arguments,o=i.length;return e.replace(r,(function(e){if(t>=o)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""}}))},n=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 n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?r.push(i[t.name][a]):r.push(i[t.names[n]])}else r.push(i[t.name]);return o.apply(null,r)},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 r=t.outerOrder||a,o=t.innerOrder||s,l=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(n(t,i,e))}))}))})),e.media.forEach((function(e){l.push(n("m",i.m[0],e)),o.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(n(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}})),dw=Zb((e=>{var t=lw(),i=cw(),r=sw();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})),uw=((Ub=uw||{})[Ub.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ub[Ub.INVALID_OPERATION=4097]="INVALID_OPERATION",Ub[Ub.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ub[Ub.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ub[Ub.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ub[Ub.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ub[Ub.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ub[Ub.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ub[Ub.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ub[Ub.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ub[Ub.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ub[Ub.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ub[Ub.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ub[Ub.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ub[Ub.CLIENT_BANNED=16448]="CLIENT_BANNED",Ub[Ub.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ub[Ub.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ub[Ub.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ub[Ub.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ub[Ub.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ub[Ub.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ub[Ub.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ub[Ub.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ub[Ub.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ub[Ub.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ub[Ub.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ub[Ub.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ub[Ub.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ub[Ub.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ub[Ub.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ub[Ub.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Ub[Ub.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Ub[Ub.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Ub[Ub.UNKNOWN=65535]="UNKNOWN",Ub),hw=uw,pw=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=hw.UNKNOWN,extraCode:o=0,constraint:n}=e,a="<".concat(function(e){for(let t in hw)if(hw[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),s="".concat(i).concat(n?" constraint: ".concat(n):"").concat(null!=i&&i.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=r,this.extraCode=o,this.name=t,this.message=s,this.constraint=n,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},mw=pw,fw=function(){return 0},_w=function(){return Date.now()+0},gw=function(){let e=new Date;return e.setTime(_w()),e.toLocaleString()},Ew=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)},vw={};ew(vw,{REPORT_TYPE:()=>ON,buildSSOPackage:()=>MN,bytes2ms:()=>MD,calculateScaleResolutionDownNumber:()=>CN,concatArrayBuffers:()=>PN,convertObjectNumberToInt:()=>AN,copyProperties:()=>OD,deepClone:()=>pN,deepCloneBasic:()=>kN,deepMerge:()=>hN,delay:()=>SN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>fN,getEnv:()=>ID,getFirst16Bits:()=>xN,getInternalVersion:()=>aN,getLast16Bits:()=>LN,getLoggerUrl:()=>SD,getMediaStreamTrackInfo:()=>wN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>bD,getNumNetworkType:()=>kD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>vN,getTurnServer:()=>dN,getUint32Version:()=>IN,getValueType:()=>WD,getViewListFromView:()=>mN,glog:()=>UD,ipv4ToUint32:()=>uN,isArray:()=>JD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>ZD,isEmpty:()=>lN,isFunction:()=>GD,isLangChinese:()=>VD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>yN,isPromise:()=>$D,isRemoteTrack:()=>QD,isRotate90Or270:()=>DN,isSetSinkIdSupported:()=>iN,isString:()=>zD,isUndefined:()=>jD,loadImage:()=>TN,loadVideo:()=>NN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>bN,performanceNow:()=>oN,promiseAny:()=>rN,samples2ms:()=>PD,setNetworkTypeFromWebRTC:()=>ND,stringify:()=>gN,stringifyIncludeValue:()=>EN,throttlePromise:()=>RN});var yw={};ew(yw,{AUDIO_MUTE_BIT:()=>lC,AUDIO_STAT_BIT:()=>sC,AUX_STAT_BIT:()=>aC,AUX_STREAM_MSID:()=>pC,BACKEND_ENV:()=>iC,BASE_DOC_URL:()=>Lw,BASE_HOST:()=>kw,CAPABILITIES_KEYS:()=>eD,CLASS_NAME:()=>zC,CLOUD_CONSOLE_URL:()=>Pw,CROSS_ROOM_BIT:()=>uC,DATA_FREEZE_TIMING:()=>VC,DOC_BILLING_CN:()=>Uw,DOC_BILLING_OVERSEA:()=>Vw,DOC_URL:()=>xw,DTLS_STATE_UNKNOWN:()=>AC,ENV_NAME:()=>Gw,EXCHANGE_SDP_TIMEOUT:()=>MC,IS_WORKER:()=>bw,IS_WORKLET:()=>ww,KIBANA_EVENT:()=>NC,LOCAL_STREAM_PUBLISH_STATE:()=>UC,LOGGER_CMD_TYPE:()=>Ww,LOGGER_DOMAIN:()=>Fw,LOGGER_DOMAIN_OVERSEA:()=>Bw,LOG_LEVEL:()=>jw,LOG_LEVEL_NAME:()=>XC,MAIN_STREAM_MSID:()=>hC,MAX_RTT:()=>tD,MICROPHONE_COMMUNICATIONS:()=>JC,MICROPHONE_DEFAULT:()=>qC,MUTE_ALL_BIT:()=>dC,NAME:()=>eC,NETWORK_TYPE:()=>qw,NOT_SUPPORTED_H264:()=>xC,PAUSED_RETRY_COUNT:()=>KC,PEERCONNECTION_CONNECTING_TIMEOUT:()=>WC,PEER_CONNECTION_STATE:()=>SC,PEER_LEAVE_REASON:()=>QC,RECOVER_CAPTURE_INTERVAL:()=>ZC,REMOTE_STREAM_TYPE_AUX:()=>fC,REMOTE_STREAM_TYPE_MAIN:()=>mC,RENDER_FREEZE_TIMING:()=>FC,SCHEDULE_DOMAIN:()=>GC,SCHEDULE_TIMEOUT:()=>jC,SDP_SEMANTICS_PLAN_B:()=>LC,SDP_SEMANTICS_UNIFIED_PLAN:()=>PC,SECOND_HOST:()=>Ow,SIGNAL_PING_PONG_INTERVAL:()=>Kw,SIGNAL_PING_TIMEOUT:()=>zw,SIGNAL_RECONNECTION_COUNT:()=>DC,SMALL_STAT_BIT:()=>nC,SPEAKER_DEFAULT:()=>YC,STORAGE_EXPIRES_TIME:()=>Yw,STREAM_TYPE_BIG:()=>BC,STREAM_TYPE_SMALL:()=>HC,SUBSCRIBE_SMALL_RETRY_COUNT:()=>$C,SYNC_USER_LIST_INTERVAL:()=>kC,Scene:()=>rC,THIRD_HOST:()=>Mw,TRANSPORT_DIRECTION:()=>tC,TRTC_ERROR_ASSISTANCE:()=>Hw,TRTC_QUALITY_BAD:()=>yC,TRTC_QUALITY_DISCONNECTED:()=>IC,TRTC_QUALITY_EXCELLENT:()=>gC,TRTC_QUALITY_GOOD:()=>EC,TRTC_QUALITY_POOR:()=>vC,TRTC_QUALITY_UNKNOWN:()=>_C,TRTC_QUALITY_VERY_BAD:()=>TC,UPDATE_OFFER_TIMEOUT:()=>OC,VIDEO_MUTE_BIT:()=>cC,VIDEO_STAT_BIT:()=>oC,audioProfileMap:()=>Jw,defaultBigVideoProfile:()=>Qw,defaultSmallVideoProfile:()=>$w,getRetryCount:()=>wC,getScriptDir:()=>Cw,innerVersion:()=>Tw,loggerProxy:()=>Dw,screenProfileMap:()=>Zw,setLoggerProxy:()=>Nw,setRetryCount:()=>bC,setVersion:()=>Aw,version:()=>Iw,videoProfileMap:()=>Xw});var Tw="4.15.00.1600",Iw="5.0.0";function Aw(e){Iw=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Tw="".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 Sw,Rw,bw="undefined"!=typeof importScripts,ww="undefined"!=typeof registerProcessor,Cw=()=>{let e=bw?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Dw="",Nw=e=>Dw=e,kw="web.sdk.qcloud.com",Ow="web.sdk.tencent.cn",Mw="web.sdk.cloud.tencent.cn",Pw="https://console.cloud.tencent.com/trtc",Lw="https://".concat(kw,"/trtc/webrtc/doc"),xw="".concat(Lw,"/zh-cn/"),Uw="https://cloud.tencent.com/document/product/647/85386",Vw="https://trtc.io/document/56025",Fw="https://yun.tim.qq.com",Bw="https://apisgp.my-imcloud.com",Hw="trtc_error_assistance",Ww={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Gw={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},jw=((Rw=jw||{})[Rw.TRACE=0]="TRACE",Rw[Rw.DEBUG=1]="DEBUG",Rw[Rw.INFO=2]="INFO",Rw[Rw.WARN=3]="WARN",Rw[Rw.ERROR=4]="ERROR",Rw[Rw.NONE=5]="NONE",Rw),zw=18e3,Kw=2e3,qw={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},Yw=6048e5,Jw={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}},Xw={"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}},Qw=Xw["480p_2"],$w=Xw["120p_2"],Zw={"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}},eC={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",LOADSTART:"loadstart",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"},tC={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},iC={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},rC=((Sw=rC||{}).LIVE="live",Sw.RTC="rtc",Sw),oC=1,nC=2,aC=4,sC=8,lC=64,cC=16,dC=112,uC=128,hC="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",pC="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",mC=eC.MAIN,fC=eC.AUXILIARY,_C=0,gC=1,EC=2,vC=3,yC=4,TC=5,IC=6,AC="unknown",SC={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},RC=1/0;function bC(e){RC=e}function wC(){return RC}var CC,DC=30,NC={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",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},kC=1e4,OC=1e4,MC=1e4,PC="unified-plan",LC="plan-b",xC=1028,UC=((CC=UC||{})[CC.UNPUBLISH=-1]="UNPUBLISH",CC[CC.PUBLISHING=0]="PUBLISHING",CC[CC.PUBLISHED=1]="PUBLISHED",CC),VC=500,FC=1e3,BC=eC.BIG,HC=eC.SMALL,WC=1e4,GC={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"},jC=2e3,zC={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},KC=5,qC="default",YC=qC,JC="communications",XC=Object.keys(jw),QC=["normal leave","timeout leave","kick","role change"],$C=10,ZC=2e3,eD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],tD=1e4,iD=function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())}))},rD=Symbol(32),oD=Symbol(16),nD=Symbol(8),aD=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 iD(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(rD)}readU16(){return this.read(oD)}readU8(){return this.read(nD)}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===rD){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===oD){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===nD){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}};aD.U32=rD,aD.U16=oD,aD.U8=nD;var sD=128;function lD(e){let t=new aD;for(;e>=128;)t.malloc(1)[0]=255&e|sD,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function cD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new aD,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(lD(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(lD(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new aD;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=cD(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=cD(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(lD(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var dD=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 uD(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 hD(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function pD(e,t){return e[t]}function mD(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var fD=0,_D=2654435769,gD=16,ED=2,vD=7;function yD(e,t){let i=new dD,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,fD);fD=fD+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new dD;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.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,zD(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===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+ED+vD)%8;r&&(r=8-r);let o=i+1+ED+vD+r,n=new Uint8Array(o),a=0,s=new Uint8Array(8),l=new Uint8Array(8),c=new Uint8Array(8),d=0;s[0]=248&Math.floor(256*Math.random())|r,d=1;for(let h=0;h<r;h++)s[d]=255&Math.floor(256*Math.random()),d+=1;for(let h=0;h<ED;)if(d<8&&(s[d]=255&Math.floor(256*Math.random()),d+=1,h+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}let u=0;for(;u<i;)if(d<8&&(s[d]=e[u],d+=1,u+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}for(let h=0;h<vD;)if(d<8&&(s[d]=0,d+=1,h+=1),8===d){TD(s,t,l,c,n,a),a+=8,d=0;for(let e=0;e<8;e++)c[e]=n[a-8+e]}return n}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function TD(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=hD(e,0),n=hD(e,4),a=[];for(let l=0;l<4;l++)a[l]=hD(t,4*l);let s=0;for(let l=0;l<gD;l++)s+=_D,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;uD(i,o,r),uD(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var ID=function(){return new URLSearchParams(location.search).get("trtc_env")||""},AD=e=>Number(e)<14e8,SD=function(e,t){let i;i=Dw||(AD(e)?Bw:Fw);let r=Math.floor(Math.random()*Jb(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},RD="unknown";function bD(){!function(){var e;CD||(CD=!0,null==(e=navigator.connection)||e.addEventListener("typechange",wD))}();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(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===o&&(o="2g"),r?DD(r,o):RD}function wD(){eM.warn("netType changed",bD())}var CD=!1;function DD(e,t){if(qw[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ND(e){RD=DD(e)}function kD(){return qw[bD()]}function OD(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 MD(e){return PD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function PD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function LD(e){return 4*xD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function xD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var UD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},VD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},FD=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 BD(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:BD(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function HD(e){return e>8?3e4:1e3*BD(e)}function WD(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var GD=e=>"function"==typeof e,jD=e=>void 0===e,zD=e=>"string"==typeof e,KD=e=>"number"==typeof e,qD=e=>"boolean"==typeof e,YD=e=>"object"===WD(e),JD=e=>"array"===WD(e),XD=e=>WD(e)==="MediaStreamTrack".toLowerCase(),QD=e=>e.isRemote,$D=e=>"promise"===WD(e),ZD=e=>GD(e)&&e.prototype.constructor===e,eN=e=>ZD(e)?e.prototype.constructor.name:"",tN="undefined"!=typeof AudioWorkletNode,iN="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype;function rN(e){return new Promise(((t,i)=>{let r=[];e.forEach((o=>{o.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function oN(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var nN=e=>+e<10?"0".concat(e):e,aN=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=nN(i[1])+nN(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},sN=Object.prototype.hasOwnProperty;function lN(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(FD(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(sN.call(e,t))return!1;return!0}return!1}function cN(e,t){return{userId:t,hasAudio:!!(e&sC),hasVideo:!!(e&oC),hasAuxiliary:!!(e&aC),hasSmall:!!(e&nC),audioMuted:!!(e&lC),videoMuted:!!(e&cC),audioAvailable:!(!(e&sC)||e&lC),videoAvailable:!(!(e&oC)||e&cC)}}function dN(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!jD(e.username)&&!jD(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",jD(e.credentialType)||(t.credentialType=e.credentialType)),t}function uN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!zD(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 hN=function(e,t,i,r){if(!YD(e)||!YD(t))return 0;let o,n=0,a=Object.keys(t);for(let s=0,l=a.length;s<l;s++)if(o=a[s],!(jD(t[o])||i&&i.includes(o)))if(YD(e[o])&&YD(t[o]))n+=hN(e[o],t[o],i,r);else{if(r&&r.includes(t[o]))continue;e[o]!==t[o]&&(e[o]=pN(t[o]),n+=1)}return n};function pN(e){if(JD(e)){let t=[];return e.forEach(((e,i)=>{t[i]=pN(e)})),t}if(YD(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=pN(e[i])})),t}return e}var mN=e=>{let t=[];if(JD(e))t=[...e];else if(zD(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},fN=e=>zD(e)?document.getElementById(e):e,_N=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,o=e.getDate(),n=t(e.getHours()),a=t(e.getMinutes()),s=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(o," ").concat(n,":").concat(a,":").concat(s)})(new Date);function gN(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(JD(e))return"[".concat(e.map((e=>gN(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!FD(e)||!JD(i)&&!JD(r))return JSON.stringify(e);let t={},o=new Set(i),n=new Set(r);return Object.keys(e).forEach((a=>{(0===n.size&&o.has(a)||0===o.size&&!n.has(a))&&(t[a]=FD(e[a])||JD(e[a])?JSON.parse(gN(e[a],{keysToExclude:r,keysToInclude:i})):e[a])})),JSON.stringify(t)}catch(CC){return"{}"}}function EN(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)})),gN(e,{keysToInclude:i})}function vN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var yN=()=>{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},TN=e=>nw(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(zD(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 mw({code:hw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),IN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},AN=e=>(Object.keys(e).forEach((t=>{KD(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(FD(e[t])||JD(e[t]))&&AN(e[t])})),e);function SN(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}function RN(e,t){let i=null;return function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return i||(i=e.apply(t||this,o),i.finally((()=>i=null)),i)}}function bN(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function wN(e){var t;try{let{width:i,height:r,frameRate:o,sampleRate:n,sampleSize:a,channelCount:s}=null==(t=e.getSettings)?void 0:t.call(e),l=e.kind===eC.AUDIO?"".concat(n,"x").concat(a,"@").concat(s):"".concat(i,"x").concat(r,"@").concat(o),c=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(l).concat(c)}catch(Sw){return""}}function CN(e,t){return e.width*e.height==t.width*t.height?1:yN()&&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 DN(e){return 90===e||270===e}function NN(e){return nw(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 kN(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]=kN(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]=kN(e[r],t)})),i}return e}var ON=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(ON||{});function MN(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return jD(r)||(o=$b(Qb({},o),{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(o)}}}(e,t,i,r);return yD(cD(o),i)}catch(cM){return JSON.stringify(e)}}function PN(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 LN(e){return(65535&e)>>>0}function xN(e){return(4294901760&e)>>>0}function UN(e){let t=function(e){try{let t={},i=0;t.totalLength=hD(e,i),i+=4,t.version=hD(e,i),i+=4,t.encryption=pD(e,i),i+=1,t.uinType=pD(e,i),i+=1,t.uinLength=hD(e,i),i+=4,t.uin=t.uinLength>4?mD(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),o=new Uint8Array(e.slice(0,8)),n=VN(o,t),a=7&n[0],s=e.length-1-a-ED-vD,l=new Uint8Array(s),c=0,d=r,u=e.slice(0,8);i=8;let h=1;h+=a;for(let m=1;m<=ED;)if(h<8)h++,m++;else if(8===h){let r=FN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}let p=s;for(;p>0;)if(h<8)l[c++]=n[h]^d[h],h++,p--;else if(8===h){let r=FN(e,i,d,u,n,t);d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}for(let m=1;m<=vD;)if(h<8)n[h],d[h],h++,m++;else if(8===h){if(i>=e.length)break;let r=FN(e,i,d,u,n,t);if(!r.success)break;d=r.ivPreCrypt,u=r.ivCurCrypt,n=r.debiBuf,i=r.bufPos,h=0}return l}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=hD(e,i),i+=4,t.seqNo=hD(e,i),i+=4,t.retCode=hD(e,i),i+=4,t.retStrLength=hD(e,i),i+=4,t.retStr=t.retStrLength?mD(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=hD(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?mD(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=hD(e,i),i+=4,t.cookie=t.cookieLength?mD(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=hD(e,i),i+=4,t.busiBuffLength=hD(e,i),i+=4,t.busiBuff=t.busiBuffLength?mD(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function VN(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 o=_D*gD>>>0;for(let n=0;n<gD;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=_D,o>>>=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 FN(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:VN(l,n),bufPos:t+8}}var BN="undefined"!=typeof TextDecoder?new TextDecoder:void 0;function HN(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise(((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:UN(new Uint8Array(e))||(BN?BN.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(hM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)}))}function WN(e){return nw(this,null,(function*(){let t=oN(),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 eM.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(oN()-t,"ms")),r}catch(CC){return i}}))}var GN=Object.prototype.hasOwnProperty,jN=e=>"function"==typeof e,zN=e=>void 0===e,KN=e=>e.isRemote,qN=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 YN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>nw(this,null,(function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(jN(d)?d():d)?(h++,m=1,jN(o)&&o.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,i)}),jN(u)?u(h):u)):(t(),jN(n)&&n.call(this,_))};jN(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}}));return new Promise(f)}},JN=class e{constructor(e){rw(this,"_parentPath"),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=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:zN(t.userId)?this.userId:t.userId,sdkAppId:zN(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:zN(t.type)?this.type:t.type,isLocal:zN(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:zN(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),eM.log(e,t,zN(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(qN(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(GN.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={};ew(XN,{ANDROID_VERSION:()=>dk,CHROME_MAJOR_VERSION:()=>fO,CHROME_VERSION:()=>_O,EDGE_VERSION:()=>gk,EDG_MAJOR_VERSION:()=>yk,EDG_VERSION:()=>vk,ELECTRON_MAJOR_VERSION:()=>gO,FIREFOX_MAJOR_VERSION:()=>fk,FIREFOX_VERSION:()=>mk,HUAWEI_VERSION:()=>tO,IE_VERSION:()=>kk,IOS_MAIN_VERSION:()=>RO,IOS_VERSION:()=>IO,IPADQQB_VERSION:()=>Wk,IS_ANDROID:()=>ck,IS_ANDROID_WEBVIEW:()=>TO,IS_ANY_SAFARI:()=>vO,IS_CHROME:()=>pO,IS_CHROME_OS:()=>Kk,IS_CHROMIUM_BASE:()=>hO,IS_DESKTOP_IOS_CHROME:()=>DO,IS_EDG:()=>Ek,IS_EDGE:()=>_k,IS_ELECTRON:()=>Jk,IS_FIREFOX:()=>pk,IS_HEADLESS_CHROME:()=>mO,IS_HONOR:()=>eO,IS_HUAWEI:()=>Zk,IS_HUAWEIBROWSER:()=>$k,IS_IE:()=>Nk,IS_IE8:()=>Dk,IS_IOS:()=>sk,IS_IOS_13_OR_14:()=>CO,IS_IOS_15_1:()=>wO,IS_IOS_CHROME:()=>uO,IS_IPAD:()=>rk,IS_IPADQQB:()=>Hk,IS_IPAD_PRO:()=>ok,IS_IPHONE:()=>nk,IS_IPOD:()=>ak,IS_LINUX:()=>zk,IS_LOCAL:()=>NO,IS_MAC:()=>jk,IS_MACQQB:()=>Fk,IS_MIBROWSER:()=>Xk,IS_MQQB:()=>Lk,IS_NATIVE_ANDROID:()=>hk,IS_OLD_ANDROID:()=>uk,IS_OPENHARMONY:()=>lO,IS_OPPOBROWSER:()=>oO,IS_SAFARI:()=>EO,IS_SAFARI_15_1:()=>bO,IS_SAMSUNGBROWSER:()=>iO,IS_SOGOU:()=>Ak,IS_SOGOUM:()=>Tk,IS_TBS:()=>Rk,IS_UCBROWSER:()=>Yk,IS_VIVOBROWSER:()=>aO,IS_WECHAT:()=>Ok,IS_WIN:()=>Gk,IS_WQQB:()=>Uk,IS_WX:()=>qk,IS_X5MQQB:()=>Pk,IS_XWEB:()=>wk,MACQQB_VERSION:()=>Bk,MI_VERSION:()=>Qk,MQQB_VERSION:()=>xk,OPENHARMONY_VERSION:()=>cO,OPPO_VERSION:()=>nO,SAFARI_VERSION:()=>yO,SAMSUNG_VERSION:()=>rO,SOGOUM_VERSION:()=>Ik,SOGOU_VERSION:()=>Sk,TBS_VERSION:()=>bk,UA_DATA_STRING:()=>xO,USER_AGENT:()=>QN,VIVO_VERSION:()=>sO,WECHAT_VERSION:()=>Mk,WQQB_VERSION:()=>Vk,XWEB_VERSION:()=>Ck,browserInfo:()=>OO,getBrowserCoreNumber:()=>jO,getBrowserInfo:()=>MO,getChromeMajorVersion:()=>dO,getDeviceModel:()=>FO,getDeviceModelFromUA:()=>BO,getGPUInfo:()=>VO,getOSName:()=>WO,getOSNumber:()=>GO,getOSString:()=>zO,getOSType:()=>qO,getTerminalType:()=>KO,getUserAgentData:()=>UO,isLocalStorageEnabled:()=>kO,isMobile:()=>LO,isRealIOS:()=>lk,isVersionLargerThan:()=>SO,isVersionSmallerThan:()=>AO});var QN="undefined"==typeof navigator?"":navigator.userAgent,$N=e=>new RegExp(e,"i").test(QN),ZN=e=>{if($N(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=QN.match(t);if(i&&i[1])return i[1]}return""},ek=e=>{if($N(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=QN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},tk=/AppleWebKit\/([\d.]+)/i.exec(QN),ik=tk?parseFloat(tk[1]):NaN,rk=$N("iPad"),ok="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$N("Macintosh"),nk=$N("iPhone")&&!rk,ak=$N("iPod"),sk=nk||rk||ak||ok,lk=()=>{try{return sk&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch(UH){return sk}},ck=$N("Android"),dk=function(){if(ck){let e=QN.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}(),uk=ck&&$N("webkit")&&dk<2.3,hk=ck&&dk<5&&ik<537,pk=$N("Firefox"),mk=ZN("Firefox"),fk=ek("Firefox"),_k=$N("Edge"),gk=ZN("Edge"),Ek=$N("Edg"),vk=ZN("Edg"),yk=ek("Edg"),Tk=$N("SogouMobileBrowser"),Ik=ZN("SogouMobileBrowser"),Ak=$N("MetaSr\\s"),Sk=ZN("MetaSr\\s"),Rk=$N("TBS"),bk=ZN("TBS"),wk=$N("XWEB"),Ck=ZN("XWEB"),Dk=$N("MSIE\\s8\\.0"),Nk=$N("MSIE\\/\\d+"),kk=function(){if(Nk){let e=/MSIE\s(\d+)\.\d/.exec(QN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(QN)&&/rv:11.0/.test(QN)&&(t=11),t}return NaN}(),Ok=$N("(micromessenger|webbrowser)"),Mk=ZN("MicroMessenger"),Pk=!Rk&&$N("MQQBrowser")&&$N("COVC"),Lk=!Rk&&$N("MQQBrowser")&&!$N("COVC"),xk=Lk||Pk?ZN("MQQBrowser"):"",Uk=!Rk&&$N(" QQBrowser"),Vk=ZN(" QQBrowser"),Fk=!Rk&&$N("QQBrowserLite"),Bk=ZN("QQBrowserLite"),Hk=!Rk&&$N("MQBHD"),Wk=ZN("MQBHD"),Gk=$N("Windows"),jk=!sk&&$N("MAC OS X"),zk=!ck&&$N("Linux"),Kk=$N("CrOS"),qk=$N("MicroMessenger"),Yk=$N("UCBrowser"),Jk=$N("Electron"),Xk=$N("MiuiBrowser"),Qk=ZN("MiuiBrowser"),$k=$N("HuaweiBrowser"),Zk=$N("Huawei")||$N("HUAWEI"),eO=$N("Honor")||$N("HONOR"),tO=ZN("HuaweiBrowser"),iO=$N("SamsungBrowser"),rO=ZN("SamsungBrowser"),oO=$N("HeyTapBrowser"),nO=ZN("HeyTapBrowser"),aO=$N("VivoBrowser"),sO=ZN("VivoBrowser"),lO=$N("OpenHarmony"),cO=ZN("OpenHarmony"),dO=()=>ek("Chrome"),uO=$N("CriOS"),hO=$N("Chrome"),pO=!_k&&!Ak&&!Tk&&!Rk&&!wk&&!Ek&&!Uk&&!Xk&&!$k&&!iO&&!oO&&!aO&&hO,mO=$N("HeadlessChrome"),fO=dO(),_O=ZN("Chrome"),gO=ek("Electron"),EO=!hO&&!Lk&&!Pk&&!Fk&&!Hk&&$N("Safari"),vO=EO||sk,yO=ZN("Version"),TO=/Android.*(wv|.0.0.0)/.test(QN),IO=(()=>{if(ok)return yO;if(sk){let e=QN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function AO(e,t){let i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let o=0;o<Math.max(i.length,r.length);o++){let e=i[o]||0,t=r[o]||0;if(e<t)return!0;if(e>t)return!1}return!1}function SO(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.split(".").map((e=>Number(e))),o=t.split(".").map((e=>Number(e)));for(let n=0;n<Math.max(r.length,o.length);n++){let e=r[n]||0,t=o[n]||0;if(e>t)return!0;if(e<t)return!1}return i}var RO=Number(IO.split(".")[0]),bO="15.1"===yO,wO="15.1"===IO,CO=(()=>{let e=Number(IO.split(".")[0]);return 14===e||13===e})(),DO=uO&&"11.1.1"===yO,NO="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),kO=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(lM){e=!1}return e}})(),OO=MO();function MO(){let e=new Map([[pk,["Firefox",mk]],[Ek,["Edg",vk]],[pO,["Chrome",_O]],[uO,["ChiOS",ZN("CriOS")]],[EO&&!uO,["Safari",yO]],[Rk,["TBS",bk]],[wk,["XWEB",Ck]],[Ok&&nk,["WeChat",Mk]],[Uk,["QQ(Win)",Vk]],[Lk,["QQ(Mobile)",xk]],[Pk,["QQ(Mobile X5)",xk]],[Fk,["QQ(Mac)",Bk]],[Hk,["QQ(iPad)",Wk]],[Xk,["MI",Qk]],[$k,["HW",tO]],[iO,["Samsung",rO]],[oO,["OPPO",nO]],[aO,["VIVO",sO]],[_k,["EDGE",gk]],[Tk,["SogouMobile",Ik]],[Ak,["Sogou",Sk]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var PO=null;function LO(){return PO&&"boolean"==typeof PO.mobile?PO.mobile:ck||sk||nk||rk||lO}var xO="";function UO(){return nw(this,null,(function*(){if(PO)return PO;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(PO=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!xO&&(xO="UAData: ".concat(PO.platform,"/").concat(PO.platformVersion),PO.architecture&&PO.bitness&&(xO+=" ".concat(PO.architecture,"/").concat(PO.bitness)),PO.mobile&&(xO+=" mobile"),PO.model&&(xO+=" model: ".concat(PO.model.replace(/\s+/g,"/"))),PO.fullVersionList&&(xO+=" ".concat(PO.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),PO}catch(UH){return null}}))}function VO(){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(UH){return""}}function FO(){return(null==PO?void 0:PO.model)||BO()||""}function BO(){let e=QN.match(/;\s*([^;)]+)\s+Build\//);return null!=e&&e[1]?e[1].trim():null}var HO=new Map([[ck,"Android"],[sk,"iOS"],[Gk,"Windows"],[jk,"MacOS"],[zk,"Linux"],[Kk,"ChromeOS"]]),WO=function(){return HO.get(!0)?HO.get(!0):PO?PO.platform:"unknown"};function GO(){return Gk?1:ck?2:jk?3:sk?4:zk?5:Kk?6:lO?7:0}function jO(){return Ok||wk?4:hO?1:EO?2:pk?3:0}var zO=()=>{let e=WO();return null!=PO&&PO.platformVersion?e+="/".concat(PO.platformVersion):sk?e+="/".concat(IO):ck&&(e+="/".concat(dk)),e+="/".concat(OO.name,"/").concat(EO&&!uO?OO.version:OO.version.split(".")[0]),null!=PO&&PO.architecture&&(e+="/".concat(PO.architecture)),e};function KO(){return ck?4:nk?2:rk?3:jk?12:Gk?5:zk?13:lO?22:1}function qO(){return ck?"Android":nk?"iPhone":rk?"iPad":jk?"Mac":Gk?"Windows":zk?"Linux":"unknown"}var YO,JO=new(tw(aw(),1).default),XO=((YO=XO||{}).ROOM_DESTROY="1",YO.JOIN_START="21",YO.JOIN_SCHEDULE_SUCCESS="22",YO.JOIN_SIGNAL_CONNECTION_START="23",YO.JOIN_SIGNAL_CONNECTION_END="24",YO.JOIN_SEND_CMD="25",YO.JOIN_RECEIVED_CMD_RES="26",YO.JOIN_SUCCESS="27",YO.JOIN_FAILED="28",YO.LEAVE_START="51",YO.LEAVE_SEND_CMD="52",YO.LEAVE_SUCCESS="53",YO.PUBLISH_START="61",YO.SEND_FIRST_VIDEO_FRAME="62",YO.PUBLISH_FAILED="63",YO.SUBSCRIBE_START="81",YO.SUBSCRIBE_SUCCESS="82",YO.SUBSCRIBE_FAILED="84",YO.UNSUBSCRIBE_SUCCESS="83",YO.LOCAL_TRACK_CAPTURE_START="101",YO.LOCAL_TRACK_CAPTURE_SUCCESS="102",YO.LOCAL_TRACK_CAPTURE_FAILED="103",YO.LOCAL_TRACK_PUBLISHED="104",YO.LOCAL_TRACK_UNPUBLISHED="105",YO.LOCAL_TRACK_REPLACED="106",YO.SWITCH_DEVICE_SUCCESS="107",YO.TRACK_MUTED="108",YO.TRACK_UNMUTED="109",YO.REMOTE_TRACK_SUBSCRIBED="110",YO.REMOTE_TRACK_UNSUBSCRIBED="111",YO.LOCAL_TRACK_RECAPTURE="112",YO.LOCAL_AUDIO_STARTED="113",YO.LOCAL_AUDIO_STOPPED="114",YO.REMOTE_AUDIO_STARTED="115",YO.REMOTE_AUDIO_STOPPED="116",YO.PLAY_TRACK_START="151",YO.PLAYER_STATE_CHANGED="152",YO.VIDEO_LOADED_DATA="153",YO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",YO.AUDIO_CONTEXT_LONG_SUSPENDED="155",YO.REMOTE_VIDEO_PLAY_START="156",YO.REMOTE_VIDEO_PLAY_FINISH="157",YO.SIGNAL_CONNECTION_STATE_CHANGED="201",YO.PEER_CONNECTION_STATE_CHANGED="202",YO.SINGLE_CONNECTION_STAT="203",YO.SPC_RECONNECTED="204",YO.HEARTBEAT_REPORT="251",YO.RECEIVED_PUBLISHED_USER_LIST="252",YO.REMOTE_PUBLISH_STATE_CHANGED="253",YO.AUDIO_LEVEL_INTERVAL="260",YO.NETWORK_QUALITY="261",YO.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",YO.QUALITY_LIMITATION_CHANGED="263",YO.LOG="264",YO.AUDIO_PROCESSOR_DEBUG="265",YO.SSO_SWITCH="266",YO.SEI_MESSAGE="267",YO.USER_PAUSE_IN_PIP="268",YO.USER_RESUME_IN_PIP="269",YO.ENTER_PICTURE_IN_PICTURE="270",YO.LEAVE_PICTURE_IN_PICTURE="271",YO.SWITCH_ROOM_START="401",YO.SWITCH_ROOM_SUCCESS="407",YO.SWITCH_ROOM_FAILED="408",YO),QO=XO,$O=new class{constructor(){rw(this,"enable",!1),rw(this,"ssoFailCount",0),JO.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&JO.emit("266",{enable:!0})})),JO.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&JO.emit("266",{enable:!1})}},ZO=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),!bw&&!ww&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){JO.on(QO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&jw[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),JO.on(QO.JOIN_START,(e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),JO.on(QO.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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})}));else if(zD(i.userId)&&KD(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 nw(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:o}=t[e],n={timestamp:gw(),sdkAppId:String(r),userId:i,version:Iw,log:o.map((e=>e.log)).join("\n")},a=JSON.stringify(n),s=$O.enable?MN(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach((e=>e.uploaded=!0))}}catch(cM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return YN({retryFunction:()=>HN({url:SD(t,Ww.LOG),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&($O.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(_w()),"[".concat(Ew(t),"] <").concat(jw[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){jD(jw[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(zD(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Sw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=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:r,sdkAppId:o,forAllJoinedClients:i};JO.emit(QO.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(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(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=jw[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",...i):console[s](...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){if(e.parent instanceof JN){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)Kb.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&jb)for(var r of jb(e))t.indexOf(r)<0&&qb.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new JN(r);return o.bindParent(i),o}return new JN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;jw[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};rw(ZO,"PRINT_LOG_TAG",!(sk||ck||mO));var eM=new ZO,tM=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)}))},iM=new class{constructor(){rw(this,"_prefix","TRTC"),rw(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){kO()&&(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(cM){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(kO())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(lM){eM.warn(lM)}}getItem(e){if(!kO())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(Sw){eM.warn(Sw)}}setItem(e,t){if(kO())try{let i={expiresIn:Date.now()+Yw,value:t};this._queue.set(this.getRealKey(e),i)}catch(CC){eM.warn(CC)}}deleteItem(e){if(!kO())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Sw){return eM.warn(Sw),!1}}clear(){if(kO())try{localStorage.clear()}catch(lM){eM.warn(lM)}}},rM={};ew(rM,{HTTPS_API:()=>qP,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>fL,IS_GET_CAPABILITIES_SUPPORTED:()=>mL,IS_GET_SETTINGS_SUPPORTED:()=>pL,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>hL,IS_INSERTABLE_STREAM_SUPPORTED:()=>_L,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>DL,IS_RTC_RTP_SENDER_SUPPORTED:()=>cL,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>gL,IS_SEI_SUPPORTED:()=>EL,IS_SPC_SUPPORTED:()=>sL,basis:()=>SL,capabilityCheck:()=>wL,checkSystemRequirementsInternal:()=>HP,decodeSupportStatus:()=>BP,detectVideoCodecCapabilities:()=>OL,detectVideoDecoderCapabilities:()=>PL,detectVideoEncoderCapabilities:()=>ML,encodeSupportStatus:()=>FP,getBrowserInfo:()=>kP,getDisplayResolution:()=>JP,getH264ProfileLevelIds:()=>LL,isAddTransceiverSupported:()=>aL,isBrowserSupported:()=>OP,isCanvasCaptureStreamAPISupported:()=>$P,isCanvasSmallStreamSupported:()=>ZP,isGetReceiversSupported:()=>rL,isGetSendersSupported:()=>oL,isGetTransceiversSupported:()=>nL,isGetUserMediaSupported:()=>XP,isMediaDevicesSupported:()=>PP,isMediaSessionSupported:()=>TL,isMediaStreamTrackGeneratorSupported:()=>VP,isMediaStreamTrackProcessorSupported:()=>UP,isReplaceTrackSupported:()=>dL,isRequestVideoFrameCallbackSupported:()=>CL,isSIMDSupported:()=>AL,isScaleResolutionDownBySupported:()=>eL,isScreenCaptureApiAvailable:()=>GP,isSelectedCandidatePair:()=>YP,isSetParametersSupported:()=>uL,isSetSinkIdSupported:()=>jP,isSmallStreamSupported:()=>tL,isStopTransceiverSupported:()=>lL,isTRTCSupported:()=>WP,isUnifiedPlanDefault:()=>iL,isUsedInHttpProtocol:()=>xP,isWebAudioSupported:()=>QP,isWebCodecSupported:()=>yL,isWebCodecsSupported:()=>MP,isWebRTCSupported:()=>vL,isWebTransportSupported:()=>IL});var oM={};ew(oM,{AUDIO_LEVEL_SCALE:()=>XM,AlphaStitchingType:()=>dP,AudioCodecPipelineType:()=>iP,AudioDecoderDowngradeState:()=>kM,AudioPlayerMode:()=>qM,AudioType:()=>UM,BASIC_TYPE:()=>ZM,BannedReason:()=>YM,CONNECTION_CLOSED_REASON:()=>EM,CheckPermissionType:()=>lP,ClientEvent:()=>vM,CodecType:()=>rP,ConnectionEvent:()=>gM,ConnectionState:()=>NM,DECODE_FAILED_ERROR_CODE:()=>oP,DenoiserMode:()=>QM,DeviceType:()=>cP,FacingMode:()=>zM,FrameWorkType:()=>_M,LeaveReason:()=>JM,LocalTrackEvent:()=>TM,MULTI_VIDEO_DATA_TYPE:()=>HM,MediaType:()=>LM,MediaTypeLabel:()=>xM,MonitorEventId:()=>WM,MutedFlag:()=>bM,NetworkQualityValue:()=>GM,PlayerState:()=>IM,ReceiveMode:()=>jM,RemoteStreamType:()=>BM,RemoteTrackEvent:()=>RM,RoomEvent:()=>AM,SMALL_MODE:()=>sP,SceneNumber:()=>wM,StreamEvent:()=>yM,StreamType:()=>FM,SubscribeMediaType:()=>$M,TIMER_TYPE:()=>aP,TRACK_ACTION:()=>PM,TRACK_KIND:()=>MM,TrackEvent:()=>SM,UserRole:()=>DM,UserRoleNumber:()=>CM,VideoCodec:()=>eP,VideoCodecPipelineType:()=>tP,VideoContentHint:()=>nP,VideoDecoderDowngradeState:()=>OM,VideoPlayerMode:()=>KM,VideoType:()=>VM});var nM,aM,sM,lM,cM,dM,uM,hM,pM,mM,fM,_M=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(_M||{}),gM=((fM=gM||{}).TRACK_ADDED="track-added",fM.TRACK_UPDATED="track-updated",fM.TRACK_SUBSCRIBED="track-subscribed",fM.STREAM_ADDED="stream-added",fM.STREAM_REMOVED="stream-removed",fM.STREAM_UPDATED="stream-updated",fM.STREAM_PUBLISHED="stream-published",fM.STREAM_SUBSCRIBED="stream-subscribed",fM.STREAM_UNSUBSCRIBED="stream-unsubscribed",fM.STATE_CHANGED="state-changed",fM.ERROR="error",fM.CONNECTION_STATE_CHANGED="connection-state-changed",fM.FIREWALL_RESTRICTION="firewall-restriction",fM.SEI_MESSAGE="sei-message",fM.CLOSED="closed",fM),EM=(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))(EM||{}),vM=((mM=vM||{}).STREAM_ADDED="stream-added",mM.STREAM_REMOVED="stream-removed",mM.STREAM_UPDATED="stream-updated",mM.STREAM_SUBSCRIBED="stream-subscribed",mM.CONNECTION_STATE_CHANGED="connection-state-changed",mM.PEER_JOIN="peer-join",mM.PEER_LEAVE="peer-leave",mM.MUTE_AUDIO="mute-audio",mM.MUTE_VIDEO="mute-video",mM.UNMUTE_AUDIO="unmute-audio",mM.UNMUTE_VIDEO="unmute-video",mM.CLIENT_BANNED="client-banned",mM.NETWORK_QUALITY="network-quality",mM.AUDIO_VOLUME="audio-volume",mM.SEI_MESSAGE="sei-message",mM.ERROR="error",mM),yM=((pM=yM||{}).PLAYER_STATE_CHANGED="player-state-changed",pM.SCREEN_SHARING_STOPPED="screen-sharing-stopped",pM.CONNECTION_STATE_CHANGED="connection-state-changed",pM.DEVICE_AUTO_RECOVERED="device-auto-recovered",pM.ERROR="error",pM),TM=((hM=TM||{}).DEVICE_AUTO_RECOVERED="1",hM.DEVICE_RECOVER_FAILED="5",hM.DEVICE_CHANGED="2",hM.ERROR="3",hM.PUBLISH_STATE_CHANGED="4",hM.ENCODE_FAILED="6",hM.TRACK_ENDED="7",hM.RENDER="render",hM),IM=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(IM||{}),AM=((uM=AM||{}).PEER_JOIN="peer-join",uM.PEER_LEAVE="peer-leave",uM.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",uM.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",uM.BANNED="banned",uM.NETWORK_QUALITY="network-quality",uM.AUDIO_VOLUME="audio-volume",uM.SEI_MESSAGE="sei-message",uM.ERROR="error",uM.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",uM.REMOTE_PUBLISHED="remote-published",uM.REMOTE_UNPUBLISHED="remote-unpublished",uM.FIREWALL_RESTRICTION="firewall-restriction",uM.HEARTBEAT_REPORT="heartbeat-report",uM.CUSTOM_MESSAGE="custom-message",uM.LAYER_DATA="layerData",uM.FIRST_VIDEO_FRAME="first-video-frame",uM.DUMP="dump",uM.AUDIO_FRAME="audio-frame",uM.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",uM.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",uM.NTP_TIME_UPDATED="ntp-time-updated",uM),SM=(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))(SM||{}),RM=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_FAILED_DURING_CALL="decode-failed-during-call",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e.REMOTE_PUBLISH_CHANGED="remote-publish-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",e))(RM||{}),bM=((dM=bM||{})[dM.VIDEO=1]="VIDEO",dM[dM.SMALL=2]="SMALL",dM[dM.AUX=4]="AUX",dM[dM.AUDIO=8]="AUDIO",dM[dM.VIDEO_MUTE=16]="VIDEO_MUTE",dM[dM.AUX_MUTE=32]="AUX_MUTE",dM[dM.AUDIO_MUTE=64]="AUDIO_MUTE",dM),wM=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(wM||{}),CM=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(CM||{}),DM=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(DM||{}),NM=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(NM||{}),kM=((cM=kM||{}).INITIALIZED="INITIALIZED",cM.STARTING="STARTING",cM.STARTED="STARTED",cM.FAILED="FAILED",cM),OM=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(OM||{}),MM=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(MM||{}),PM=(e=>(e.ADD="add",e.REMOVE="remove",e))(PM||{}),LM=(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))(LM||{}),xM={1:"audio",2:"auxVideo",4:"video"},UM=((lM=UM||{})[lM.opus=111]="opus",lM),VM=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(VM||{}),FM=(e=>(e.Big="big",e.Small="small",e))(FM||{}),BM=(e=>(e.Main="main",e.Aux="auxiliary",e))(BM||{}),HM=(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))(HM||{}),WM=((sM=WM||{})[sM.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",sM[sM.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",sM[sM.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",sM[sM.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",sM[sM.MUTE_AUDIO=32772]="MUTE_AUDIO",sM[sM.MUTE_VIDEO=32773]="MUTE_VIDEO",sM[sM.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",sM[sM.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",sM[sM.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",sM[sM.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",sM[sM.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",sM[sM.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",sM[sM.SWITCH_CAMERA=32780]="SWITCH_CAMERA",sM[sM.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",sM[sM.REPLACE_VIDEO=32782]="REPLACE_VIDEO",sM[sM.REPLACE_AUDIO=32783]="REPLACE_AUDIO",sM[sM.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",sM[sM.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",sM[sM.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",sM[sM.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",sM[sM.JOIN=32788]="JOIN",sM[sM.LEAVE=32789]="LEAVE",sM[sM.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",sM[sM.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",sM[sM.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",sM[sM.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",sM[sM.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",sM[sM.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",sM[sM.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",sM[sM.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",sM[sM.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",sM[sM.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",sM[sM.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",sM[sM.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",sM[sM.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",sM[sM.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",sM[sM.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",sM[sM.PUBLISH_AUX=32805]="PUBLISH_AUX",sM[sM.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",sM[sM.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",sM[sM.VIDEO_ENCODER=4004]="VIDEO_ENCODER",sM[sM.VIDEO_DECODER=4005]="VIDEO_DECODER",sM),GM=(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))(GM||{}),jM=(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))(jM||{}),zM=(e=>(e.user="user",e.environment="environment",e))(zM||{}),KM=(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))(KM||{}),qM=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(qM||{}),YM=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(YM||{}),JM=((aM=JM||{})[aM.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",aM[aM.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",aM[aM.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",aM[aM.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",aM[aM.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",aM[aM.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",aM[aM.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",aM),XM=1e8,QM=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(QM||{}),$M=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)}},ZM=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(ZM||{}),eP=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(eP||{}),tP=(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))(tP||{}),iP=(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))(iP||{}),rP=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(rP||{}),oP=((nM=oP||{})[nM.SUCCESS=0]="SUCCESS",nM[nM.FAILED=1]="FAILED",nM[nM.WEBCODEC_INIT=2]="WEBCODEC_INIT",nM[nM.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",nM[nM.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",nM[nM.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",nM[nM.WASM_INIT=6]="WASM_INIT",nM[nM.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",nM[nM.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",nM[nM.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",nM[nM.TEST=10]="TEST",nM[nM.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",nM),nP=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(nP||{}),aP=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(aP||{}),sP=(e=>(e.CANVAS="canvas",e.API="api",e))(sP||{}),lP=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(lP||{}),cP=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cP||{}),dP=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(dP||{}),uP={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"},hP={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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(o,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:o}=e;return"the max value of ".concat(t||i.name," is ").concat(i.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: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:o}=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:o}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(o," 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,"()")},pP=(e,t)=>t?"".concat(Lw,"/").concat(e,"/").concat(t):"".concat(Lw,"/").concat(e,"/index.html"),mP=()=>{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(Hw);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 fP(e){let{key:t,data:i,link:r,addDocLink:o=!0}=e,n="",a="",s="";GD(hP[t])?n=hP[t](i):zD(hP[t])&&(n=hP[t]);let{TRTC_ERROR_INFO:l,TRTC_ERROR_LINK:c}=mP();r?s="".concat(r.className,".html#").concat(r.fnName):c&&c[t]&&(GD(c[t])?s=c[t](i):zD(c[t])&&(s=c[t]));let d=n;return VD()&&(l&&l[t]&&(GD(l[t])?a=l[t](i):zD(l[t])&&(a=l[t])),a&&(d=o?"".concat(a,"\n请查看文档: ").concat(pP("zh-cn",s),"\n\n"):"".concat(a,"\n\n"),d+=n)),o&&(d+=" \nRefer to: ".concat(pP("en",s),"\n")),d}var _P,gP,EP,vP=tw(dw(),1),yP=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",eM.createLogger({id:"kv"})),e&&(JO.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===eC.AUDIO?501700:511700,cost:i})})),JO.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===eC.AUDIO?501700:511700,error:i})})),JO.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:IN(this.version||Iw),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 o;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 n=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map;n.set(i,(n.get(i)||0)+1),this.distributionMap.set(t,n)}addNumber(e){let{key:t,value:i,split:r=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;i>n&&(i=n),this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(a=this.distributionMap)?void 0:a.get(t))||new Map,l=0;if(KD(r))l=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){l=c;break}s.set(l,(s.get(l)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:o}=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:o}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=hw.UNKNOWN;i&&(KD(i)?r=i:(!jD(i.extraCode)||!jD(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})}},TP=((gP=TP||{})[gP.enterRoom=500700]="enterRoom",gP[gP.exitRoom=500701]="exitRoom",gP[gP.switchRole=500702]="switchRole",gP[gP.destroy=500703]="destroy",gP[gP.startLocalAudio=500704]="startLocalAudio",gP[gP.updateLocalAudio=500705]="updateLocalAudio",gP[gP.stopLocalAudio=500706]="stopLocalAudio",gP[gP.startLocalVideo=500707]="startLocalVideo",gP[gP.updateLocalVideo=500708]="updateLocalVideo",gP[gP.stopLocalVideo=500709]="stopLocalVideo",gP[gP.startScreenShare=500710]="startScreenShare",gP[gP.updateScreenShare=500711]="updateScreenShare",gP[gP.stopScreenShare=500712]="stopScreenShare",gP[gP.startRemoteVideo=500713]="startRemoteVideo",gP[gP.updateRemoteVideo=500714]="updateRemoteVideo",gP[gP.stopRemoteVideo=500715]="stopRemoteVideo",gP[gP.muteRemoteAudio=500716]="muteRemoteAudio",gP[gP.setRemoteAudioVolume=500717]="setRemoteAudioVolume",gP[gP.use=500718]="use",gP[gP.switchRoom=500719]="switchRoom",gP[gP.getPermissions=500720]="getPermissions",gP[gP.sendSEIMessage=5e5]="sendSEIMessage",gP[gP.sendCustomMessage=500001]="sendCustomMessage",gP),IP=((_P=IP||{})[_P.AudioMixer=550700]="AudioMixer",_P[_P.AIDenoiser=551700]="AIDenoiser",_P[_P.VirtualBackground=570700]="VirtualBackground",_P[_P.Beauty=571700]="Beauty",_P[_P.Watermark=572700]="Watermark",_P[_P.BasicBeauty=574700]="BasicBeauty",_P[_P.FaceDetector=575700]="FaceDetector",_P[_P.CDNStreaming=590700]="CDNStreaming",_P[_P.DeviceDetector=591700]="DeviceDetector",_P[_P.Debug=592700]="Debug",_P[_P.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",_P[_P.VideoMixer=594700]="VideoMixer",_P[_P.AudioProcessor=595700]="AudioProcessor",_P),AP=(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.FaceDetector=575701]="FaceDetector",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))(AP||{}),SP=(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.FaceDetector=575702]="FaceDetector",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))(SP||{}),RP=((EP=RP||{})[EP.DECODER_TYPE=514700]="DECODER_TYPE",EP[EP.DECODER_HW_SW=514701]="DECODER_HW_SW",EP[EP.DECODE_RESULT=514702]="DECODE_RESULT",EP[EP.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",EP[EP.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",EP[EP.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",EP[EP.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",EP[EP.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",EP[EP.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",EP[EP.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",EP[EP.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",EP[EP.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",EP[EP.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",EP[EP.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",EP[EP.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",EP[EP.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",EP[EP.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",EP[EP.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",EP[EP.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",EP),bP=new yP(!0),wP=new yP(!1),CP=bP,DP={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}},NP=new Map([[pk,["Firefox",mk]],[Ek,["Edg",vk]],[pO,["Chrome",_O]],[EO,["Safari",yO]],[Rk,["TBS",bk]],[wk,["XWEB",Ck]],[Ok&&nk,["WeChat",Mk]],[Uk,["QQ(Win)",Vk]],[Lk,["QQ(Mobile)",xk]],[Pk,["QQ(Mobile X5)",xk]],[Fk,["QQ(Mac)",Bk]],[Hk,["QQ(iPad)",Wk]],[Xk,["MI",Qk]],[$k,["HW",tO]],[iO,["Samsung",rO]],[oO,["OPPO",nO]],[aO,["VIVO",sO]],[_k,["EDGE",gk]],[Tk,["SogouMobile",Ik]],[Ak,["Sogou",Sk]]]);function kP(){let e=NP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var OP=function(){return!(Yk||_k||Ek&&yk<80||pk&&fk<56)},MP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},PP=function(){if(!navigator.mediaDevices)return xP()||eM.error(hP.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},LP=!1;function xP(){return"http:"===location.protocol&&!NO&&(LP||eM.error(fP({key:uP.NOT_SUPPORTED_HTTP})),LP=!0,!0)}var UP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},VP=function(){return!(null==window||!window.MediaStreamTrackGenerator)},FP=function(){return nw(this,null,(function*(){var e,t,i;if(DP.detail.isH264EncodeSupported&&DP.detail.isVp8EncodeSupported)return{isH264EncodeSupported:DP.detail.isH264EncodeSupported,isVp8EncodeSupported:DP.detail.isVp8EncodeSupported,isH265EncodeSupported:DP.detail.isH265EncodeSupported};let r,o=!1,n=!1,a=!1;try{let s=new RTCPeerConnection,l=document.createElement(eC.CANVAS);l.getContext("2d");let c=l.captureStream(0);return s.addTrack(c.getVideoTracks()[0],c),r=yield s.createOffer(),o=-1!==(null==(e=r.sdp)?void 0:e.toLowerCase().indexOf("h264")),n=-1!==(null==(t=r.sdp)?void 0:t.toLowerCase().indexOf("vp8")),a=-1!==(null==(i=r.sdp)?void 0:i.toLowerCase().indexOf("h265")),s.close(),{isH264EncodeSupported:o,isVp8EncodeSupported:n,isH265EncodeSupported:a}}catch(dM){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}}))},BP=function(){return nw(this,null,(function*(){var e;if(DP.detail.isH264DecodeSupported&&DP.detail.isVp8DecodeSupported)return{isH264DecodeSupported:DP.detail.isH264DecodeSupported,isVp8DecodeSupported:DP.detail.isVp8DecodeSupported,isH265DecodeSupported:DP.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let o=new RTCPeerConnection;aL()?(o.addTransceiver(eC.VIDEO,{direction:"recvonly"}),t=yield o.createOffer()):t=yield o.createOffer({offerToReceiveVideo:!0}),-1!==t.sdp.toLowerCase().indexOf("h264")&&(i=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0);let n=-1!==(null==(e=t.sdp)?void 0:e.toLowerCase().indexOf("h265"));return o.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:n}}catch(cM){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}}))};var HP=RN((e=>nw(void 0,null,(function*(){let t=Date.now(),i=vL(),r=PP(),o=MP();if(DP.detail.isWebRTCSupported=i,DP.detail.isMediaDevicesSupported=r,DP.detail.isWebCodecsSupported=o,DP.detail.isScreenShareSupported=GP(),DP.detail.isSmallStreamSupported=tL(),37===e)return Object.assign(DP.detail,yield function(){return nw(this,null,(function*(){return KP||(KP=new Promise((e=>nw(this,null,(function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!MP())return void e(t);let i=null,r=null,o=null,n=()=>{o&&clearTimeout(o),i=null,r=null};try{i=document.createElement("canvas"),r=i.getContext("2d"),i.width=320,i.height=240;let a=0,s=()=>{!r||!i||(r.fillStyle="hsl(".concat(a%360,", 50%, 50%)"),r.fillRect(0,0,i.width,i.height),r.fillStyle="white",r.font="20px Arial",r.fillText("Frame ".concat(a),10,30),a++)};o=setTimeout((()=>{n(),e(t)}),5e3);let l=[{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(l.map((e=>nw(this,null,(function*(){let t,r={type:e.type,encodeSupported:!1,decodeSupported:!1};try{t=yield new Promise(((t,o)=>nw(this,null,(function*(){try{let n=new VideoEncoder({output:e=>{t(e),r.encodeSupported=!0},error:o});n.configure(e.encodeConfig),s();let a=new VideoFrame(i,{timestamp:0});n.encode(a,{keyFrame:!0}),a.close(),yield n.flush(),n.close()}catch(fM){o(fM)}}))))}catch(p){return eM.warn("".concat(e.type," encoder error:"),p),r}try{yield new Promise(((i,o)=>nw(this,null,(function*(){try{let n=new VideoDecoder({output:e=>{r.decodeSupported=!0,i(0),e.close()},error:o});n.configure(e.decodeConfig),n.decode(t),yield n.flush(),n.close()}catch(fM){o(fM)}}))))}catch(p){eM.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)})),n(),e(t)}catch(a){n(),eM.warn("detectWebCodecsSupported failed:",a),e(t)}})))),KP)}))}()),DP.detail.isBrowserSupported=o,DP.result=r&&o,DP.result||eM.error("".concat(navigator.userAgent," ").concat(EN(DP.detail,!1))),bL(e),CP.addNumber({key:523800,value:Date.now()-t}),DP;if(DP.result&&DP.detail.isH264EncodeSupported&&DP.detail.isVp8EncodeSupported&&DP.detail.isH265EncodeSupported&&DP.detail.isH264DecodeSupported&&DP.detail.isVp8DecodeSupported&&DP.detail.isH265DecodeSupported)return DP;let n=OP(),{encode:a,decode:s}=yield function(){return nw(this,null,(function*(){let[e,t]=yield Promise.all([FP(),BP()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}}))}(),{h264:l,vp8:c}=a,{h264:d}=s,{h265:u}=a,{vp8:h,h265:p}=s;if(!l||!c){let e=yield FP();eM.warn("detect encode again h264:".concat(l," vp8:").concat(c," result: ").concat(JSON.stringify(e))),l=e.isH264EncodeSupported,c=e.isVp8EncodeSupported}if(l&&d&&ck&&hO&&!wk&&!Rk&&(!oO||115!==fO)){let{encode:e,decode:t}=yield function(){return nw(this,null,(function*(){return zP||(zP=new Promise((e=>nw(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=640,r.height=480;let n=setInterval((()=>{o.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),66),a=-1,s=-1;i=()=>{clearInterval(a),clearInterval(n),clearTimeout(s),c.close(),d.close(),l.getTracks().forEach((e=>e.stop()))},s=setTimeout((()=>{i(),e(t)}),2e3);let l=r.captureStream(),c=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});c.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>c.addIceCandidate(e.candidate))),c.addTrack(l.getVideoTracks()[0],l);let u=yield c.createOffer();yield c.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=vP.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=vP.default.write(p),yield d.setLocalDescription(h),yield c.setRemoteDescription(h),a=setInterval((()=>nw(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let[r,o]=yield Promise.all([c.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===eC.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||o.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===eC.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),eM.warn("detectH264Supported failed",r),e({encode:!0,decode:!0})}})))).then((e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&eM.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(xO)),e))),zP)}))}();l=e,d=t}return DP.result=n&&i&&r&&(l||c)&&(d||h),DP.detail.isBrowserSupported=n,DP.detail.isWebRTCSupported=i,DP.detail.isH264EncodeSupported=l,DP.detail.isVp8EncodeSupported=c,DP.detail.isH265EncodeSupported=u,DP.detail.isH264DecodeSupported=d,DP.detail.isVp8DecodeSupported=h,DP.detail.isH265DecodeSupported=p,DP.result||eM.error("".concat(navigator.userAgent," ").concat(EN(DP.detail,!1))),bL(),CP.addNumber({key:523800,value:Date.now()-t}),DP})))),WP=function(){return DP.result},GP=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},jP="undefined"!=typeof HTMLMediaElement&&"setSinkId"in HTMLMediaElement.prototype,zP=null;var KP=null;var qP=(e,t,i)=>{"http:"===location.protocol&&!NO&&(e[t]=()=>{throw new mw({code:hw.INVALID_OPERATION,message:hP.NOT_SUPPORTED_HTTP})})},YP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(qD(e.selected)&&!e.selected)};function JP(){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 XP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function QP(){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 $P(){return"captureStream"in HTMLCanvasElement.prototype}function ZP(){return!(Ok||sk||fO&&fO<63)&&!(!OP()||!$P())}function eL(){return!(fO<74||_k||RO<11||fk<46)}function tL(){return ZP()||eL()}var iL=function(){if(jD(window.RTCRtpTransceiver)||!aL()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:PC}),e.addTransceiver(eC.AUDIO),t=!0}catch(Sw){}return null==e||e.close(),t};function rL(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function oL(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function nL(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function aL(){return!(11===RO&&!DO)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var sL=!(!aL()||hO&&fO<86);function lL(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var cL="RTCRtpSender"in window;function dL(){return cL&&"replaceTrack"in window.RTCRtpSender.prototype}function uL(){return cL&&"setParameters"in window.RTCRtpSender.prototype&&oL()}var hL="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,pL=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,mL=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,fL="undefined"!=typeof InputDeviceInfo&&"getCapabilities"in InputDeviceInfo.prototype,_L=cL&&"createEncodedStreams"in window.RTCRtpSender.prototype&&dO()>=86,gL="RTCRtpScriptTransform"in window,EL=cL&&(_L||gL),vL=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function yL(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return jD(window.AudioDecoder)||(e.AudioDecoder=!0),jD(window.AudioEncoder)||(e.AudioEncoder=!0),jD(window.VideoDecoder)||(e.VideoDecoder=!0),jD(window.VideoEncoder)||(e.VideoEncoder=!0),jD(window.ImageDecoder)||(e.ImageDecoder=!0),e}function TL(){return"mediaSession"in navigator&&!jD(navigator.mediaSession.setActionHandler)}function IL(){return!jD(window.WebTransport)}function AL(){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 SL(){let e={browser:"".concat(OO.name,"/").concat(OO.version),os:WO(),displayResolution:JP(),isScreenShareSupported:GP(),isWebRTCSupported:vL(),isGetUserMediaSupported:XP(),isWebAudioSupported:QP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:yL(),isMediaSessionSupported:TL(),isWebTransportSupported:IL()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var RL="checkResult";function bL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30;iM.setItem(RL+e,{ua:navigator.userAgent,checkResult:DP})}function wL(e){xP();let t=iM.getItem(RL+e);t&&t.ua===navigator.userAgent&&t.checkResult&&function(e,t){return!!YD(e)&&Object.keys(t).every((t=>t in e))}(t.checkResult.detail,DP.detail)&&(DP=t.checkResult),HP(e)}function CL(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var DL="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function NL(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var kL=!1;function OL(){return nw(this,null,(function*(){var e;try{if(kL||null==(e=null==navigator?void 0:navigator.mediaCapabilities)||!e.encodingInfo)return;let t=GO(),i=jO();if(0===t||0===i)return;kL=!0;let r=["H264","VP8","VP9","AV1","H265"],[o,n]=yield Promise.all([ML(r),PL(r)]);o&&Object.keys(o).forEach((e=>{let r=NL(e.toLowerCase());CP.addEnum({key:513707,value:+"".concat(r).concat(+o[e].supported).concat(+o[e].powerEfficient).concat(t).concat(i),useUV:!1})})),n&&Object.keys(n).forEach((e=>{let r=NL(e.toLowerCase());CP.addEnum({key:514713,value:+"".concat(r).concat(+n[e].supported).concat(+n[e].powerEfficient).concat(t).concat(i),useUV:!1})}));let{sender:a,receiver:s}=LL();CP.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+a.high),useUV:!1}),CP.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+a.main),useUV:!1}),CP.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+s.high),useUV:!1}),CP.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+s.main),useUV:!1})}catch(lM){eM.info("detectVideoCodecCapabilities failed",lM)}}))}function ML(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return nw(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:i,bitrate:o,framerate:r}});n[a]=e}}catch(Rw){}return n}))}function PL(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,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:3e3;return nw(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:i,bitrate:o,framerate:r}});n[a]=e}}catch(Rw){}return n}))}function LL(){let e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};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])switch(i[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}}))}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])switch(i[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}}))}}catch(lM){eM.warn("get H264 profile levelId failed",lM)}return e}var xL=tw(aw(),1),UL=Symbol("instance"),VL=Symbol("cacheResult"),FL=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,jL.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},BL=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var HL=new Map;function WL(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=HL.get(r)||[];HL.has(r)||HL.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=zL.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[VL]:Promise.resolve(r[VL]);r.state instanceof FL&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof FL&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(c=new BL(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new BL(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new FL(u,t,a);jL.call(r,h);let p=e=>{var o;return r[VL]=e,h.aborted||(jL.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[VL])),e},m=e=>(jL.call(r,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):i.sync?p(e):Promise.resolve(p(e))}catch(mM){return m(new BL(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(mM),mM instanceof Error?mM:new Error(String(mM))))}}}}var GL="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 jL(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(zL.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var zL=class e extends xL.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 o=r[UL];o?this.name=o.name+"-"+o.count++:r[UL]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=HL.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);HL.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:n})})):o.push({to:i,action:n})})),r.forEach((e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};GL(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){jL.call(this,e)}};zL.STATECHANGED="stateChanged",zL.UPDATEAFSM="updateAFSM",zL.INIT="[*]",zL.ON="on",zL.OFF="off",zL.instances=new Map,zL.instances2=new WeakMap;var KL="undefined"!=typeof window,qL=KL&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},YL=KL&&window.cancelIdleCallback||function(e){clearTimeout(e)},JL=KL&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),XL=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=Qb("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=$b(Qb({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=oN(),o=()=>{if(i=oN()-r,i>=t.delay&&(r=oN()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=qL(o,{timeout:t.delay})};return t.ricID=qL(o,{timeout:t.delay})}static raf(t){let i,r=oN(),o=()=>document.hidden&&t.backgroundTask?(i=oN()-r,r=oN(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(i%t.delay))):(i=oN()-r,i>=t.delay&&(r=oN()-Math.floor(i%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=oN()-r;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:i,rafID:r,ricID:o,onVisibilitychange:n}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&JL&&JL(r),o&&YL(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(XL,"taskMap",new Map),rw(XL,"currentTaskID",1),rw(XL,"sharedWorker",null),rw(XL,"workerTasks",new Map);var QL=XL;eC.SEI_MESSAGE;var $L={LOAD_START:eC.LOADSTART,LOADED_DATA:eC.LOADEDDATA,LOADED_META_DATA:eC.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:eC.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:eC.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:eC.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP:"user-resume-in-pip",USER_PAUSE_IN_PIP:"user-pause-in-pip"},ZL={};ew(ZL,{create:()=>tx,remove:()=>ix});var ex=new WeakMap;function tx(e,t){ex.has(e)||ex.set(e,[]);let i=ex.get(e),r={add:(e,o)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,o)),t.addEventListener(e,o)):(i.push(t.off.bind(t,e,o)),t.on(e,o)),r)};return r}function ix(e){let t=ex.get(e);t&&(t.forEach((e=>e())),ex.delete(e))}var rx=new class{constructor(){rw(this,"_roomIdMap",new Map),rw(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Iw,env:Gw.QCLOUD,browserVersion:OO.name+OO.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:o}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(e){NO||!eM.isAbleToUpload||this._configs.env===Gw.QCLOUD&&this.uploadEventToKibana($b(Qb({},e),{result:"success"}))}logFailedEvent(e){if(NO||!eM.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:o}=e,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||hw.UNKNOWN};this._configs.env===Gw.QCLOUD&&this.uploadEventToKibana($b(Qb({},n),{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,o={timestamp:gw(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Iw,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+="\n".concat(r.stack)));let n=$O.enable?MN(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(SD(this._configs.sdkAppId,Ww.LOG),n)}sendRequest(e,t){setTimeout((()=>HN({url:e,body:t,priority:"low"}).catch((()=>{}))),2e3)}},ox=new WeakMap;function nx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:o}=e;return function(e,n,a){let s=YN({retryFunction:a.value,settings:t,onError(t){let{error:r,retry:o,reject:a,retryFuncArgs:s}=t;var l;i?i.call(this,r,(()=>{var t;null!=(t=ox.get(e))&&t.has(n)?o():a(r)}),a,s):null!=(l=ox.get(e))&&l.has(n)?o():a(r)},onRetrying(t,i){var o;jN(r)&&r.call(this,t,i),null!=(o=ox.get(e))&&o.has(n)&&(ox.get(e).get(n).stopRetry=i)},onRetryFailed:o});return a.value=function(){let t=ox.get(e);for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return t?t.set(n,{args:r}):ox.set(e,new Map([[n,{args:r}]])),s.apply(this,r).finally((()=>{var t;return null==(t=ox.get(e))?void 0:t.delete(n)}))},a}}var ax=class extends zL{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,"isPlayCalled",!1),rw(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=KC,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 nw(this,null,(function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,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(Sw){let t=fP({key:uP.PLAY_FAILED,data:{media:this.kind,error:Sw}});if(this._log.warn(Sw),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new mw({code:hw.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!vO?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(eC.ENDED),this._interval>0&&QL.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(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;null==(e=this.element)||e.pause()}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(e)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():wO?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return tx(this.element,this.element).add(eC.PLAYING,e).add(eC.ENDED,e).add(eC.PAUSE,e).add(eC.ERROR,e).add(eC.LOADSTART,e).add(eC.LOADEDDATA,e).add(eC.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==ZL||ZL.create(e,e).add(eC.ENDED,t).add(eC.MUTE,t).add(eC.UNMUTE,t),e.readyState===eC.ENDED&&this.handleTrackEvent({type:eC.ENDED}),e.muted&&this.handleTrackEvent({type:eC.MUTE})}}bindAutoPlayEvent(){JO.listeners(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM).includes(this.resume)||JO.on(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&ix(e)}unbindEvents(){this.element&&ix(this.element),this.unbindTrackEvents(),JO.off(QO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case eC.PLAYING:Sx()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(eC.PLAYING),this._interval&&(QL.clearTask(this._interval),this._interval=-1);break;case eC.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(eC.ENDED);break;case eC.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(eC.PAUSE);break;case eC.ERROR:if(this.element&&this.element.error){this.handlePaused(eC.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)),rx.uploadEvent({log:"stat-".concat(this.kind,"-").concat(NC.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),eO||Zk?this.emit($L.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case eC.LOADEDDATA:this.kind===eC.VIDEO&&this.emit($L.LOADED_DATA);break;case eC.LOADEDMETADATA:this.kind===eC.VIDEO&&this.emit($L.LOADED_META_DATA);break;case eC.LOADSTART:this.emit($L.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),rx.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),CP.addSuccessEvent({key:this.kind===eC.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),rx.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),CP.addFailedEvent({key:this.kind===eC.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit($L.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{SN(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)}),SN(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 nw(this,null,(function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===eC.UNMUTE?"info":"warn"]("track ".concat(t)),t){case eC.ENDED:this.handleStopped(eC.ENDED);break;case eC.MUTE:this.handlePaused(eC.MUTE);break;case eC.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(eC.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(ax,"PlayerEvent",$L),iw([nx({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],ax.prototype,"doReplayByRecreateMediaStream",1),iw([WL([],"PLAYING",{sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],ax.prototype,"handlePlaying",1),iw([WL("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],ax.prototype,"handlePaused",1),iw([WL([],"STOPPED",{sync:!0,success(e){this.emit($L.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],ax.prototype,"handleStopped",1);var sx="trtc_autoplay",lx="".concat(sx,"_mask"),cx="".concat(sx,"_wrapper"),dx="".concat(sx,"_header"),ux="".concat(sx,"_content"),hx="".concat(sx,"_action_wrapper"),px="".concat(sx,"_question"),mx="".concat(sx,"_collapse"),fx="".concat(sx,"_action_confirm"),_x="".concat(sx,"_detail"),gx="#2473E8",Ex="dialog",vx="".concat(Ex,"-show"),yx="".concat(Ex,"-1"),Tx="".concat(Ex,"-2"),Ix=!1,Ax=!1,Sx=()=>Ax,Rx="".concat(Lw,"/").concat(VD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),bx="<br><a href='".concat(Rx,"' target='_blank'>").concat(VD()?"其他方案?":"Any other solution?","</a>"),wx="".concat(VD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(bx):"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(bx)),Cx=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),VD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ix){let e=document.createElement("style");e.innerHTML=".".concat(lx,"{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(lx," div:not(.").concat(hx,"){display:block !important;}.").concat(cx,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(cx," a{color:").concat(gx,";}.").concat(dx,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(ux,"{margin:8px 0;}.").concat(hx,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(mx,"{margin-right:auto;cursor:pointer}.").concat(px,"{height:100%;line-height:16px;cursor:pointer;}.").concat(fx,"{margin-left:8px;color:#fff;background:").concat(gx,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(fx,":hover{opacity:0.9;}.").concat(mx,",.").concat(fx,",.").concat(ux,",.").concat(px,"{font-size:14px;}@media screen and (max-width:750px){.").concat(cx,"{width:80vw;}}"),document.head.appendChild(e),Ix=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(lx,"\"><div class='").concat(cx,"'><div class='").concat(dx,"'>").concat(location.host,"</div><div class='").concat(ux,"'>").concat(this.content,"</div><div class='").concat(_x,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(wx,"</div><div class='").concat(hx,"'></div></div></div>").trim();let t=document.createElement("button");t.className=fx,t.innerText=VD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=px,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=mx,r.innerText="".concat(VD()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let o=e.content.firstChild,n=o.querySelector(".".concat(hx));return n.appendChild(r),n.appendChild(i),n.appendChild(t),o}addDiaLog(){Sx()||(Ax=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(cx)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",eM.info("show autoplay dialog"),rx.uploadEvent({log:vx}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ax=!1),Dx=null}onConfirm(){eM.warn("confirm clicked, try resume stream"),JO.emit(QO.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||rx.uploadEvent({log:yx}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Rx,"_blank"),this._isQuestionClicked||rx.uploadEvent({log:Tx}),this._isQuestionClicked=!0}},Dx=null;function Nx(){Dx||(Dx=new Cx)}var kx,Ox=class e extends ax{constructor(e){super(e,eC.VIDEO),rw(this,"stat",{}),rw(this,"_calculateTimeout",-1),rw(this,"viewMirror",!1),rw(this,"objectFit","cover"),rw(this,"container"),rw(this,"canvas"),rw(this,"shouldRenderAlpha",!1),rw(this,"_preSize",{width:0,height:0}),rw(this,"posterImg"),rw(this,"_originContainerPosition"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,jD(e.viewMirror)||(this.viewMirror=e.viewMirror),jD(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(eC.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,ck&&(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,";").concat(this.shouldRenderAlpha?"":"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(eC.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(eC.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(eC.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===eC.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var t,i,r,o,n,a;if(2===this.mode)return;super.handleElementEvent(e);let s=e.type,l=this.isPictureInPicture()&&e.isTrusted&&EO;if(s===eC.PLAYING&&l&&(this._log.warn("user resume in pip"),this.emit($L.USER_RESUME_IN_PIP)),s===eC.PAUSE&&(l&&(this._log.warn("user pause in pip"),this.emit($L.USER_PAUSE_IN_PIP)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),SN(500).then((()=>{var e;null!=(e=this.container)&&e.isConnected&&(this._pausedRetryCount=KC,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))}))),this._pausedRetryCount>0&&!Sx()&&!this.isPausedByUserCall&&!l&&(this._log.info("[".concat(KC-this._pausedRetryCount+1,"/").concat(KC,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),sk&&!l&&(this._interval=QL.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&!this.isPausedByUserCall&&this.doResume()}),{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;s===eC.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):s===eC.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}s===eC.RESIZE&&(this._preSize.height!==(null==(t=this.element)?void 0:t.videoHeight)||this._preSize.width!==(null==(i=this.element)?void 0:i.videoWidth))&&(this._log.info("video size changed to ".concat(null==(r=this.element)?void 0:r.videoWidth,"x").concat(null==(o=this.element)?void 0:o.videoHeight)),this._preSize.height=(null==(n=this.element)?void 0:n.videoHeight)||0,this._preSize.width=(null==(a=this.element)?void 0:a.videoWidth)||0,this.emit($L.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),s===eC.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),ck&&hO&&fO<143&&this.isPlayCalled&&this.element&&this.track&&(this._log.warn("reset srcObject for android chrome after exit pip"),this.element.srcObject=new MediaStream([this.track]),this.element.play().catch((e=>{this._log.warn("play failed after reset srcObject",e)}))),this.emit($L.LEAVE_PICTURE_IN_PICTURE)),s===eC.ENTER_PICTURE_IN_PICTURE&&(this._log.warn("enter pip"),this.emit($L.ENTER_PICTURE_IN_PICTURE))}setCanvas(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;var i,r,o,n;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==(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){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((i=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),""===e?this.element.removeAttribute("poster"):this.element.poster=e,!t||!EO&&!pk))return i();if(""===e)return this.removePosterImg(),i();if(this.posterImg)return i();let r=document.createElement("img");r.src=e;let o=window.getComputedStyle(this.element).objectFit||this.objectFit;r.style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(o,";"),r.onload=()=>nw(this,null,(function*(){var e;try{r.decode&&(yield r.decode()),this.container&&"static"===window.getComputedStyle(this.container).position&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=r,null==(e=this.container)||e.appendChild(r),lk()&&RO<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(t){this._log.warn("decode poster image error",t)}return i()})),r.onerror=()=>(this._log.warn("load poster image error"),i())}))}removePosterImg(){this.posterImg&&(lk()&&RO<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!jD(this._originContainerPosition)&&"relative"===this.container.style.position&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!(null==(e=this.element)||!e.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return nw(this,null,(function*(){ow(e.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(hO&&fO>=128||t&&(pk||EO))&&(yield this.setPoster(this.getVideoFrame(),!0))}))}resume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return super.resume(e).then((()=>{var e;(this.posterImg||null!=(e=this.element)&&e.poster)&&this.setPoster("",!0)}))}doResume(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&hO&&fO>=128&&"video"===this.track.kind&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;this.isPictureInPicture()&&this.exitPictureInPicture().catch((e=>{})),this.isFullscreen()&&this.exitFullscreen().catch((e=>{})),super.stop(e),null==(t=this.canvas)||t.remove(),this.removePosterImg()}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($L.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(CL()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,o)=>{this.stat.width=o.width,this.stat.height=o.height,t&&(this.stat.fps=Math.round((o.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=o,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(Sw){this._log.warn("init stat failed",Sw)}}enterFullscreen(){return nw(this,null,(function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(CC){throw this._log.error("failed to enter fullscreen:",CC),CC}}))}exitFullscreen(){return nw(this,null,(function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(Sw){throw this._log.error("failed to exit fullscreen:",Sw),Sw}}))}isFullscreen(){let e=this.elementToRender;return!!e&&(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e}toggleFullscreen(){return nw(this,null,(function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()}))}enterPictureInPicture(){return nw(this,null,(function*(){var e;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&1!==this.mode)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let i=yield t.requestPictureInPicture();return this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),null==(e=this.container)||e.appendChild(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(CC){throw this._log.error("failed to enter pip:",CC.name,CC.message),CC}}))}exitPictureInPicture(){return nw(this,null,(function*(){var e,t;try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&(null==(e=this.element)||e.remove(),this._pausedRetryCount=KC,null==(t=this.container)||t.appendChild(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(cM){throw this._log.error("failed to exit pip:",cM),cM}}))}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&"picture-in-picture"===e.webkitPresentationMode}togglePictureInPicture(){return nw(this,null,(function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()}))}};function Mx(e,t){return nw(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),eM.info("worklet addModule success")}catch(Sw){throw eM.info("worklet addModule catch error. ".concat(Sw.message)),Sw}}))}"undefined"!=typeof AudioContext?kx=AudioContext:"undefined"!=typeof webkitAudioContext?kx=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(kx=mozAudioContext);var Px,Lx=1500,xx=-1,Ux=0,Vx=-1,Fx=!1,Bx=0,Hx=-1,Wx=-1;!function e(){try{if(Px)return;(Px=new kx({sampleRate:48e3})).onstatechange=()=>{eM.info("context state: ".concat(Px.state).concat("running"!==Px.state?" visibilityState: ".concat(document.visibilityState):"")),Gx()},clearTimeout(xx)}catch(UH){eM.error("initAudioContext failed: ".concat(UH," typeof AudioContextClass: ").concat(typeof kx)),xx=setTimeout(e,1e3)}}();var Gx=()=>{"suspended"===Px.state?(Ux=oN(),-1===Vx&&(Vx=setTimeout((()=>{"suspended"===Px.state&&(Fx=!0,JO.emit("155",{isSuspended:!0}))}),Lx)),Kx(),document.addEventListener("click",Gx)):"interrupted"===Px.state?Kx():(Ux&&(CP.addNumber({key:507800,value:oN()-Ux,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Ux=0),-1!==Vx&&(clearTimeout(Vx),Vx=-1,Fx&&(Fx=!1,JO.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",Gx),document.removeEventListener("click",Gx))},jx=0,zx=-1;function Kx(){return new Promise(((e,t)=>{if("running"===Px.state)return e();Date.now()-jx<1e3?(clearTimeout(zx),zx=setTimeout((()=>{jx=Date.now(),Px.resume().then(e,t)}),1e3)):(clearTimeout(zx),jx=Date.now(),Px.resume().then(e,t))})).catch((e=>{eM.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",Gx)}))}document.addEventListener("click",Gx);var qx=e=>Px,Yx=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(CC){eM.error(CC)}}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(),CP.addSuccessEvent({key:502701})}catch(cM){eM.error(cM),CP.addFailedEvent({key:502701,error:cM})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),CP.addSuccessEvent({key:502702})}catch(Sw){eM.error(Sw),CP.addFailedEvent({key:502702,error:Sw})}}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}},Jx=class extends Yx{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,i=0,r="M".concat(t,",").concat(i);for(let o=0;o<e.length;o++)i=e[o]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},Xx=class{constructor(){rw(this,"source",new Yx),rw(this,"gain",new Yx),rw(this,"destination",new Yx)}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(qx().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=eU(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}},Qx=class extends Xx{constructor(e){super(),this.context=e,rw(this,"aec",new Yx("aec")),rw(this,"mixNode",new Yx("mixNode")),rw(this,"silentNode",new Yx("silentNode")),rw(this,"denoiser",new Yx("denoiser")),rw(this,"voiceChanger",new Yx("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()}},$x=class{constructor(){rw(this,"audioContext",qx()),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]}},Zx=new WeakMap;function eU(e){try{let t=Zx.get(e);if(t)return t;let i=qx();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return Zx.set(e,t),t}catch(lM){if(!(pk&&lM instanceof Error&&"NotSupportedError"===lM.name))throw lM;eM.warn(lM)}}var tU=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,JO.on(QO.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=Mx(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(lM){this._log.error("volumeMeter init audio worklet error: ".concat(lM)),rx.logFailedEvent({userId:this._log.userId,eventType:NC.LOAD_WORKLET,error:lM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qx().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(lM){this._log.error("volumeMeter init script processor error: ".concat(lM))}}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,JO.off(QO.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})}};rw(tU,"lastMessageTime",0),rw(tU,"audioContext",qx()),rw(tU,"workletReady");var iU=tU,rU=class extends Yx{constructor(e){super(),rw(this,"_volumeMeter"),this._volumeMeter=new iU(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return nw(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()}}},oU=iU,nU=tw(aw(),1),aU=e=>t=>t.deviceId===e,sU=class{constructor(e,t){rw(this,"kind"),rw(this,"type"),rw(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&&dU(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(aU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");eM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(aU(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");eM.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},lU=class extends nU.EventEmitter{constructor(){super(),rw(this,"audioInputs",new sU(eC.AUDIO,"Input")),rw(this,"videoInputs",new sU(eC.VIDEO,"Input")),rw(this,"audioOutputs",new sU(eC.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||QL.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){uU().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return nw(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield uU(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=qx())?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)))))}},cU=ww||bw?null:new lU;function dU(e){return e.deviceId===e.groupId&&""===e.groupId}function uU(){return nw(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(xP()||!PP())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{dU(e)&&(e.kind===eC.AUDIO_INPUT?i.audio=!0:e.kind===eC.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&&Kx()}catch(cM){eM.debug("capture before getDevices failed: ",cM)}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&&_U.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function hU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return cU.update(e?1:0).then((e=>e.audioInputs.devices))}function pU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return cU.update(e?2:0).then((e=>e.videoInputs.devices))}var mU=!1;function fU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nw(this,null,(function*(){return(sk||EO)&&(e=!1),cU.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var _U=new Set;function gU(e,t){return nw(this,null,(function*(){let i=(yield hU()).find((e=>e.deviceId===qC));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var EU,vU=class extends Xx{constructor(e){super(),this.log=e,rw(this,"volumeMeter"),rw(this,"volumeMeterAfter3A"),rw(this,"volumeDestination"),rw(this,"analyser",new Jx),this.volumeMeter=new rU({log:this.log}),this.volumeMeterAfter3A=new rU({log:this.log}),this.volumeDestination=new Yx,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},yU=class e extends ax{constructor(e){super(e,eC.AUDIO),rw(this,"_outputDeviceId"),rw(this,"_floatVolume",1),rw(this,"_destination"),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 vU(this._log)}setTrack(e){}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"===IO||"15.3"===IO||"15.4"===IO)&&this.muted)return void this._log.info("audioElement is muted.");let t=EU||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,this.setVolume(KD(e)?e/100:this._floatVolume),t===EU&&(EU=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit($L.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return nw(this,null,(function*(){if(this.track||this.url){try{!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(qx().createAnalyser()),function(){nw(this,null,(function*(){try{mU||(mU=!0,eM.info("speakers:".concat((yield fU()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(e){}}))}()}catch(CC){throw this._log.warn("audio play error: ".concat(CC)),(wk||Ok)&&SO(IO,"18.7",!0)&&this.bindAutoPlayEvent(),CC}return ow(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._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return nw(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 yU{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit($L.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},IU=class extends yU{constructor(e){super(e),rw(this,"_sourceElement"),rw(this,"_output",new Yx),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(qx().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($L.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){var t;let i=e<=1&&!lk();if(this._floatVolume!==e||!(i&&(null==(t=this.element)?void 0:t.volume)===e||!i&&this.pipeline.volume===e))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(i)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(lk()){if(!this.enableVolumeControlInIOS)return;!function(){if(!sk||-1!==Wx)return;let e=()=>{oN()-Bx<500||(Px&&"running"===Px.state&&Px.currentTime===Hx&&(eM.warn("context is fake running, auto resume"),Px.suspend().catch((e=>{eM.warn("context suspend failed: ".concat(e))}))),Hx=Px.currentTime,Bx=oN())};Wx=setInterval((()=>{e()}),2e3),document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&e()}))}()}if(pk&&!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._destination||(this._destination=qx().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),ix(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch((e=>{this.emit($L.AUTOPLAY_FAILED,e)})))}}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&vO&&(EU=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},AU=class extends zL{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:o,PlayerClass:n=(1===r?IU:Ox)}=e;var a;super(),rw(this,"id",tM()),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=r,this._log=eM.createLogger({parent:null==o?void 0:o.getLogger(),id:"".concat(this.kind[0],"t"),userId:null==(a=o||this.room)?void 0:a.userId,remoteUserId:this instanceof sB?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof sB}),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($L.PLAYER_STATE_CHANGED,(e=>{if(JO.emit(QO.PLAYER_STATE_CHANGED,Qb({track:this},e)),this.emit("player-state-changed",e),"PLAYING"===e.state&&this.room){let e=!0;for(let{remoteAudioTrack:t,remoteVideoTrack:i,remoteAuxiliaryTrack:r}of[...this.room.remotePublishedUserMap.values()])if(t.isAvailable&&!t.player.isPlaying||i.isAvailable&&!i.player.isPlaying||r.isAvailable&&!r.player.isPlaying){e=!1;break}e&&Sx()&&Dx&&Dx.deleteDialog()}})),this.kind===eC.VIDEO&&(this.player.on($L.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent($L.LOADED_DATA),JO.emit(QO.VIDEO_LOADED_DATA,{track:this})})),this.player.on($L.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent($L.LOADED_META_DATA)})),this.player.on($L.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))})),this.player.on($L.RESIZE,(e=>{this.emitFirstVideoFrameEvent($L.RESIZE),this.emit("video-size-changed",Qb({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($L.ERROR,this.onPlayerError.bind(this)),this.player.on($L.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||eM}get kind(){return 1===this.mediaType?eC.AUDIO:eC.VIDEO}get isAudio(){return this.kind===eC.AUDIO}get strMediaType(){return 4===this.mediaType?eC.VIDEO:2===this.mediaType?eC.SCREEN:eC.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 nw(this,null,(function*(){let i=JD(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!jD(t.muted)&&this.setPlayerMute(t.muted),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof Ox&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),JD(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!jD(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===eC.VIDEO)&&this.setPlayerMute(!0),t&&!jD(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof Ox&&(this.player.setObjectFit(this.objectFit),t&&!jD(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof Ox&&this.player.setContainer(i)),JO.emit(QO.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),JD(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(pM){throw this.handleAutoPlayFailed(pM),pM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==eC.VIDEO||jD(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(qD(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 nw(this,null,(function*(){if(!this._outputTrack||this.kind===eC.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,o]of e.entries()){let e=this.subVideoPlayerMap.get(o);e?t&&(jD(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new Ox({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(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.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(KN(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return nw(this,null,(function*(){var e;this.isPlayCalled&&(yield null==(e=this.player)?void 0:e.resume())}))}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),JO.emit(e?QO.TRACK_MUTED:QO.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){tx(e,e).add(eC.MUTE,this.onTrackMuted).add(eC.UNMUTE,this.onTrackUnmuted).add(eC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===eC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ix(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){var t,i;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){if(KN(this)&&this.isAudio&&null!=(t=this.user)&&t.muteState.hasAudio&&null!=(i=this.user)&&i.muteState.audioMuted)return;return this.player.stop(KN(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){return nw(this,null,(function*(){var t;this.log.warn("handleAutoPlayFailed",e);let i=()=>{this.resume().then((()=>{document.removeEventListener("click",i,!0)}))};if(this.room&&this.room.enableAutoPlayDialog){if((wk||Ok)&&(yield SN(100),null!=(t=this.player)&&t.isPlaying))return;Nx()}else document.addEventListener("click",i,!0);JO.once(QO.LOCAL_TRACK_CAPTURE_SUCCESS,(e=>{let{track:t}=e;"audio"===t.kind&&Sx()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()})),this.emit("error",e)}))}getVideoFrame(){return this.player instanceof Ox?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let o=null==(t=this.mediaTrack)?void 0:t.getSettings(),n=(null==o?void 0:o.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,a=(null==o?void 0:o.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;e===$L.RESIZE&&!n&&!a||e===$L.LOADED_META_DATA&&!n&&!a||(e===$L.LOADED_DATA&&!n&&!a&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,DN(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"))}};iw([WL([],zL.INIT,{sync:!0})],AU.prototype,"_toInitState",1);var SU=Object.prototype.hasOwnProperty;var RU=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(FD(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(SU.call(e,t))return!1;return!0}return!1},bU=YN({retryFunction:function(e){return nw(this,null,(function*(){let t=function(e){return{audio:CU(e),video:DU(e)}}(e);eM.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],o=["label","deviceId","groupId"];if(t.audio&&(i=yield hU(),eM.info("microphones: ".concat(gN(i.map((e=>$b(Qb({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:o})))),t.video&&(r=yield pU(),eM.info("cameras: ".concat(gN(r,{keysToInclude:o}))),!qD(t.video)&&"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,eM.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let i=yield navigator.mediaDevices.getUserMedia(t);return mL&&i.getTracks().forEach((t=>{var i;let r=t.getCapabilities();eM.info("".concat(t.kind," capabilities: ").concat(gN(r,{keysToInclude:eD}))),!jD(e.echoCancellation)&&-1===(null==(i=r.echoCancellation)?void 0:i.indexOf(e.echoCancellation))&&eM.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(r.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))})),t.audio&&Kx(),i}catch(pM){let{message:o}=pM;throw"NotFoundError"===pM.name&&(e.video&&r&&0===r.length&&(o=fP({key:uP.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(o=fP({key:uP.MICROPHONE_NOT_FOUND}))),new mw({code:hw.INITIALIZE_FAILED,name:pM.name,message:o,constraint:pM.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,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,(!EO||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),i()):r(t),o[0].microphoneId&&wU(o[0].microphoneId,!1),o[0].cameraId&&wU(o[0].cameraId,!0)},onRetrying:e=>{eM.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{rx.logFailedEvent({eventType:NC.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{rx.logSuccessEvent({eventType:NC.GET_USER_MEDIA_RETRY}),rx.uploadEvent({log:"stat-".concat(NC.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function wU(e,t){return nw(this,null,(function*(){let i=(t?yield pU():yield hU()).find((t=>t.deviceId===e));i&&GD(i.getCapabilities)&&eM.warn(gN(i.getCapabilities(),{keysToInclude:eD}))}))}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!RU(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(KD(e.channelCount)&&(t.channelCount=e.channelCount),(qD(e.echoCancellation)||"remote-only"===e.echoCancellation||"all"===e.echoCancellation)&&(t.echoCancellation=e.echoCancellation),qD(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),qD(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!RU(t)||t)}function DU(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&&!RU(i)?i:(e.width&&(i.width={ideal:e.width},t&&!pk&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!pk&&(i.height.max=e.height)),pk&&jk&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!RU(i)||i)}var NU=bU;function kU(e){return OU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return nw(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function OU(e){return function(t,i,r){return r.value=e(r.value,i),r}}var MU=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&eM.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{eM.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),PU=0,LU=class{constructor(e){rw(this,"log"),rw(this,"isRunning",!1),rw(this,"queue",[]);let t="fq".concat(++PU);e&&(t+="|".concat(e)),this.log=eM.createLogger({id:t})}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 o=Qb({},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==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(o.resolve,o.reject):this.queue.push(o),this.log.debug("push ".concat(this.length),e.funcName,e.args),this.isRunning||this.callNext(),n}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length),null==e?void 0:e.funcName,null==e?void 0:e.args),e}callNext(){if(this.isRunning||0===this.length)return;let{fn:e,args:t,context:i,resolve:r,reject:o,funcName:n}=this.queue[0];this.log.debug("callNext",this.length,n,t),this.isRunning=!0,e.apply(i,t).then(r,o).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},xU=new WeakMap,UU=new WeakMap;function VU(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let o=r.value;return r.value=function(){let t=xU.get(this)||new LU;for(var r=arguments.length,n=new Array(r),a=0;a<r;a++)n[a]=arguments[a];return xU.set(this,t),t.push({fn:o,args:n,context:this,funcName:i},e)},r}}function FU(e,t){return function(i,r,o){let n=o.value,a=t=>e(...t);return o.value=function(){for(var e=arguments.length,i=new Array(e),o=0;o<e;o++)i[o]=arguments[o];let s=UU.get(this)||new Map,l=s.get(a(i))||new LU(null==t?void 0:t(...i));return s.set(a(i),l),UU.set(this,s),l.push({fn:n,args:i,context:this,funcName:r})},o}}function BU(e,t){return OU(((i,r)=>function(){let r=e;try{for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let e=i.apply(this,n),s=oN();return $D(e)?e.then((e=>(t?CP.addSuccessEvent({key:r,cost:oN()-s}):CP.addSuccessEvent({key:r}),e))).catch((e=>{throw CP.addFailedEvent({key:r,error:e}),e})):(CP.addSuccessEvent({key:r}),e)}catch(Rw){throw CP.addFailedEvent({key:r,error:Rw}),Rw}}))}var HU={};function WU(){}ew(HU,{Events:()=>rV,Inspect:()=>YU,LastSink:()=>JU,Sink:()=>XU,Subscribe:()=>QU,TimeoutError:()=>oV,audit:()=>uF,bindCallback:()=>BV,bindNodeCallback:()=>HV,buffer:()=>gV,bufferCount:()=>_V,bufferTime:()=>YF,call:()=>GU,catchError:()=>XF,combineLatest:()=>hV,concat:()=>cV,concatMap:()=>xF,concatMapTo:()=>UF,count:()=>qV,create:()=>ZU,debounce:()=>mF,debounceTime:()=>fF,defer:()=>yV,delay:()=>JF,deliver:()=>eV,dispose:()=>zU,elementAt:()=>_F,empty:()=>jV,every:()=>TF,exhaustMap:()=>jF,exhaustMapTo:()=>zF,expand:()=>$F,filter:()=>QV,find:()=>gF,findIndex:()=>EF,first:()=>vF,fromAnimationFrame:()=>VV,fromArray:()=>wV,fromEvent:()=>OV,fromEventPattern:()=>kV,fromFetch:()=>PV,fromIterable:()=>LV,fromPromise:()=>MV,fromReadableStream:()=>UV,fromReader:()=>xV,groupBy:()=>KF,identity:()=>jU,ignoreElements:()=>$V,iif:()=>uV,inspect:()=>KU,interval:()=>CV,last:()=>yF,map:()=>RF,mapTo:()=>bF,max:()=>YV,merge:()=>sV,mergeMap:()=>BF,mergeMapTo:()=>HF,min:()=>JV,never:()=>WV,nothing:()=>WU,of:()=>bV,pairwise:()=>AF,pipe:()=>$U,race:()=>lV,range:()=>FV,reduce:()=>KV,retry:()=>oB,scan:()=>IF,setAsapScheduler:()=>SV,share:()=>aV,shareReplay:()=>dV,skip:()=>rF,skipUntil:()=>oF,skipWhile:()=>nF,startWith:()=>mV,subject:()=>vV,subscribe:()=>tB,sum:()=>XV,switchMap:()=>kF,switchMapTo:()=>MF,take:()=>ZV,takeLast:()=>iF,takeUntil:()=>eF,takeWhile:()=>tF,tap:()=>iB,throttle:()=>cF,throwError:()=>GV,timeInterval:()=>qF,timeout:()=>rB,timer:()=>DV,toPromise:()=>ZF,toReadableStream:()=>eB,withLatestFrom:()=>fV,zip:()=>pV});var GU=e=>e(),jU=e=>e;function zU(){this.dispose()}var KU=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,qU=1,YU=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new iV(e,this,this.streamId++);return rV.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},JU=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=WU,this.error=WU,this.next=WU,this.dispose=WU,this.subscribe=WU,this.doDefer()}subscribe(e){return e instanceof YU?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(GU),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}},XU=class extends JU{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)}},QU=class extends JU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:WU,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:WU;if(super(),this._next=t,this._error=i,this._complete=r,this.then=WU,e instanceof YU){let o={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{rV.defer(o,0)})),rV.create(o),rV.pipe(o),this.sourceId=o.id,this.subscribe(e),rV.subscribe({id:o.id,end:!0}),t==WU?this._next=e=>rV.next(o,0,e):this.next=e=>{rV.next(o,0,e),t(e)},r==WU?this._complete=()=>rV.complete(o,0):this.complete=()=>{this.dispose(),rV.complete(o,0),r()},i==WU?this._error=e=>rV.complete(o,0,e):this.error=e=>{this.dispose(),rV.complete(o,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 $U(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 ZU(e,t,i){if(KU()){let r=Object.defineProperties(Object.setPrototypeOf(e,YU.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}});rV.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof YU&&rV.addSource(r,t)}return r}return e}function eV(e,t){return function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return i=>{if(i instanceof YU){let o=ZU((t=>{let n=new e(t,...r);n.sourceId=o.id,n.subscribe(i)}),t,arguments);return o.source=i,rV.pipe(o),o}return t=>i(new e(t,...r))}}}function tV(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var iV=class extends XU{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{rV.defer(this.source,this.id)}))}next(e){rV.next(this.source,this.id,e),this.sink.next(e)}complete(){rV.complete(this.source,this.id),this.sink.complete()}error(e){rV.complete(this.source,this.id,e),this.sink.error(e)}},rV={addSource(e,t){tV("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){tV("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;tV("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){tV("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){tV("defer",{id:e.id,streamId:t})},pipe(e){tV("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){tV("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=qU++),tV("create",{name:e.toString(),id:e.id})}},oV=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},nV=class extends JU{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 aV(){return e=>{let t=new nV(e);if(e instanceof YU){let i=ZU((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,rV.pipe(i),i}return ZU(t.add.bind(t),"share",arguments)}}function sV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=new XU(e),r=t.length;i.complete=()=>{0==--r&&e.complete()},t.forEach(i.bindSubscribe)}),"merge",arguments)}function lV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=new Map;t.forEach((t=>{let r=new XU(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 cV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=0,r=t.length,o=new XU(e);o.complete=()=>{i<r&&!o.disposed?(o.doDefer(),o.subscribe(t[i++])):e.complete()},o.complete()}),"concat",arguments)}function dV(e){return t=>{let i=new nV(t),r=[];return i.next=function(t){r.push(t),r.length>e&&r.shift(),this.sinks.forEach((e=>e.next(t)))},ZU((e=>{e.defer((()=>i.remove(e))),r.forEach((t=>e.next(t))),i.add(e)}),"shareReplay",arguments)}}function uV(e,t,i){return ZU((r=>e()?t(r):i(r)),"iif",arguments)}function hV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=t.length,r=i,o=i,n=new Array(i),a=()=>{0==--o&&e.complete()};t.forEach(((t,i)=>{let o=new XU(e);o.next=t=>{r--,o.next=t=>{n[i]=t,0===r&&e.next(n)},o.next(t)},o.complete=a,o.subscribe(t)}))}),"combineLatest",arguments)}function pV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU((e=>{let i=t.length,r=i,o=new Array(i),n=()=>{0==--r&&e.complete()};t.forEach(((t,i)=>{let r=new XU(e),a=[];o[i]=a,r.next=t=>{a.push(t),o.every((e=>e.length))&&e.next(o.map((e=>e.shift())))},r.complete=n,r.subscribe(t)}))}),"zip",arguments)}function mV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>ZU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<o&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}var fV=eV(class extends XU{constructor(e){super(e);let t=new XU(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];t.next=e=>this.buffer=e,t.complete=WU,t.subscribe(hV(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),_V=eV(class extends XU{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"),gV=eV(class extends XU{constructor(e,t){super(e),this.buffer=[];let i=new XU(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=WU,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),EV=function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){e.done?o(e.value):function(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(a,s)}l((r=r.apply(e,t||[])).next())}))};function vV(e){let t=arguments,i=aV()(ZU((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=WU,i.complete=WU,i.error=WU,i}function yV(e){return ZU((t=>t.subscribe(e())),"defer",arguments)}var TV={promise:e=>{Promise.resolve().then(e)},setImmediate:"undefined"!=typeof setImmediate?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},IV="undefined"!=typeof Promise?TV.promise:TV.setImmediate?TV.setImmediate:TV.setTimeout,AV=e=>t=>{IV((()=>e(t)))},SV=e=>{"function"==typeof e?IV=e:TV[e]&&(IV=TV[e])},RV=e=>AV((t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()}));function bV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZU(RV(t),"of",arguments)}function wV(e){return ZU(RV(e),"fromArray",arguments)}function CV(e){return ZU((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function DV(e,t){return ZU((i=>{let r=0,o=setTimeout((()=>{if(i.removeDefer(n),i.next(r++),t){let e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),n=()=>clearTimeout(o);i.defer(n)}),"timer",arguments)}function NV(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function kV(e,t){return ZU(NV(e,t),"fromEventPattern",arguments)}function OV(e,t){if("on"in e&&"off"in e)return ZU(NV((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return ZU(NV((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return ZU(NV((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function MV(e){return ZU((t=>{e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function PV(e,t){return ZU(yV((()=>MV(fetch(e,t)))),"fromFetch",arguments)}function LV(e){return ZU(AV((t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(Sw){t.error(Sw)}})),"fromIterable",arguments)}function xV(e){let t=i=>EV(this,void 0,void 0,(function*(){if(i.disposed)return;let{done:r,value:o}=yield e.read();r?i.complete():(i.next(o),t(i))}));return ZU((e=>{t(e)}),"fromReader",arguments)}function UV(e){return ZU((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 VV(){return ZU((e=>{let t=requestAnimationFrame((function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))}));e.defer((()=>cancelAnimationFrame(t)))}),"fromAnimationFrame",arguments)}function FV(e,t){return ZU((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;for(;r<o&&!i.disposed;)i.next(r++);return i.complete(),"range"}),"range",arguments)}function BV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return ZU((i=>{let o=r.concat((e=>(i.next(e),i.complete())));e.apply(t,o)}),"bindCallback",arguments)}function HV(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return ZU((i=>{let o=r.concat(((e,t)=>e?i.error(e):(i.next(t),i.complete())));e.apply(t,o)}),"bindNodeCallback",arguments)}function WV(){return ZU((()=>{}),"never",arguments)}function GV(e){return ZU((t=>t.error(e)),"throwError",arguments)}function jV(){return ZU((e=>e.complete()),"empty",arguments)}var zV=class extends XU{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)}},KV=eV(zV,"reduce"),qV=e=>eV(zV,"count")(((t,i)=>e(i)?t+1:t),0),YV=()=>eV(zV,"max")(Math.max),JV=()=>eV(zV,"min")(Math.min),XV=()=>eV(zV,"sum")(((e,t)=>e+t),0),QV=eV(class extends XU{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"),$V=eV(class extends XU{next(e){}},"ignoreElements"),ZV=eV(class extends XU{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&(this.doDefer(),this.complete())}},"take"),eF=eV(class extends XU{constructor(e,t){super(e);let i=new XU(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=zU,i.subscribe(t)}},"takeUntil"),tF=eV(class extends XU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),iF=e=>KV(((t,i)=>(t.push(i),t.length>e&&t.shift(),t)),[]),rF=eV(class extends XU{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},"skip"),oF=eV(class extends XU{constructor(e,t){super(e),e.next=WU;let i=new XU(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=zU,i.subscribe(t)}},"skipUntil"),nF=eV(class extends XU{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),aF={leading:!0,trailing:!1},sF=class extends XU{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)}},lF=class extends XU{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:aF;super(e),this.durationSelector=t,this.config=i,this._throttle=new sF(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=WU,this._throttle.complete(),super.complete()}},cF=eV(lF,"throttle"),dF={leading:!1,trailing:!0},uF=e=>eV(lF,"audit")(e,dF),hF=class extends XU{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},pF=class extends XU{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new hF(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()}},mF=eV(pF,"debounce"),fF=e=>eV(pF,"debounceTime")((t=>DV(e))),_F=eV(class extends XU{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"),gF=e=>t=>ZV(1)(nF((t=>!e(t)))(t)),EF=eV(class extends XU{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"),vF=eV(class extends XU{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"),yF=eV(class extends XU{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"),TF=eV(class extends XU{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"),IF=eV(class extends XU{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"),AF=eV(class extends XU{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),SF=class extends XU{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},RF=eV(SF,"map"),bF=e=>eV(SF,"mapTo")((t=>e)),wF=class extends XU{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()}},CF=class e extends XU{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()}},DF=class extends wF{},NF=class extends CF{next(e){this.subInner(e,DF),this.next=e=>{this.currentSink.dispose(),this.subInner(e,DF)}}},kF=eV(NF,"switchMap");function OF(e){return(t,i)=>e((()=>t),i)}var MF=OF(eV(NF,"switchMapTo")),PF=class extends wF{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},LF=class extends CF{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(),PF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},xF=eV(LF,"concatMap"),UF=OF(eV(LF,"concatMapTo")),VF=class extends wF{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},FF=class extends CF{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,VF),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},BF=eV(FF,"mergeMap"),HF=OF(eV(FF,"mergeMapTo")),WF=class extends wF{dispose(){this.context.resetNext(),super.dispose()}},GF=class extends CF{next(e){this.next=WU,this.subInner(e,WF)}},jF=eV(GF,"exhaustMap"),zF=OF(eV(GF,"exhaustMapTo")),KF=eV(class extends XU{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=vV(),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"),qF=eV(class extends XU{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"),YF=eV(class extends XU{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"),JF=eV(class extends XU{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"),XF=eV(class extends XU{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),QF=class extends wF{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},$F=eV(class extends CF{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 QF(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"),ZF=()=>e=>new Promise(((t,i)=>{let r;new QU(e,(e=>r=e),i,(()=>t(r)))})),eB=()=>e=>{let t;return new ReadableStream({start(i){t=new QU(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},tB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:WU,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WU,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:WU;return r=>new QU(r,e,t,i)},iB=eV(class extends XU{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"),rB=eV(class extends XU{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new oV(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),oB=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return t=>{if(t instanceof YU){let i=ZU((r=>{let o=e,n=new XU(r);n.error=e=>{o-- >0?n.subscribe(t):r.error(e)},n.sourceId=i.id,n.subscribe(t)}),"retry",[e]);return i.source=t,rV.pipe(i),i}return i=>{let r=e,o=new XU(i);o.error=e=>{r-- >0?t(o):i.error(e)},t(o)}}},nB=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(nB||{}),aB=class e extends AU{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.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(eC.MUTE,this.onTrackMuted),e.addEventListener(eC.UNMUTE,this.onTrackUnmuted),e.addEventListener(eC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===eC.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(eC.MUTE,this.onTrackMuted),e.removeEventListener(eC.UNMUTE,this.onTrackUnmuted),e.removeEventListener(eC.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(this,null,(function*(){var i;let r=this.sourceTrack;try{let r,o=oN();JO.emit(QO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(t||null==(i=this.sourceTrack)||i.stop(),r=yield NU(e));let n=r.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),JO.emit(QO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:oN()-o}),r}catch(Rw){throw JO.emit(QO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Rw}),this.log.error("getUserMedia error observed ".concat(Rw)),Rw}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=cN((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 nw(this,null,(function*(){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.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)}))}_checkPublishFlag(e){return new Promise(((t,i)=>nw(this,null,(function*(){var r,o,n,a;let s=()=>i(new mw({code:hw.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===zL.INIT||"ready"===this.state)&&s(),$U(OV(e,"local-publish-flag-changed"),QV((()=>this.hasFlag)),eF(sV(OV(this,zL.INIT),OV(this,"ready"))),tB(t,i,s))),((null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.uplinkNetworkQuality)||0)>3)return t();let l=e.heartbeatCount,c=(null==(a=null==(n=this.mediaTrack)?void 0:n.stats)?void 0:a.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout((()=>nw(this,null,(function*(){var r,o,n,a,s,d,u;if(((null==(o=null==(r=this.room)?void 0:r.networkQuality)?void 0:o.uplinkNetworkQuality)||0)>3||e.heartbeatCount-l<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(null!=(n=this.mediaTrack)&&n.stats){let e=this.mediaTrack.stats.totalFrames||0;e-c==0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",e)}let e=this.kind===eC.AUDIO,r=this.stat.bytesSent>0;if(CP[r?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),!e){let e={H264:513704,H265:513705,VP8:513706}[(null==(s=null==(a=this.room)?void 0:a.videoCodec)?void 0:s.toUpperCase())||"H264"];e&&CP[r?"addSuccessEvent":"addFailedEvent"]({key:e})}if(!r){if(CP.addEnum({key:e?503701:513703,value:GO()}),rx.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(FO()||zO()),userId:this.userId}),this.log.warn(e?"encode failed":"".concat(null==(u=null==(d=this.room)?void 0:d.videoCodec)?void 0:u.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield SN(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),i(new mw({message:"".concat(this.strMediaType," encode failed"),code:e?hw.AUDIO_ENCODE_FAILED:hw.VIDEO_ENCODE_FAILED}))}}}))),1e4)}))))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),JO.emit(QO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return nw(this,null,(function*(){if(this.sourceTrack&&pL){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:i}=this.sourceTrack;(yield function(e){return nw(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:o,kind:n}=e;return function*(){return t===i&&(n!==eC.AUDIO||t!==qC||(yield gU(r,o)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),uU().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===eC.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(eC.AUDIO_INPUT);return!!_U.has(i)}(this.sourceTrack)||this.kind===eC.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(eC.VIDEO_INPUT);return!!_U.has(i)}(this.sourceTrack)||this._isRecapturing||e&&jk&&EO)}onTrackMuted(){if(super.onTrackMuted(),MU(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ZC)return void setTimeout((()=>this.onTrackMuted()),ZC);this._onMuteTimeoutId=setTimeout((()=>nw(this,null,(function*(){var e;if(null!=(e=this.sourceTrack)&&e.muted){if((sk||ck)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return nw(this,null,(function*(){if(ow(e.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&0===this.recaptureMode){if(Date.now()-this._lastRecaptureTime<ZC)return void setTimeout((()=>this.onTrackEnded()),ZC);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(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 o={useExactDeviceId:!0};if("user"===e||"environment"===e)o.facingMode=e;else{let t;("audio"===this.kind?yield hU():yield pU()).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}),JO.emit(QO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),JO.emit(QO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})})).finally((()=>{t&&(null==r||r.stop())}))}))}getRecoverCaptureDeviceId(){return nw(this,null,(function*(){let e=this instanceof fB;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(lB.get(t)||0)+1;if(lB.set(t,i),i>=3&&this.enableAutoSwitchWhenRecapturing){let r=e?(yield pU()).find((e=>!lB.has(e.deviceId))):(yield hU()).find((e=>!lB.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)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};iw([WL(zL.INIT,"ready",{ignoreError:!0,sync:!0})],aB.prototype,"setStateToReady",1),iw([VU()],aB.prototype,"capture",1),iw([WL("ready","publish",{ignoreError:!0,success(){JO.emit(QO.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var t;null==(t=this.room)||t.localTracks.delete(this);let i="error",r=e instanceof mw?e:e.cause instanceof mw?e.cause:e,o=!1;r instanceof mw&&(r.message.includes("timeout")?i="timeout":r.code===hw.API_CALL_ABORTED&&(o=!0,i="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:r}),this.log[o?"info":"error"]("publish failed",r)}}),BU(521714,!1)],aB.prototype,"publish",1),iw([OU((e=>function(){return nw(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)}))})),WL([],"ready",{sync:!0})],aB.prototype,"unpublish",1);var sB=aB,lB=new Map;JO.on(QO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&lB.delete(e.track.deviceId)}));var cB=class e extends sB{constructor(e){super(1,TU),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 Yx),rw(this,"_output",new Yx),rw(this,"codecPipeline",[]),rw(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),rw(this,"mixedAudioReferenceMap",new Map),rw(this,"isAudioContextLongSuspended",!1),rw(this,"after3aSilenceStartTime",0),this.manager=e,this.pipeline=new Qx(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),JO.on(QO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return oU.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.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){jD(e)||(0!==e||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=oN())}setInputMediaStreamTrack(t){return nw(this,null,(function*(){let i=this.trackSettings||{};CP.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),CP.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),CP.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:o}))),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(t),yield ow(e.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)}))}capture(t){return nw(this,arguments,(function(t){var i=this;let{deviceId:r,customSource:o,useExactDeviceId:n=!0,retryWhenExactFailed:a}=t,s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){let t=yield ow(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:n,retryWhenExactFailed:a,customSource:o},s);return Kx(),t}()}))}switchDevice(e){return nw(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource){if(e!==qC)return;if(yield gU(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}),JO.emit(QO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(CC){throw this.log.error("switch microphone failed ".concat(CC)),this.deviceId&&this.recapture(this.deviceId),CC}}}))}listenDeviceChange(){cU&&!cU.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&cU.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return nw(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(nB[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:6,streamType:1});let e=yield hU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&cU.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){1===this.recaptureMode&&e.deviceId!==this.deviceId||(cU.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return nw(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:o}=e;return function*(){let e=t.sourceTrack||t.mediaTrack;if(!e)return;let n=e.getConstraints(),a=!1;!jD(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,n.echoCancellation=i,a=!0),!jD(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,n.noiseSuppression=r,a=!0),!jD(o)&&o!==t.profile.autoGainControl&&(t.profile.autoGainControl=o,n.autoGainControl=o,a=!0),a&&(pk||EO?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&&CP.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),sk&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(qx().createGain()),this._output.setNode(qx().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!EO&&!sk)return this.update3A({echoCancellation:e})}addDenoiser(e){var t;fO<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(CP.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=eU(e);if(!i)return;let r=new Yx,o=qx().createGain();o.gain.value=1;let n=new Yx;r.pipeTo(n).pipeTo(this.pipeline.mixNode),r.setNode(i),n.setNode(o),this.mixedAudioReferenceMap.set(t,[r,n])}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(),cU.off("audioInputAdded",this.handleMicrophoneAdded,this),cU.off("audioInputRemoved",this.handleMicrophoneRemoved,this),JO.off(QO.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return nw(this,null,(function*(){try{yield ow(e.prototype,this,"recapture").call(this,t,i)}catch(cM){let r=(yield hU()).find((e=>e.deviceId!==t));if(!r)throw cM;yield ow(e.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,ntp:_w()}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}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(vO?"":", 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)}};function dB(e,t){return t+4<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&0===e.getUint8(t+2)&&1===e.getUint8(t+3)?4:t+3<=e.byteLength&&0===e.getUint8(t)&&0===e.getUint8(t+1)&&1===e.getUint8(t+2)?3:0}function uB(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=new DataView(e),r=[],o=0;for(;o<i.byteLength;){let e=dB(i,o);if(0===e){o+=1;continue}let n=-1;for(let t=o+e;t<i.byteLength;t+=1)if(dB(i,t)>0){n=t;break}let a=-1===n?i.byteLength:n,s=a-o,l=new ArrayBuffer(s),c=new DataView(l);for(let t=0;t<s;t+=1)c.setUint8(t,i.getUint8(o+t));r.push(new hB(c,t)),o=a}return r}var hB=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{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-2,i=[],r=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===r&&(i.push(3),r=0),0===e?r+=1:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}removePreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-1,i=[],r=0;for(let n=e;n<=t;n++)switch(this.dataView.getInt8(n)){case 0:r++,i.push(this.dataView.getInt8(n));break;case 3:2!==r&&i.push(this.dataView.getInt8(n)),r=0;break;default:i.push(this.dataView.getInt8(n)),r=0}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=o}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e+=1,255===this.dataView.getUint8(t));t+=1);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+=1){let i=this.dataView.getUint8(n);if(t+=1,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i),o=t;for(let n=0;n<i.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(o+n));return r}get naluType(){let e=this.getStartCodeLength();return e>=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&0===this.dataView.getUint8(2)&&1===this.dataView.getUint8(3)?4:this.dataView.byteLength>=3&&0===this.dataView.getUint8(0)&&0===this.dataView.getUint8(1)&&1===this.dataView.getUint8(2)?3:0}get isIDR(){return 5===this.naluType}get isSPS(){return 7===this.naluType}get isPPS(){return 8===this.naluType}get isSEI(){return 6===this.naluType}},pB=class{constructor(){rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<i;a++)o.push(255);o.push(r);let n=new DataView(e);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hB(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,i=0,r=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(r.getUint8(o)){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)),o=r.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(o+e.data.byteLength),a=new DataView(n),s=new DataView(e.data),l=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)a.setInt8(l++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)a.setInt8(l++,s.getInt8(i));return e.data=n,r.length}return 0}},mB=class e extends sB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Ox),rw(this,"profile",Qb({},Qw)),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 pB),this.manager=e;let t=()=>{var e;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1});else{let t=AD((null==(e=this.room)?void 0:e.sdkAppId)||0)?Vw:Uw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(t)),this.setProfile($b(Qb({},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(pL&&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 nw(this,null,(function*(){var i,r,o;if(zD(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,fillVideo:!0}),this.muteImage=t,ow(e.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield null==(o=this.manager)?void 0:o.deleteWatermark("mute"),this.muteImage=void 0),ow(e.prototype,this,"setMute").call(this,t)}))}capture(t){return nw(this,arguments,(function(t){var i=this;let{deviceId:r,facingMode:o,useExactDeviceId:n=!0,customSource:a,retryWhenExactFailed:s=!0}=t;return function*(){let t={audio:!1,video:!0,facingMode:o||i.facingMode,cameraId:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:s,customSource:a};if("environment"===t.facingMode){let e=yield i.getDeviceIdWhenUsingBackCamera();e&&(t.cameraId=e)}return ow(e.prototype,i,"capture").call(i,t)}()}))}setProfile(e){var t;let i=this.fallbackProfile(e);if(i.bitrate&&(this.isNeedToSetBandwidth=i.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(i);else{let e=AD((null==(t=this.room)?void 0:t.sdkAppId)||0)?Vw:Uw;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(e)),super.setProfile($b(Qb({},this.profile),{width:1920,height:1080}))}}applyProfile(){return nw(this,null,(function*(){var e;if(!this.mediaTrack)return;let{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,o=this.settings,n=o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate;if(n&&(16===RO&&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 n&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:eC.VIDEO,videoType:eC.BIG})}}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return pL&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:CN(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 nw(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),JO.emit(QO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(CC){throw this.log.error("switch camera failed ".concat(CC)),this.deviceId&&this.recapture(this.deviceId),CC}}))}getDeviceIdWhenUsingBackCamera(){return nw(this,null,(function*(){let e;try{if(Zk&&!lO&&fL){let t=(yield pU(!0)).map((e=>{var t;return $b(Qb({},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,o,n;let{capabilities:a}=e;(null!=(t=a.width)&&t.max&&null!=(r=a.height)&&r.max?a.width.max*a.height.max:0)>(null!=(o=i.capabilities.width)&&o.max&&null!=(n=i.capabilities.height)&&n.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(CC){this._log.warn("get max res camera failed",CC)}return e}))}updateSmallConfig(e){return nw(this,null,(function*(){var t,i;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let r=!this.small;this.small=this.fallbackProfile(e,!0),yield null==(t=this.manager)?void 0:t.update(),r&&(yield null==(i=this.room)?void 0: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=Qb({},e);return e.width*e.height<=19200&&ck&&hO&&(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&&CO&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),AO(IO,"14.3")&&SO(IO,"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&&(hO||pk)&&!LO()&&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(){cU&&!cU.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&cU.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return nw(this,null,(function*(){if(e.deviceId===this.deviceId){let t=1===this.recaptureMode;if(this.log.warn("RecaptureMode: ".concat(nB[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),0===this.recaptureMode){rH(this.userId,{eventId:2003,param1:7,streamType:2});let e=yield pU();e[0]?this.recapture(e[0].deviceId):t=!0}t&&cU.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return nw(this,null,(function*(){1===this.recaptureMode&&e.deviceId!==this.deviceId||(cU.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 jD(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){cU.off("videoInputAdded",this.handleCameraAdded,this),cU.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return nw(this,null,(function*(){try{yield ow(e.prototype,this,"recapture").call(this,t)}catch(CC){let r=(yield pU()).find((e=>e.deviceId!==t));if(!r)throw CC;yield ow(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||jD(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};iw([kU((function(e){this.setContentHint(e.contentHint||"motion")}))],mB.prototype,"capture",1);var fB=mB,_B={};ew(_B,{REPORT_TYPE:()=>ON,buildSSOPackage:()=>MN,bytes2ms:()=>MD,calculateScaleResolutionDownNumber:()=>CN,concatArrayBuffers:()=>PN,convertObjectNumberToInt:()=>AN,copyProperties:()=>OD,deepClone:()=>pN,deepCloneBasic:()=>kN,deepMerge:()=>hN,delay:()=>SN,fibonacci:()=>BD,formatedTime:()=>_N,getConstructorName:()=>eN,getContainerFromElement:()=>fN,getEnv:()=>ID,getFirst16Bits:()=>xN,getInternalVersion:()=>aN,getLast16Bits:()=>LN,getLoggerUrl:()=>SD,getMediaStreamTrackInfo:()=>wN,getMuteStateFromFlag:()=>cN,getNetworkType:()=>bD,getNumNetworkType:()=>kD,getReconnectionTimeout:()=>HD,getStringByteLength:()=>vN,getTurnServer:()=>dN,getUint32Version:()=>IN,getValueType:()=>WD,getViewListFromView:()=>mN,glog:()=>UD,ipv4ToUint32:()=>uN,isArray:()=>JD,isAudioWorkletSupported:()=>tN,isBoolean:()=>qD,isConstructor:()=>ZD,isEmpty:()=>lN,isFunction:()=>GD,isLangChinese:()=>VD,isMediaStreamTrack:()=>XD,isNumber:()=>KD,isObject:()=>YD,isOverseaSdkAppId:()=>AD,isPlainObject:()=>FD,isPortrait:()=>yN,isPromise:()=>$D,isRemoteTrack:()=>QD,isRotate90Or270:()=>DN,isSetSinkIdSupported:()=>iN,isString:()=>zD,isUndefined:()=>jD,loadImage:()=>TN,loadVideo:()=>NN,ms2bytes:()=>LD,ms2samples:()=>xD,normalizeUrl:()=>bN,performanceNow:()=>oN,promiseAny:()=>rN,samples2ms:()=>PD,setNetworkTypeFromWebRTC:()=>ND,stringify:()=>gN,stringifyIncludeValue:()=>EN,throttlePromise:()=>RN});var gB=[-1,-1,1,-1,-1,1,1,1],EB=[0,0,1,0,0,1,1,1],vB=class e extends zL{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 xB)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==RO?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(EB),this.positionBuffer=this.createBuffer(gB),!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(cM){this.context.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(cM.message||cM)}))}}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 LB&&this.render(e)||this.context instanceof xB&&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 LB){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,o,n,a,s,l,c){let d=!(jD(a)||jD(s)||jD(l)||jD(c));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,a,s,l,c):this.ctx2d.putImageData(t,i,r),this.emit(e.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,a,s,l,c,i,r,o,n):this.ctx2d.drawImage(t,i,r,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:i,y:r,width:o,height:n,name:a,cost:s}=this,l=Date.now(),c=(t-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:o,height:n,timestamp:l,fps:c,name:a,cost:s},Qb({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}};rw(vB,"RENDER","render"),iw([WL(zL.INIT,"connected",{sync:!0})],vB.prototype,"connect",1),iw([WL("connected",zL.INIT,{ignoreError:!0,sync:!0})],vB.prototype,"disconnect",1),iw([WL([],"closed",{sync:!0})],vB.prototype,"close",1);var yB=vB,TB=$U(CV(250),RF((()=>performance.now())),aV()),IB=e=>t=>{let i=performance.now();$U(TB,nF((t=>t-i<e)),ZV(1))(t)},AB=[0,1,1,1,0,0,1,0],SB=class extends yB{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 xB?this.ctx2d=e.ctx||null:e.available&&null!=t&&t.mirrorUpAndDown&&this.setTexBuffer(AB)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),QL.clearTask(this._intervalId),this._intervalId=QL.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(QL.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof LB){let e=this.context.ctx.getError();e&&this.context.destroy(new mw({code:hw.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(yB.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&&(QL.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),QL.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),QL.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},RB=class extends SB{constructor(e,t){super(e,t),rw(this,"_videoTrack"),rw(this,"_muteOb"),rw(this,"_closedOb",OV(this,"closed")),rw(this,"_subscription"),rw(this,"_canvasContainer"),Number(yO)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=OV(this._videoTrack,"mute"),$U(OV(this._videoTrack,"ended"),eF(this._closedOb),tB((()=>{this.context.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=$U(this._muteOb,eF(this._closedOb),MF(IB(5e3)),QV((()=>{var e;return!(null==(e=this._videoTrack)||!e.muted||document.hidden)})),tB((()=>{this.context.destroy(new mw({code:hw.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()}},bB=class extends RB{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),this.emit(yB.RENDER,this.context._canvas2d)}else this.emit(yB.RENDER,this.context._canvas);return i}},wB=class extends RB{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=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," ")),r>o?i=r/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)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},CB=class extends yB{constructor(e,t){super(e,Qb({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===RO&&(this._canvasRendered=vV(),$U(this._canvasRendered,mV(this._image),kF((e=>e instanceof HTMLCanvasElement?OV(e,"rendered"):jV())),eF(OV(this,"closed")),tB((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),CL()&&!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:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),({videoWidth:r,videoHeight:o}=n),!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:r,height:o}=n),n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?(({width:r,height:o}=n),this._lastImage=n):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame&&(({displayWidth:r,displayHeight:o}=n),null==(i=this._lastImage)||i.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&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(r,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)}},DB=class extends CB{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",$U(OV(this._player,$L.PLAYER_STATE_CHANGED),eF(OV(this,"closed")),QV((e=>{let{state:t}=e;return"PLAYING"===t})),tB((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},NB=class extends DB{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new Ox({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()}},kB=class extends yB{constructor(e,t,i){super(e,$b(Qb({name:"textSource"},i),{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: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 o=this.font.match(/(\d+)px/),n=(o?parseInt(o[1],10):16)*i,a=this.content.split("\n");for(let s=0;s<a.length;s++)this.ctx2d.fillText(a[s],e,t+s*n)}},OB=class extends zL{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 NB(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new RB(this,e)}createVideoImageSource(e,t){return new CB(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new DB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new kB(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};rw(OB,"_ids",0);var MB={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},PB=class extends OB{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(OB._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",MB),!this.ctx)throw new mw({code:hw.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 mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,CP.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}};rw(PB,"UNAVAILABLE","unavailable"),iw([WL(zL.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),CP.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),CP.addSuccessEvent({key:512700})}})],PB.prototype,"create",1),iw([WL("created",zL.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(PB.UNAVAILABLE,e),this.removeAllListeners()}})],PB.prototype,"destroy",1);var LB=PB,xB=class extends OB{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(OB._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new mw({code:hw.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,CP.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(),CP.addSuccessEvent({key:512703})}};function UB(e,t,i,r,o){arguments.length>5&&void 0!==arguments[5]&&arguments[5]&&([i,r]=[r,i]);let n={sWidth:e,sHeight:t,dWidth:i,dHeight:r,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(i/e,r/t);n.dWidth=e*o,n.dHeight=t*o,n.dx=(i-n.dWidth)/2,n.dy=(r-n.dHeight)/2;break}case"cover":{let o=Math.max(i/e,r/t),a=i/o,s=r/o;n.sx=(e-a)/2,n.sy=(t-s)/2,n.sWidth=a,n.sHeight=s;break}}return n}iw([WL(zL.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),CP.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),CP.addSuccessEvent({key:512701})}})],xB.prototype,"create",1),iw([WL("created",zL.INIT,{ignoreError:!0,sync:!0})],xB.prototype,"destroy",1);var VB=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}},FB=class extends yB{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 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 o=new VB(e,t);this.inputs.splice(i,0,o)}changeInputLayout(e,t){let i=this.inputs.findIndex((t=>t.node===e));if(i<0)return;let{x:r,y:o,width:n,height:a,zIndex:s,fillMode:l,rotation:c,hidden:d}=t;if(!jD(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[i];jD(r)||(u.layout.x=r),jD(o)||(u.layout.y=o),jD(n)||(u.layout.width=n),jD(a)||(u.layout.height=a),jD(c)||(u.layout.rotation=c),jD(d)||(u.layout.hidden=d),l&&(u.layout.fillMode=l),!jD(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 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 LB&&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=UB(t.node.width,t.node.height,t.width,t.height,t.fillMode,DN(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 o=arguments.length>4&&void 0!==arguments[4]&&arguments[4];this.ctx2d&&(o&&([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: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:i,width:r,height:o,timestamp:a,fps:s,name:n},Qb({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 LB)try{null==(t=this.context.ctx)||t.deleteBuffer(e.positionBuffer)}catch(cM){}}))}close(){super.close(),this.removeAllInputs()}},BB=[1,0,0,0,1,1,0,1],HB=class extends yB{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),rw(this,"mirror",!1),rw(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof LB)try{this.setTexBuffer(BB)}catch(Rw){e.destroy(new mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(Rw.message||Rw)}))}}draw2d(e,t,i,r,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(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(o/r,r/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/r,r/o));let n=super.draw2d(e,t,i,r,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){DN(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},WB=class extends sB{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,Ox),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(yB.RENDER,(e=>{this.emit("render",e)})),this.mixNode=new FB(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=QL.run("interval",(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new xB({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,i=0,r=!0;for(let[o,n]of this.inputLocalVideoTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.cameraNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o}for(let[o,n]of this.inputLocalScreenTracks)if(n.profile.frameRate>i){if(this.endedIds.has(o)){let e=this.screenNodeMap.get(o);e&&e.image.cancelVideoFrameCallback(e.videoCallbackId);continue}i=n.profile.frameRate,t=o,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 nw(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),vO&&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:o}=t;if(!o)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tx(this,cU).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===RO&&o instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(o,"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 o=this.videoContext.createVideoTrackSource(r,"screenNodeSource");o.resize(t.settings.width,t.settings.height),o.shouldUpdate=!1,this._connectMix(o,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,o),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,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:i,font:r,color:o});a.resize(n.width,n.height),this._connectMix(a,n),this.textNodeMap.set(t,a)}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,o=this.cameraNodeMap.get(e);if(o){if(i){if(16===RO&&i instanceof CanvasCaptureMediaStreamTrack)if(o instanceof NB){let t=o.output;o.close(),o=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),o.connect(t),this.cameraNodeMap.set(e,o)}else o.image=i.canvas;else if(o instanceof NB)o.replaceTrack(i);else{let t=o.output;o.close(),o=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),o.connect(t),this.cameraNodeMap.set(e,o)}let{width:t,height:r}=i.getSettings();t&&r&&o.resize(t,r)}r&&o.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(o,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:o,layout:n}=e,a=this.textNodeMap.get(t);a&&(jD(i)||(a.content=i),jD(r)||(a.font=r),jD(o)||(a.color=o),a.resize(n.width,n.height),this._changeMixLayout(a,n))}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:o}=t;e.disconnect();let n=new HB(this.videoContext,this.log,r,o);n=e.connect(n),t.fillMode||(t.fillMode=i),n.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,o=e.output||e;o instanceof HB&&(jD(i)||(o.mirror=i),jD(r)||(o.rotation=r),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 i=this.cameraNodeMap.get(e);i&&(i.output instanceof HB&&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 HB&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof HB&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof HB&&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(),QL.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(),ix(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")}},GB=tM();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:GB,exposeOrigin:!0,permittedOrigins:["*"]})}catch(UH){}var jB=function(e){return nw(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:EO?{max:e.width}:{ideal:e.width,max:e.width},height:EO?{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:o=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return t}(e);eM.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(pO&&fO<74||EO||pk)&&eM.warn("Your browser not support capture system audio");let o=r.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(pM){eM.warn("screen applyConstraints failed: ".concat(pM))}e.captureElement&&(yield function(e,t){return nw(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&GD(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==GB)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){eM.warn("cropTo target failed ".concat(r))}}))}(o,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 jD(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);eM.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},zB=class extends fB{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 GB===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(cM){return}}capture(e){return nw(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:n,audioTrack:a,videoTrack:s,captureElement:l,preferDisplaySurface:c}=e;return function*(){try{let e;return s||a?(e=new MediaStream,s&&e.addTrack(s),a&&e.addTrack(a)):(e=yield jB({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:n,captureElement:l,preferDisplaySurface:c}),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 mw?e:new mw({code:hw.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return nw(this,null,(function*(){throw new Error("Method not implemented.")}))}};iw([kU((function(e){this.setContentHint(e.contentHint||"detail")}))],zB.prototype,"capture",1);var KB,qB=class extends cB{constructor(e){super(e),this._log.id="s-".concat(this._log.id),this.isScreen=!0}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 YB(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 nw(this,null,(function*(){let o=qx();KB||(KB=Mx(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=i,r&&a.port.postMessage({port:r},[r]),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 JB=class extends $x{constructor(e){super(),this.room=e,rw(this,"_localAudioTrack"),rw(this,"_localScreenAudioTrack"),rw(this,"log"),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),this.log=eM.createLogger({parent:null==e?void 0:e.getLogger(),id:"am",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0: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=[],o=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.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),l=()=>{for(let e=0;e<o.length;e++){let t=URL.createObjectURL(new Blob(a[e])),i=document.createElement("a");i.href=t,i.download="".concat(o[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(s),n.abort("download")},c=YB(r).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=>l))));return{then:c.then.bind(c),download:l}}getPCM(e,t){var i,r,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:l}=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!n)return;this.log.info("getPCM ".concat(t||"local"));let c,d,u=Math.floor(.04*a),h=new Float32Array(u),p=new Float32Array(u),m=0,f=new AbortController,_=""===t?null==(i=this._localAudioTrack)?void 0:i.mediaTrack:null==(o=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:o.remoteAudioTrack.mediaTrack;if(_)return YB([qx().createMediaStreamSource(new MediaStream([_]))],a,s,l).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),c=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):(c&&(h.set(c,m),m+=c.length,c=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: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!jD(this._localScreenAudioTrack)}get hasAudioTrack(){return!jD(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof qB?(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 cB?(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 $B?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 qB?delete this._localScreenAudioTrack:e instanceof cB&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var o;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==(o=this._localScreenAudioTrack)||o.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 o=this.getPCM((e=>{var t;null==(t=this.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,o),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(){JO.on("113",this.handleLocalTrackStarted,this),JO.on("114",this.handleLocalTrackStopped,this),JO.on("115",this.handleRemoteTrackStarted,this),JO.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){JO.off("113",this.handleLocalTrackStarted),JO.off("114",this.handleLocalTrackStopped),JO.off("115",this.handleRemoteTrackStarted),JO.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:o}=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||jD(o))return;this.setAudioReferenceVolume(r,o)}}};var XB=class e extends AU{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,rw(this,"tinyId"),rw(this,"isRemote",!0),rw(this,"jitterBufferDelay",0),rw(this,"availableState"),rw(this,"remotePublishState"),rw(this,"_triggerCheckDecodeSubject",vV(OV(this,e.STATE_SUBSCRIBE))),rw(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new zL("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new zL("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),$U(sV(OV(this,zL.STATECHANGED),OV(this.remotePublishState,zL.STATECHANGED)),RF((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),tB((e=>{this.availableState.state!==(e?zL.ON:zL.OFF)&&(this.availableState.state=e?zL.ON:zL.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(e)})));let o=$U(OV(this.player,$L.ERROR),QV((e=>e.code===MediaError.MEDIA_ERR_DECODE))),n=$U(DV(5e3),QV((()=>!(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)&&(!this.player.isPlaying&&!(this.kind===eC.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1))))),a=$U(lV(o,n),eF(OV(this,zL.INIT)));$U(this._triggerCheckDecodeSubject,QV((()=>!this.ignoreDecodeError)),MF(a),tB((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===zL.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var i,r;let o=this.kind===eC.AUDIO;if(CP[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let t=(null==(i=this.room)?void 0:i.downlinkVideoCodec.toUpperCase())||"H264";CP[e?"addSuccessEvent":"addFailedEvent"]({key:RP["DECODE_".concat(t,"_RESULT")]}),e||this.log.warn("".concat(null==(r=this.room)?void 0:r.downlinkVideoCodec," decode failed"))}e||(CP.addEnum({key:o?504701:514703,value:GO()}),rx.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(FO()||zO()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===eC.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),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?zL.ON:zL.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};rw(XB,"STATE_SUBSCRIBE","subscribe"),iw([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 OU(((i,r)=>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 i=new mw({code:hw.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||eM).warn(i),2===t?a(i):1===t&&o()}),1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(s),i.apply(this,n).then(o,a).finally((()=>{clearTimeout(s),this._checkPendingPromiseSet&&s&&this._checkPendingPromiseSet.delete(s)}))}))}))}(5,1)],XB.prototype,"waitHasMediaTrack",1),iw([WL(zL.INIT,XB.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),JO.emit(QO.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),BU(521716,!1)],XB.prototype,"subscribe",1),iw([WL(XB.STATE_SUBSCRIBE,zL.INIT,{sync:!0,success(){this.log.info("unsubscribed"),JO.emit(QO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],XB.prototype,"unsubscribe",1);var QB=XB,$B=class extends QB{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 oU.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&&yL().AudioDecoder&&_L)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let o={frame:e,track:this};if(1===i&&this.isAvailable&&"audience"===this.room.role&&(o.onAudioFrameNTPTime=e=>{let{ntp:t,frame:i,hasLeavingTag:r}=e;this.emit("audio-frame-with-ntp",{ntp:t,frame:i,hasLeavingTag:r})}),t=r(o),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},ZB=class extends yB{constructor(e,t,i,r,o){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,rw(this,"initStat",{alphaStitchingType:1}),rw(this,"end",vV()),rw(this,"minSize",320),rw(this,"maxSize",1280),rw(this,"draggable",!1),rw(this,"startDragX",0),rw(this,"startDragY",0),rw(this,"left",0),rw(this,"top",0),rw(this,"baseWidth",320),rw(this,"baseRatio"),rw(this,"container"),this.initStat=o,this.draggable=i,this.bindDragEvents(),CP.addEnum({key:515700,value:1}),this.draggable&&CP.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=eF(this.end);$U(OV(e,"mousedown"),iB(this.startDrag.bind(this)),kF((()=>$U(OV(window,"mousemove"),eF(OV(window,"mouseup"))))),t,tB(this.doDrag.bind(this))),$U(OV(e,"dblclick"),t,tB(this.resetPosition.bind(this))),$U(OV(e,"wheel"),t,tB(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(e){e.preventDefault(),0===e.button&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),e&&this.baseRatio&&this.draggable&&(e.style.setProperty("width","".concat(this.baseWidth,"px")),e.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),e.style.setProperty("position","fixed"),e.style.setProperty("left","".concat(this.left,"px")),e.style.setProperty("top","".concat(this.top,"px")))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=e.deltaY,i=this.context._canvas;i&&(this.baseWidth||(this.baseWidth=i.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,i,r,o){var n;let{ctx2d:a}=this,s=this.context._canvas;if(!a||!s)return!1;let l=super.draw2d(e,t,i,r,o),c=a.getImageData(0,0,r,o),{data:d}=c,u=!1;if(1===this.initStat.alphaStitchingType){let e=Math.floor(r/2);for(let t=0;t<o;t++)for(let i=0;i<e;i++){let o=4*(t*r+i),n=4*(t*r+(i+e)),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,e,o),s.width=e}else if(2===this.initStat.alphaStitchingType){let e=Math.floor(o/2);for(let t=0;t<e;t++)for(let i=0;i<r;i++){let o=4*(t*r+i),n=4*((t+e)*r+i),a=d[n];d[n+3]=0;let s=a>=100;d[o+3]=s?255:0}u=super.draw2d(c,0,0,0,0,r,e),s.height=e}return null==(n=this.context.ctx)||n.clearRect(0,0,r,o),l&&u}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};var eH=class extends QB{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,"shouldRenderAlpha",!1),rw(this,"alphaNode"),rw(this,"shouldBeDraggable",!0),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.on("first-video-frame",(e=>{this.room.emit("first-video-frame",e)}))}isAlphaSei(e){if(this.userId!==e.userId||50!==e.seiPayloadType)return!1;let t=new Uint8Array(e.data);return t.length%3==0&&0===t[0]&&1===t[1]&&t}play(e,t){return null!=t&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat(),JO.emit("156",{track:this,player:this.player})}))}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(this.alphaNode){let e=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===e)return;this.alphaNode.initStat={alphaStitchingType:e};let i=this.player.getElement();if(i){let t=i.videoWidth/i.videoHeight;t&&(this.alphaNode.baseRatio=t*(1===e?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(e))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(e){let t=dP[e];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(e){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new xB({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let i=new SB(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let r=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},o=new ZB(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(o),o.connect(i),this.alphaNode=o}else this.source.connect(i);CL()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),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;!KD(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),JO.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),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)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},tH=class extends eH{constructor(e,t){super(e,t,2),rw(this,"mediaType",2),rw(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},iH=new Map;function rH(e,t){let i=$b(Qb({},t),{timestamp:_w()});iH.has(e)?iH.get(e).push(i):iH.set(e,[i])}function oH(e){if(iH.has(e)){let t=iH.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 iH.delete(e),t}return[]}function nH(e,t,i,r){try{if(JD(e))for(let o=0;o<e.length;o++)aH.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else aH.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(cM){throw eM.error(cM),cM}}function aH(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;if(jD(i)){if(t.required)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(jD(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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),zD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map((e=>ZD(e)?eN(e):zD(e)?e:WD(e)))},fnName:o,value:i},link:{className:n,fnName:o}})})}else if(!jD(t.type)&&WD(i)!==t.type)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),a=zD(i)&&""===i.trim();if(e||a)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}if(t.notLessThanZero&&KD(i)&&i<0)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!jD(t.min)&&KD(i)&&i<t.min)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(!jD(t.max)&&KD(i)&&i>t.max)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(zD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})})}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});if(t.values&&!t.values.includes(i))throw new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:o,value:i},link:{className:n,fnName:o}})});let{properties:a}=t;FD(a)&&YD(i)&&Object.keys(a).forEach((e=>{aH.call(this,{rule:a[e],value:i&&i[e],key:"".concat(r,".").concat(e),fnName:o,className:n})}));let{arrayItem:s}=t;FD(s)&&JD(i)&&i.forEach(((e,t)=>{aH.call(this,{rule:s,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})})),GD(t.validate)&&t.validate.call(this,i,r,o,n,this)}JO.on(QO.JOIN_SUCCESS,(e=>{let{room:t}=e;rH(t.userId,{eventId:32788})})),JO.on(QO.LEAVE_START,(e=>{let{room:t}=e;rH(t.userId,{eventId:32789})})),JO.on(QO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),rH(t.room.userId,{eventId:e})}})),JO.on(QO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),rH(t.room.userId,{eventId:e})}})),JO.on(QO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===eC.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),JO.on(QO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===eC.AUDIO?rH(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):rH(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),JO.on(QO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),JO.on(QO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;t.room&&(1===t.mediaType&&rH(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&rH(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&rH(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),JO.on(QO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===eC.VIDEO?32780:32781})})),JO.on(QO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&rH(t.room.userId,{eventId:t.kind===eC.VIDEO?32782:32783})})),JO.on(QO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:o}=e;switch(o){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&rH(i.userId,{eventId:t})})),JO.on(QO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:o,remoteUserId:n}=e,a=!!n;switch(o){case"CONNECTED":t="RECONNECTING"===r?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&rH(i.userId,{eventId:t,remoteUserId:n})})),JO.on(QO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:i,remoteUserId:r,codec:o,isHWCodec:n,prevImplementation:a,streamType:s}=e,l=n?1:0;a||(l=n?3:2);let c={H264:0,H265:1,VP8:2}[o.toUpperCase()],d={eventId:4004,param1:l,param2:c,streamType:s||2};r&&(d.remoteUserId=r,d.eventId=4005),rH(i,d),CP.addEnum({key:r?514701:513701,value:l}),CP.addEnum({key:r?514700:513700,value:c})})),JO.on(QO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===eC.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),rH(t.userId,e)}})),tw(aw(),1);var sH=Object.create,lH=Object.defineProperty,cH=Object.defineProperties,dH=Object.getOwnPropertyDescriptor,uH=Object.getOwnPropertyDescriptors,hH=Object.getOwnPropertyNames,pH=Object.getOwnPropertySymbols,mH=Object.getPrototypeOf,fH=Object.prototype.hasOwnProperty,_H=Object.prototype.propertyIsEnumerable,gH=(e,t,i)=>t in e?lH(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,EH=(e,t)=>{for(var i in t||(t={}))fH.call(t,i)&&gH(e,i,t[i]);if(pH)for(var i of pH(t))_H.call(t,i)&&gH(e,i,t[i]);return e},vH=(e,t)=>cH(e,uH(t)),yH=(e,t,i)=>(i=null!=e?sH(mH(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of hH(t))fH.call(e,o)||o===i||lH(e,o,{get:()=>t[o],enumerable:!(r=dH(t,o))||r.enumerable});return e})(!t&&e&&e.__esModule?i:lH(i,"default",{value:e,enumerable:!0}),e)),TH=(e,t,i,r)=>{for(var o,n=r>1?void 0:r?dH(t,i):t,a=e.length-1;a>=0;a--)(o=e[a])&&(n=(r?o(t,i,n):o(n))||n);return r&&n&&lH(t,i,n),n},IH=(e,t,i)=>gH(e,"symbol"!=typeof t?t+"":t,i),AH=((e,t)=>function(){return t||(0,e[hH(e)[0]])((t={exports:{}}).exports,t),t.exports})({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){var i=Object.prototype.hasOwnProperty,r="~";function o(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,o,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new n(i,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new o:delete e._events[t]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),(new o).__proto__||(r=!1)),l.prototype.eventNames=function(){var e,t,o=[];if(0===this._eventsCount)return o;for(t in e=this._events)i.call(e,t)&&o.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},l.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 o=0,n=i.length,a=new Array(n);o<n;o++)a[o]=i[o].fn;return a},l.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},l.prototype.emit=function(e,t,i,o,n,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,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,i),!0;case 4:return d.fn.call(d.context,t,i,o),!0;case 5:return d.fn.call(d.context,t,i,o,n),!0;case 6:return d.fn.call(d.context,t,i,o,n,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var h,p=d.length;for(c=0;c<p;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),u){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,i);break;case 4:d[c].fn.call(d[c].context,t,i,o);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d[c].fn.apply(d[c].context,l)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,i,o){var n=r?r+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||i&&a.context!==i||s(this,n);else{for(var l=0,c=[],d=a.length;l<d;l++)(a[l].fn!==t||o&&!a[l].once||i&&a[l].context!==i)&&c.push(a[l]);c.length?this._events[n]=1===c.length?c[0]:c:s(this,n)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,void 0!==t&&(t.exports=l)}}),SH=yH(AH(),1),RH=Symbol("instance"),bH=Symbol("cacheResult"),wH=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,OH.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},CH=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var DH=new Map;function NH(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,o,n)=>{let a=i.action||o;if(!i.context){let i=DH.get(r)||[];DH.has(r)||DH.set(r,i),i.push({from:e,to:t,action:a})}let s=n.value;n.value=function(){let r=this;for(var o=arguments.length,n=new Array(o),l=0;l<o;l++)n[l]=arguments[l];if(i.context&&(r=MH.get("function"==typeof i.context?i.context.call(this,...n):i.context)),r.state===t)return i.sync?r[bH]:Promise.resolve(r[bH]);r.state instanceof wH&&r.state.action==i.abortAction&&r.state.abort(r);let c=null;Array.isArray(e)?0==e.length?r.state instanceof wH&&r.state.abort(r):"string"==typeof r.state&&e.includes(r.state)||(c=new CH(r._state,"".concat(r.name," ").concat(a," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(c=new CH(r._state,"".concat(r.name," ").concat(a," 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(c)return d(c);let u=r.state,h=new wH(u,t,a);OH.call(r,h);let p=e=>{var o;return r[bH]=e,h.aborted||(OH.call(r,t),null===(o=i.success)||void 0===o||o.call(this,r[bH])),e},m=e=>(OH.call(r,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):i.sync?p(e):Promise.resolve(p(e))}catch(mM){return m(new CH(r._state,"".concat(r.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(mM),mM instanceof Error?mM:new Error(String(mM))))}}}}var kH="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 OH(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(MH.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var MH=class e extends SH.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 o=r[RH];o?this.name=o.name+"-"+o.count++:r[RH]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=DH.get(e)||[],i=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(e);DH.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((e=>{let{from:t,to:i,action:n}=e;"string"==typeof t?r.push({from:t,to:i,action:n}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:n})})):o.push({to:i,action:n})})),r.forEach((e=>{let{from:t,to:r,action:o}=e;n.add(t),n.add(r),n.add(o+"ing"),i.add("".concat(t," --\x3e ").concat(o,"ing : ").concat(o)),i.add("".concat(o,"ing --\x3e ").concat(r," : ").concat(o," 🟢")),i.add("".concat(o,"ing --\x3e ").concat(t," : ").concat(o," 🔴"))})),o.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),n.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let s=[...i];return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:n}}),s}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]:{};kH(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){OH.call(this,e)}};MH.STATECHANGED="stateChanged",MH.UPDATEAFSM="updateAFSM",MH.INIT="[*]",MH.ON="on",MH.OFF="off",MH.instances=new Map,MH.instances2=new WeakMap;var PH=class extends MH{constructor(){super(...arguments),IH(this,"decoder"),IH(this,"config")}initialize(){return nw(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(vH(EH({},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 LH(){var e;self.onmessage=t=>{if("init"===t.data.type){let{canvas:i,wasmScript:r,wasmBinary:o}=t.data,n=null==i?void 0:i.getContext("2d"),a=0,s=0,l={wasmBinary:o,postRun:()=>{e=new l.VideoDecoder({videoInfo(e,t){a=e,s=t,console.log("video info",e,t)},yuvData(e,t){let r=a*s,o=r>>2,c=l.HEAPU32[e>>2],d=l.HEAPU32[1+(e>>2)],u=l.HEAPU32[2+(e>>2)],h=l.HEAPU8.subarray(c,c+r),p=l.HEAPU8.subarray(d,d+o),m=l.HEAPU8.subarray(u,u+o),f=new Uint8Array(r+o+o);f.set(h),f.set(p,r),f.set(m,r+o);let _=new VideoFrame(f,{codedWidth:a,codedHeight:s,format:"I420",timestamp:t});i?(null==n||n.drawImage(_,0,0,i.width,i.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 "+r)()(l)}else if("decode"===t.data.type){let{packet:i}=t.data;null==e||e.decode(i.data,"key"==i.type,i.timestamp)}else if("setCodec"===t.data.type){let{codec:i,format:r,description:o}=t.data;null==e||e.setCodec(i,r,null!=o?o:"")}}}TH([NH([MH.INIT,"closed"],"initialized")],PH.prototype,"initialize",1),TH([NH("initialized","configured",{sync:!0})],PH.prototype,"configure",1),TH([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return(e,i,r)=>{let o=r.value,n=i;r.value=function(){if(!t.includes(this.state.toString()))throw new CH(this.state,"".concat(this.name," ").concat(n," failed: current state ").concat(this.state," not in ").concat(t));for(var e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return o.apply(this,i)}}}("configured")],PH.prototype,"decode",1),TH([NH([],MH.INIT,{sync:!0})],PH.prototype,"reset",1),TH([NH([],"closed",{ignoreError:!0,sync:!0})],PH.prototype,"close",1);var xH=class extends MH{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=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=i,this.canvas=r,this.yuvMode=o,IH(this,"worker"),IH(this,"decoder"),IH(this,"config"),IH(this,"module",{}),IH(this,"width",0),IH(this,"height",0)}initialize(e){return nw(this,null,(function*(){var t;if(this.workerMode){let e=new RegExp("\\{(.+)\\}","s").exec(LH.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"text/javascript"})));let i=null==(t=this.canvas)?void 0:t.transferControlToOffscreen(),r=yield this.wasmBinary;return console.warn("worker mode",r),this.worker.postMessage({type:"init",canvas:i,wasmScript:this.createModule.toString(),wasmBinary:r},i?[i,r]:[r]),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 i=this.module;return this.wasmBinary&&(i.wasmBinary=yield this.wasmBinary),i.print=e=>console.log(e),i.printErr=e=>console.log("[JS] ERROR: ".concat(e)),i.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise((t=>{i.postRun=e=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),t()},e&&Object.assign(i,e),this.createModule(i)}))}))}configure(e){var t,i,r;this.config=e;let o=this.config.codec.startsWith("avc")?"avc":"hevc",n=this.config.description?"avc"==o?"avcc":"hvcc":"annexb";null==(i=this.decoder)||i.setCodec(o,n,null!=(t=this.config.description)?t:""),null==(r=this.worker)||r.postMessage({type:"setCodec",codec:o,format:n,description:this.config.description})}decode(e){var t,i;null==(t=this.decoder)||t.decode(e.data,"key"==e.type,e.timestamp),"configured"===this.state&&(null==(i=this.worker)||i.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 i={width:e,height:t};this.emit("videoCodecInfo",i)}yuvData(e,t){if(!this.module)return;let i=this.width*this.height,r=i>>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+i),l=this.module.HEAPU8.subarray(n,n+r),c=this.module.HEAPU8.subarray(a,a+r);if(this.yuvMode)return void this.emit("videoFrame",{y:s,u:l,v:c,timestamp:t});let d=new Uint8Array(i+r+r);d.set(s),d.set(l,i),d.set(c,i+r),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)}};TH([NH([MH.INIT,"closed"],"initialized")],xH.prototype,"initialize",1),TH([NH("initialized","configured",{sync:!0})],xH.prototype,"configure",1),TH([NH([],MH.INIT,{sync:!0})],xH.prototype,"reset",1),TH([NH([],"closed",{sync:!0})],xH.prototype,"close",1);var UH,VH=(UH="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t,i,r=e;r.ready=new Promise(((e,r)=>{t=e,i=r}));var o,n,a,s=Object.assign({},r),l="./this.program",c="object"==typeof window,d="function"==typeof importScripts,u=("object"==typeof process&&"object"==typeof process.versions&&process.versions.node,"");(c||d)&&(d?u=self.location.href:"undefined"!=typeof document&&document.currentScript&&(u=document.currentScript.src),UH&&(u=UH),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,i)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):i()},r.onerror=i,r.send(null)});var h,p,m=r.print||console.log.bind(console),f=r.printErr||console.error.bind(console);Object.assign(r,s),s=null,r.arguments&&r.arguments,r.thisProgram&&(l=r.thisProgram),r.quit&&r.quit,r.wasmBinary&&(h=r.wasmBinary),r.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,P=null;function L(e){M++,r.monitorRunDependencies&&r.monitorRunDependencies(M)}function x(e){if(M--,r.monitorRunDependencies&&r.monitorRunDependencies(M),0==M&&P){var t=P;P=null,t()}}function U(e){r.onAbort&&r.onAbort(e),f(e="Aborted("+e+")"),D=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(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,i){return(r=e,h||!c&&!d||"function"!=typeof fetch?Promise.resolve().then((()=>F(r))):fetch(r,{credentials:"same-origin"}).then((e=>{if(!e.ok)throw"failed to load wasm binary file at '"+r+"'";return e.arrayBuffer()})).catch((()=>F(r)))).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(i,(e=>{f("failed to asynchronously prepare wasm: "+e),U(e)}));var r}V(R="videodec.wasm")||(b=R,R=r.locateFile?r.locateFile(b,u):u+b);var H=e=>{for(;e.length>0;)e.shift()(r)};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 G={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var i=0,r=e.length-1;r>=0;r--){var o=e[r];"."===o?e.splice(r,1):".."===o?(e.splice(r,1),i++):i&&(e.splice(r,1),i--)}if(t)for(;i;i--)e.unshift("..");return e},normalize:e=>{var t=G.isAbs(e),i="/"===e.substr(-1);return(e=G.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&i&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=G.splitPath(e),i=t[0],r=t[1];return i||r?(r&&(r=r.substr(0,r.length-1)),i+r):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=G.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return G.normalize(e.join("/"))},join2:(e,t)=>G.normalize(e+"/"+t)},j=e=>(j=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);U("initRandomDevice")})())(e),z={resolve:function(){for(var e="",t=!1,i=arguments.length-1;i>=-1&&!t;i--){var r=i>=0?arguments[i]:re.cwd();if("string"!=typeof r)throw new TypeError("Arguments to path.resolve must be strings");if(!r)return"";e=r+"/"+e,t=G.isAbs(r)}return(t?"/":"")+(e=G.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function i(e){for(var t=0;t<e.length&&""===e[t];t++);for(var i=e.length-1;i>=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=z.resolve(e).substr(1),t=z.resolve(t).substr(1);for(var r=i(e.split("/")),o=i(t.split("/")),n=Math.min(r.length,o.length),a=n,s=0;s<n;s++)if(r[s]!==o[s]){a=s;break}var l=[];for(s=a;s<r.length;s++)l.push("..");return(l=l.concat(o.slice(a))).join("/")}},K="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,q=(e,t,i)=>{for(var r=t+i,o=t;e[o]&&!(o>=r);)++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 l=63&e[t++];if((a=224==(240&a)?(15&a)<<12|s<<6|l:(7&a)<<18|s<<12|l<<6|63&e[t++])<65536)n+=String.fromCharCode(a);else{var c=a-65536;n+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else n+=String.fromCharCode((31&a)<<6|s)}else n+=String.fromCharCode(a)}return n},Y=[],J=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++i):t+=3}return t},X=(e,t,i,r)=>{if(!(r>0))return 0;for(var o=i,n=i+r-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(i>=n)break;t[i++]=s}else if(s<=2047){if(i+1>=n)break;t[i++]=192|s>>6,t[i++]=128|63&s}else if(s<=65535){if(i+2>=n)break;t[i++]=224|s>>12,t[i++]=128|s>>6&63,t[i++]=128|63&s}else{if(i+3>=n)break;t[i++]=240|s>>18,t[i++]=128|s>>12&63,t[i++]=128|s>>6&63,t[i++]=128|63&s}}return t[i]=0,i-o};function Q(e,t,i){var r=i>0?i:J(e)+1,o=new Array(r),n=X(e,o,0,o.length);return t&&(o.length=n),o}var $={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){$.ttys[e]={input:[],output:[],ops:t},re.registerDevice(e,$.stream_ops)},stream_ops:{open:function(e){var t=$.ttys[e.node.rdev];if(!t)throw new re.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,i,r,o){if(!e.tty||!e.tty.ops.get_char)throw new re.ErrnoError(60);for(var n=0,a=0;a<r;a++){var s;try{s=e.tty.ops.get_char(e.tty)}catch(l){throw new re.ErrnoError(29)}if(void 0===s&&0===n)throw new re.ErrnoError(6);if(null==s)break;n++,t[i+a]=s}return n&&(e.node.timestamp=Date.now()),n},write:function(e,t,i,r,o){if(!e.tty||!e.tty.ops.put_char)throw new re.ErrnoError(60);try{for(var n=0;n<r;n++)e.tty.ops.put_char(e.tty,t[i+n])}catch(a){throw new re.ErrnoError(29)}return r&&(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=Q(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,i){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,i,r){if(re.isBlkdev(i)||re.isFIFO(i))throw new re.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:re.chrdev_stream_ops}});var o=re.createNode(e,t,i,r);return re.isDir(o.mode)?(o.node_ops=ee.ops_table.dir.node,o.stream_ops=ee.ops_table.dir.stream,o.contents={}):re.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):re.isLink(o.mode)?(o.node_ops=ee.ops_table.link.node,o.stream_ops=ee.ops_table.link.stream):re.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 i=e.contents?e.contents.length:0;if(!(i>=t)){t=Math.max(t,i*(i<1048576?2:1.125)>>>0),0!=i&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var i=e.contents;e.contents=new Uint8Array(t),i&&e.contents.set(i.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=re.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,re.isDir(e.mode)?t.size=4096:re.isFile(e.mode)?t.size=e.usedBytes:re.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 re.genericErrors[44]},mknod:(e,t,i,r)=>ee.createNode(e,t,i,r),rename(e,t,i){if(re.isDir(e.mode)){var r;try{r=re.lookupNode(t,i)}catch(n){}if(r)for(var o in r.contents)throw new re.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=i,t.contents[i]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var i=re.lookupNode(e,t);for(var r in i.contents)throw new re.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var i in e.contents)e.contents.hasOwnProperty(i)&&t.push(i);return t},symlink(e,t,i){var r=ee.createNode(e,t,41471,0);return r.link=i,r},readlink(e){if(!re.isLink(e.mode))throw new re.ErrnoError(28);return e.link}},stream_ops:{read(e,t,i,r,o){var n=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,r);if(a>8&&n.subarray)t.set(n.subarray(o,o+a),i);else for(var s=0;s<a;s++)t[i+s]=n[o+s];return a},write(e,t,i,r,o,n){if(!r)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(i,i+r),a.usedBytes=r,r;if(0===a.usedBytes&&0===o)return a.contents=t.slice(i,i+r),a.usedBytes=r,r;if(o+r<=a.usedBytes)return a.contents.set(t.subarray(i,i+r),o),r}if(ee.expandFileStorage(a,o+r),a.contents.subarray&&t.subarray)a.contents.set(t.subarray(i,i+r),o);else for(var s=0;s<r;s++)a.contents[o+s]=t[i+s];return a.usedBytes=Math.max(a.usedBytes,o+r),r},llseek(e,t,i){var r=t;if(1===i?r+=e.position:2===i&&re.isFile(e.node.mode)&&(r+=e.node.usedBytes),r<0)throw new re.ErrnoError(28);return r},allocate(e,t,i){ee.expandFileStorage(e.node,t+i),e.node.usedBytes=Math.max(e.node.usedBytes,t+i)},mmap(e,t,i,r,o){if(!re.isFile(e.node.mode))throw new re.ErrnoError(43);var n,a,s=e.node.contents;if(2&o||s.buffer!==_.buffer){if((i>0||i+t<s.length)&&(s=s.subarray?s.subarray(i,i+t):Array.prototype.slice.call(s,i,i+t)),a=!0,!(n=Z()))throw new re.ErrnoError(48);_.set(s,n)}else a=!1,n=s.byteOffset;return{ptr:n,allocated:a}},msync:(e,t,i,r,o)=>(ee.stream_ops.write(e,t,0,r,i,!1),0)}},te=r.preloadPlugins||[];function ie(e,t){var i=0;return e&&(i|=365),t&&(i|=146),i}var re={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 re.ErrnoError(32);for(var i=e.split("/").filter((e=>!!e)),r=re.root,o="/",n=0;n<i.length;n++){var a=n===i.length-1;if(a&&t.parent)break;if(r=re.lookupNode(r,i[n]),o=G.join2(o,i[n]),re.isMountpoint(r)&&(!a||a&&t.follow_mount)&&(r=r.mounted.root),!a||t.follow)for(var s=0;re.isLink(r.mode);){var l=re.readlink(o);if(o=z.resolve(G.dirname(o),l),r=re.lookupPath(o,{recurse_count:t.recurse_count+1}).node,s++>40)throw new re.ErrnoError(32)}}return{path:o,node:r}},getPath:e=>{for(var t;;){if(re.isRoot(e)){var i=e.mount.mountpoint;return t?"/"!==i[i.length-1]?"".concat(i,"/").concat(t):i+t:i}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var i=0,r=0;r<t.length;r++)i=(i<<5)-i+t.charCodeAt(r)|0;return(e+i>>>0)%re.nameTable.length},hashAddNode:e=>{var t=re.hashName(e.parent.id,e.name);e.name_next=re.nameTable[t],re.nameTable[t]=e},hashRemoveNode:e=>{var t=re.hashName(e.parent.id,e.name);if(re.nameTable[t]===e)re.nameTable[t]=e.name_next;else for(var i=re.nameTable[t];i;){if(i.name_next===e){i.name_next=e.name_next;break}i=i.name_next}},lookupNode:(e,t)=>{var i=re.mayLookup(e);if(i)throw new re.ErrnoError(i,e);for(var r=re.hashName(e.id,t),o=re.nameTable[r];o;o=o.name_next){var n=o.name;if(o.parent.id===e.id&&n===t)return o}return re.lookup(e,t)},createNode:(e,t,i,r)=>{var o=new re.FSNode(e,t,i,r);return re.hashAddNode(o),o},destroyNode:e=>{re.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)=>re.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>re.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return re.lookupNode(e,t),20}catch(i){}return re.nodePermissions(e,"wx")},mayDelete:(e,t,i)=>{var r;try{r=re.lookupNode(e,t)}catch(n){return n.errno}var o=re.nodePermissions(e,"wx");if(o)return o;if(i){if(!re.isDir(r.mode))return 54;if(re.isRoot(r)||re.getPath(r)===re.cwd())return 10}else if(re.isDir(r.mode))return 31;return 0},mayOpen:(e,t)=>e?re.isLink(e.mode)?32:re.isDir(e.mode)&&("r"!==re.flagsToPermissionString(t)||512&t)?31:re.nodePermissions(e,re.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=re.MAX_OPEN_FDS;e++)if(!re.streams[e])return e;throw new re.ErrnoError(33)},getStreamChecked:e=>{var t=re.getStream(e);if(!t)throw new re.ErrnoError(8);return t},getStream:e=>re.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return re.FSStream||(re.FSStream=function(){this.shared={}},re.FSStream.prototype={},Object.defineProperties(re.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 re.FSStream,e),-1==t&&(t=re.nextfd()),e.fd=t,re.streams[t]=e,e},closeStream:e=>{re.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=re.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new re.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{re.devices[e]={stream_ops:t}},getDevice:e=>re.devices[e],getMounts:e=>{for(var t=[],i=[e];i.length;){var r=i.pop();t.push(r),i.push.apply(i,r.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),re.syncFSRequests++,re.syncFSRequests>1&&f("warning: ".concat(re.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var i=re.getMounts(re.root.mount),r=0;function o(e){return re.syncFSRequests--,t(e)}function n(e){if(e)return n.errored?void 0:(n.errored=!0,o(e));++r>=i.length&&o(null)}i.forEach((t=>{if(!t.type.syncfs)return n(null);t.type.syncfs(t,e,n)}))},mount:(e,t,i)=>{var r,o="/"===i,n=!i;if(o&&re.root)throw new re.ErrnoError(10);if(!o&&!n){var a=re.lookupPath(i,{follow_mount:!1});if(i=a.path,r=a.node,re.isMountpoint(r))throw new re.ErrnoError(10);if(!re.isDir(r.mode))throw new re.ErrnoError(54)}var s={type:e,opts:t,mountpoint:i,mounts:[]},l=e.mount(s);return l.mount=s,s.root=l,o?re.root=l:r&&(r.mounted=s,r.mount&&r.mount.mounts.push(s)),l},unmount:e=>{var t=re.lookupPath(e,{follow_mount:!1});if(!re.isMountpoint(t.node))throw new re.ErrnoError(28);var i=t.node,r=i.mounted,o=re.getMounts(r);Object.keys(re.nameTable).forEach((e=>{for(var t=re.nameTable[e];t;){var i=t.name_next;o.includes(t.mount)&&re.destroyNode(t),t=i}})),i.mounted=null;var n=i.mount.mounts.indexOf(r);i.mount.mounts.splice(n,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,i)=>{var r=re.lookupPath(e,{parent:!0}).node,o=G.basename(e);if(!o||"."===o||".."===o)throw new re.ErrnoError(28);var n=re.mayCreate(r,o);if(n)throw new re.ErrnoError(n);if(!r.node_ops.mknod)throw new re.ErrnoError(63);return r.node_ops.mknod(r,o,t,i)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,re.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,re.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var i=e.split("/"),r="",o=0;o<i.length;++o)if(i[o]){r+="/"+i[o];try{re.mkdir(r,t)}catch(n){if(20!=n.errno)throw n}}},mkdev:(e,t,i)=>(void 0===i&&(i=t,t=438),t|=8192,re.mknod(e,t,i)),symlink:(e,t)=>{if(!z.resolve(e))throw new re.ErrnoError(44);var i=re.lookupPath(t,{parent:!0}).node;if(!i)throw new re.ErrnoError(44);var r=G.basename(t),o=re.mayCreate(i,r);if(o)throw new re.ErrnoError(o);if(!i.node_ops.symlink)throw new re.ErrnoError(63);return i.node_ops.symlink(i,r,e)},rename:(e,t)=>{var i,r,o=G.dirname(e),n=G.dirname(t),a=G.basename(e),s=G.basename(t);if(i=re.lookupPath(e,{parent:!0}).node,r=re.lookupPath(t,{parent:!0}).node,!i||!r)throw new re.ErrnoError(44);if(i.mount!==r.mount)throw new re.ErrnoError(75);var l,c=re.lookupNode(i,a),d=z.relative(e,n);if("."!==d.charAt(0))throw new re.ErrnoError(28);if("."!==(d=z.relative(t,o)).charAt(0))throw new re.ErrnoError(55);try{l=re.lookupNode(r,s)}catch(p){}if(c!==l){var u=re.isDir(c.mode),h=re.mayDelete(i,a,u);if(h)throw new re.ErrnoError(h);if(h=l?re.mayDelete(r,s,u):re.mayCreate(r,s))throw new re.ErrnoError(h);if(!i.node_ops.rename)throw new re.ErrnoError(63);if(re.isMountpoint(c)||l&&re.isMountpoint(l))throw new re.ErrnoError(10);if(r!==i&&(h=re.nodePermissions(i,"w")))throw new re.ErrnoError(h);re.hashRemoveNode(c);try{i.node_ops.rename(c,r,s)}catch(p){throw p}finally{re.hashAddNode(c)}}},rmdir:e=>{var t=re.lookupPath(e,{parent:!0}).node,i=G.basename(e),r=re.lookupNode(t,i),o=re.mayDelete(t,i,!0);if(o)throw new re.ErrnoError(o);if(!t.node_ops.rmdir)throw new re.ErrnoError(63);if(re.isMountpoint(r))throw new re.ErrnoError(10);t.node_ops.rmdir(t,i),re.destroyNode(r)},readdir:e=>{var t=re.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new re.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=re.lookupPath(e,{parent:!0}).node;if(!t)throw new re.ErrnoError(44);var i=G.basename(e),r=re.lookupNode(t,i),o=re.mayDelete(t,i,!1);if(o)throw new re.ErrnoError(o);if(!t.node_ops.unlink)throw new re.ErrnoError(63);if(re.isMountpoint(r))throw new re.ErrnoError(10);t.node_ops.unlink(t,i),re.destroyNode(r)},readlink:e=>{var t=re.lookupPath(e).node;if(!t)throw new re.ErrnoError(44);if(!t.node_ops.readlink)throw new re.ErrnoError(28);return z.resolve(re.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var i=re.lookupPath(e,{follow:!t}).node;if(!i)throw new re.ErrnoError(44);if(!i.node_ops.getattr)throw new re.ErrnoError(63);return i.node_ops.getattr(i)},lstat:e=>re.stat(e,!0),chmod:(e,t,i)=>{var r;if(!(r="string"==typeof e?re.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new re.ErrnoError(63);r.node_ops.setattr(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})},lchmod:(e,t)=>{re.chmod(e,t,!0)},fchmod:(e,t)=>{var i=re.getStreamChecked(e);re.chmod(i.node,t)},chown:(e,t,i,r)=>{var o;if(!(o="string"==typeof e?re.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new re.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,t,i)=>{re.chown(e,t,i,!0)},fchown:(e,t,i)=>{var r=re.getStreamChecked(e);re.chown(r.node,t,i)},truncate:(e,t)=>{if(t<0)throw new re.ErrnoError(28);var i;if(!(i="string"==typeof e?re.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new re.ErrnoError(63);if(re.isDir(i.mode))throw new re.ErrnoError(31);if(!re.isFile(i.mode))throw new re.ErrnoError(28);var r=re.nodePermissions(i,"w");if(r)throw new re.ErrnoError(r);i.node_ops.setattr(i,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var i=re.getStreamChecked(e);if(!(2097155&i.flags))throw new re.ErrnoError(28);re.truncate(i.node,t)},utime:(e,t,i)=>{var r=re.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,i)})},open:(e,t,i)=>{if(""===e)throw new re.ErrnoError(44);var o;if(i=void 0===i?438:i,i=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&i|32768:0,"object"==typeof e)o=e;else{e=G.normalize(e);try{o=re.lookupPath(e,{follow:!(131072&t)}).node}catch(l){}}var n=!1;if(64&t)if(o){if(128&t)throw new re.ErrnoError(20)}else o=re.mknod(e,i,0),n=!0;if(!o)throw new re.ErrnoError(44);if(re.isChrdev(o.mode)&&(t&=-513),65536&t&&!re.isDir(o.mode))throw new re.ErrnoError(54);if(!n){var a=re.mayOpen(o,t);if(a)throw new re.ErrnoError(a)}512&t&&!n&&re.truncate(o,0),t&=-131713;var s=re.createStream({node:o,path:re.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),!r.logReadFiles||1&t||(re.readFiles||(re.readFiles={}),e in re.readFiles||(re.readFiles[e]=1)),s},close:e=>{if(re.isClosed(e))throw new re.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{re.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,i)=>{if(re.isClosed(e))throw new re.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new re.ErrnoError(70);if(0!=i&&1!=i&&2!=i)throw new re.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,i),e.ungotten=[],e.position},read:(e,t,i,r,o)=>{if(r<0||o<0)throw new re.ErrnoError(28);if(re.isClosed(e))throw new re.ErrnoError(8);if(1==(2097155&e.flags))throw new re.ErrnoError(8);if(re.isDir(e.node.mode))throw new re.ErrnoError(31);if(!e.stream_ops.read)throw new re.ErrnoError(28);var n=void 0!==o;if(n){if(!e.seekable)throw new re.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,t,i,r,o);return n||(e.position+=a),a},write:(e,t,i,r,o,n)=>{if(r<0||o<0)throw new re.ErrnoError(28);if(re.isClosed(e))throw new re.ErrnoError(8);if(!(2097155&e.flags))throw new re.ErrnoError(8);if(re.isDir(e.node.mode))throw new re.ErrnoError(31);if(!e.stream_ops.write)throw new re.ErrnoError(28);e.seekable&&1024&e.flags&&re.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new re.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,i,r,o,n);return a||(e.position+=s),s},allocate:(e,t,i)=>{if(re.isClosed(e))throw new re.ErrnoError(8);if(t<0||i<=0)throw new re.ErrnoError(28);if(!(2097155&e.flags))throw new re.ErrnoError(8);if(!re.isFile(e.node.mode)&&!re.isDir(e.node.mode))throw new re.ErrnoError(43);if(!e.stream_ops.allocate)throw new re.ErrnoError(138);e.stream_ops.allocate(e,t,i)},mmap:(e,t,i,r,o)=>{if(2&r&&!(2&o)&&2!=(2097155&e.flags))throw new re.ErrnoError(2);if(1==(2097155&e.flags))throw new re.ErrnoError(2);if(!e.stream_ops.mmap)throw new re.ErrnoError(43);return e.stream_ops.mmap(e,t,i,r,o)},msync:(e,t,i,r,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,i,r,o):0,munmap:e=>0,ioctl:(e,t,i)=>{if(!e.stream_ops.ioctl)throw new re.ErrnoError(59);return e.stream_ops.ioctl(e,t,i)},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 i,r=re.open(e,t.flags),o=re.stat(e).size,n=new Uint8Array(o);return re.read(r,n,0,o,0),"utf8"===t.encoding?i=q(n,0):"binary"===t.encoding&&(i=n),re.close(r),i},writeFile:function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};i.flags=i.flags||577;var r=re.open(e,i.flags,i.mode);if("string"==typeof t){var o=new Uint8Array(J(t)+1),n=X(t,o,0,o.length);re.write(r,o,0,n,void 0,i.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");re.write(r,t,0,t.byteLength,void 0,i.canOwn)}re.close(r)},cwd:()=>re.currentPath,chdir:e=>{var t=re.lookupPath(e,{follow:!0});if(null===t.node)throw new re.ErrnoError(44);if(!re.isDir(t.node.mode))throw new re.ErrnoError(54);var i=re.nodePermissions(t.node,"x");if(i)throw new re.ErrnoError(i);re.currentPath=t.path},createDefaultDirectories:()=>{re.mkdir("/tmp"),re.mkdir("/home"),re.mkdir("/home/web_user")},createDefaultDevices:()=>{re.mkdir("/dev"),re.registerDevice(re.makedev(1,3),{read:()=>0,write:(e,t,i,r,o)=>r}),re.mkdev("/dev/null",re.makedev(1,3)),$.register(re.makedev(5,0),$.default_tty_ops),$.register(re.makedev(6,0),$.default_tty1_ops),re.mkdev("/dev/tty",re.makedev(5,0)),re.mkdev("/dev/tty1",re.makedev(6,0));var e=new Uint8Array(1024),t=0,i=()=>(0===t&&(t=j(e).byteLength),e[--t]);re.createDevice("/dev","random",i),re.createDevice("/dev","urandom",i),re.mkdir("/dev/shm"),re.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{re.mkdir("/proc");var e=re.mkdir("/proc/self");re.mkdir("/proc/self/fd"),re.mount({mount:()=>{var t=re.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var i=+t,r=re.getStreamChecked(i),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{r.stdin?re.createDevice("/dev","stdin",r.stdin):re.symlink("/dev/tty","/dev/stdin"),r.stdout?re.createDevice("/dev","stdout",null,r.stdout):re.symlink("/dev/tty","/dev/stdout"),r.stderr?re.createDevice("/dev","stderr",null,r.stderr):re.symlink("/dev/tty1","/dev/stderr"),re.open("/dev/stdin",0),re.open("/dev/stdout",1),re.open("/dev/stderr",1)},ensureErrnoError:()=>{re.ErrnoError||(re.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},re.ErrnoError.prototype=new Error,re.ErrnoError.prototype.constructor=re.ErrnoError,[44].forEach((e=>{re.genericErrors[e]=new re.ErrnoError(e),re.genericErrors[e].stack="<generic error, no stack>"})))},staticInit:()=>{re.ensureErrnoError(),re.nameTable=new Array(4096),re.mount(ee,{},"/"),re.createDefaultDirectories(),re.createDefaultDevices(),re.createSpecialDirectories(),re.filesystems={MEMFS:ee}},init:(e,t,i)=>{re.init.initialized=!0,re.ensureErrnoError(),r.stdin=e||r.stdin,r.stdout=t||r.stdout,r.stderr=i||r.stderr,re.createStandardStreams()},quit:()=>{re.init.initialized=!1;for(var e=0;e<re.streams.length;e++){var t=re.streams[e];t&&re.close(t)}},findObject:(e,t)=>{var i=re.analyzePath(e,t);return i.exists?i.object:null},analyzePath:(e,t)=>{try{e=(r=re.lookupPath(e,{follow:!t})).path}catch(o){}var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var r=re.lookupPath(e,{parent:!0});i.parentExists=!0,i.parentPath=r.path,i.parentObject=r.node,i.name=G.basename(e),r=re.lookupPath(e,{follow:!t}),i.exists=!0,i.path=r.path,i.object=r.node,i.name=r.node.name,i.isRoot="/"===r.path}catch(o){i.error=o.errno}return i},createPath:(e,t,i,r)=>{e="string"==typeof e?e:re.getPath(e);for(var o=t.split("/").reverse();o.length;){var n=o.pop();if(n){var a=G.join2(e,n);try{re.mkdir(a)}catch(s){}e=a}}return a},createFile:(e,t,i,r,o)=>{var n=G.join2("string"==typeof e?e:re.getPath(e),t),a=ie(r,o);return re.create(n,a)},createDataFile:(e,t,i,r,o,n)=>{var a=t;e&&(e="string"==typeof e?e:re.getPath(e),a=t?G.join2(e,t):e);var s=ie(r,o),l=re.create(a,s);if(i){if("string"==typeof i){for(var c=new Array(i.length),d=0,u=i.length;d<u;++d)c[d]=i.charCodeAt(d);i=c}re.chmod(l,146|s);var h=re.open(l,577);re.write(h,i,0,i.length,0,n),re.close(h),re.chmod(l,s)}return l},createDevice:(e,t,i,r)=>{var o=G.join2("string"==typeof e?e:re.getPath(e),t),n=ie(!!i,!!r);re.createDevice.major||(re.createDevice.major=64);var a=re.makedev(re.createDevice.major++,0);return re.registerDevice(a,{open:e=>{e.seekable=!1},close:e=>{r&&r.buffer&&r.buffer.length&&r(10)},read:(e,t,r,o,n)=>{for(var a=0,s=0;s<o;s++){var l;try{l=i()}catch(c){throw new re.ErrnoError(29)}if(void 0===l&&0===a)throw new re.ErrnoError(6);if(null==l)break;a++,t[r+s]=l}return a&&(e.node.timestamp=Date.now()),a},write:(e,t,i,o,n)=>{for(var a=0;a<o;a++)try{r(t[i+a])}catch(s){throw new re.ErrnoError(29)}return o&&(e.node.timestamp=Date.now()),a}}),re.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=Q(o(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new re.ErrnoError(29)}},createLazyFile:(e,t,i,r,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,i=e/this.chunkSize|0;return this.getter(i)[t]}},n.prototype.setDataGetter=function(e){this.getter=e},n.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",i,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+i+". Status: "+e.status);var t,r=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=r);var s=this;s.setDataGetter((e=>{var t=e*a,o=(e+1)*a-1;if(o=Math.min(o,r-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>r-1)throw new Error("only "+r+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",i,!1),r!==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 "+i+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):Q(o.responseText||"",!0)})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!n&&r||(a=r=1,r=this.getter(0).length,a=r,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=r,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:i};var l=re.createFile(e,t,s,r,o);s.contents?l.contents=s.contents:s.url&&(l.contents=null,l.url=s.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,i,r,o){var n=e.node.contents;if(o>=n.length)return 0;var a=Math.min(n.length-o,r);if(n.slice)for(var s=0;s<a;s++)t[i+s]=n[o+s];else for(s=0;s<a;s++)t[i+s]=n.get(o+s);return a}return Object.keys(l.stream_ops).forEach((e=>{var t=l.stream_ops[e];c[e]=function(){return re.forceLoadFile(l),t.apply(null,arguments)}})),c.read=(e,t,i,r,o)=>(re.forceLoadFile(l),u(e,t,i,r,o)),c.mmap=(e,t,i,r,o)=>{re.forceLoadFile(l);var n=Z();if(!n)throw new re.ErrnoError(48);return u(e,_,n,t,i),{ptr:n,allocated:!0}},l.stream_ops=c,l}},oe=(e,t)=>e?q(g,e,t):"",ne={DEFAULT_POLLMASK:5,calculateAt:function(e,t,i){if(G.isAbs(t))return t;var r;if(r=-100===e?re.cwd():ne.getStreamFromFD(e).path,0==t.length){if(!i)throw new re.ErrnoError(44);return r}return G.join2(r,t)},doStat:function(e,t,i){try{var r=e(t)}catch(s){if(s&&s.node&&G.normalize(t)!==G.normalize(re.getPath(s.node)))return-54;throw s}y[i>>2]=r.dev,y[i+4>>2]=r.mode,T[i+8>>2]=r.nlink,y[i+12>>2]=r.uid,y[i+16>>2]=r.gid,y[i+20>>2]=r.rdev,C=[r.size>>>0,(w=r.size,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[i+24>>2]=C[0],y[i+28>>2]=C[1],y[i+32>>2]=4096,y[i+36>>2]=r.blocks;var o=r.atime.getTime(),n=r.mtime.getTime(),a=r.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[i+40>>2]=C[0],y[i+44>>2]=C[1],T[i+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[i+56>>2]=C[0],y[i+60>>2]=C[1],T[i+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[i+72>>2]=C[0],y[i+76>>2]=C[1],T[i+80>>2]=a%1e3*1e3,C=[r.ino>>>0,(w=r.ino,+Math.abs(w)>=1?w>0?+Math.floor(w/4294967296)>>>0:~~+Math.ceil((w-+(~~w>>>0))/4294967296)>>>0:0)],y[i+88>>2]=C[0],y[i+92>>2]=C[1],0},doMsync:function(e,t,i,r,o){if(!re.isFile(t.node.mode))throw new re.ErrnoError(43);if(2&r)return 0;var n=g.slice(e,e+i);re.msync(t,n,o,i,r)},varargs:void 0,get:()=>(ne.varargs+=4,y[ne.varargs-4>>2]),getStr:e=>oe(e),getStreamFromFD:function(e){return re.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 le(e){for(var t="",i=e;g[i];)t+=se[g[i++]];return t}var ce={},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,i){function r(t){var r=i(t);r.length!==e.length&&fe("Mismatched type converter count");for(var o=0;o<e.length;++o)ge(e[o],r[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),ce.hasOwnProperty(e)||(ce[e]=[]),ce[e].push((()=>{o[t]=de[e],++a===n.length&&r(o)})))})),0===n.length&&r(o)}function ge(e,t){let i=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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var r=t.name;if(e||pe('type "'.concat(r,'" must have a positive integer typeid pointer')),de.hasOwnProperty(e)){if(i.ignoreDuplicateRegistrations)return;pe("Cannot register type '".concat(r,"' twice"))}if(de[e]=t,delete ue[e],ce.hasOwnProperty(e)){var o=ce[e];delete ce[e],o.forEach((e=>e()))}}(e,t,i)}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,i){if(t===i)return e;if(void 0===i.baseClass)return null;var r=Ie(e,t,i.baseClass);return null===r?null:i.downcast(r)}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 i={$$:t};ve.register(e,i,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,i){if(void 0===e[t].overloadTable){var r=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||pe("Function '".concat(i,"' 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[r.argCount]=r}}function Pe(e,t,i,r,o,n,a,s){this.name=e,this.constructor=t,this.instancePrototype=i,this.rawDestructor=r,this.baseClass=o,this.getActualType=n,this.upcast=a,this.downcast=s,this.pureVirtualFunctions=[]}function Le(e,t,i){for(;t!==i;)t.upcast||pe("Expected null or instance of ".concat(i.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 i=t.$$.ptrType.registeredClass;return Le(t.$$.ptr,i,this.registeredClass)}function Ue(e,t){var i;if(null===t)return this.isReference&&pe("null is not a valid ".concat(this.name)),this.isSmartPointer?(i=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,i),i):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 r=t.$$.ptrType.registeredClass;if(i=Le(t.$$.ptr,r,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?i=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:i=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)i=t.$$.smartPtr;else{var o=t.clone();i=this.rawShare(i,et.toHandle((function(){o.delete()}))),null!==e&&e.push(this.rawDestructor,i)}break;default:pe("Unsupporting sharing policy")}return i}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 i=t.$$.ptrType.registeredClass;return Le(t.$$.ptr,i,this.registeredClass)}function Fe(e){return this.fromWireType(y[e>>2])}function Be(e,t,i,r,o,n,a,s,l,c,d){this.name=e,this.registeredClass=t,this.isReference=i,this.isConst=r,this.isSmartPointer=o,this.pointeeType=n,this.sharingPolicy=a,this.rawGetPointee=s,this.rawConstructor=l,this.rawShare=c,this.rawDestructor=d,o||void 0!==t.baseClass?this.toWireType=Ue:r?(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 Ge(e,t){var i,o,n,a=(e=le(e)).includes("j")?(i=e,o=t,n=[],function(){return n.length=0,Object.assign(n,arguments),((e,t,i)=>{return e.includes("j")?(o=t,n=i,a=r["dynCall_"+e],n&&n.length?a.apply(null,[o].concat(n)):a.call(null,o)):We(t).apply(null,i);var o,n,a})(i,o,n)}):We(t);return"function"!=typeof a&&pe("unknown function pointer with signature ".concat(e,": ").concat(t)),a}var je=void 0;function ze(e){var t=St(e),i=le(t);return It(t),i}function Ke(e,t){var i=[],r={};throw t.forEach((function e(t){r[t]||de[t]||(ue[t]?ue[t].forEach(e):(i.push(t),r[t]=!0))})),new je("".concat(e,": ")+i.map(ze).join([", "]))}function qe(e,t){for(var i=[],r=0;r<e;r++)i.push(T[t+4*r>>2]);return i}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 i=Oe(e.name||"unknownFunctionName",(function(){}));i.prototype=e.prototype;var r=new i,o=e.apply(r,t);return o instanceof Object?o:r}function Xe(e,t,i,r,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!==i,l=!1,c=1;c<t.length;++c)if(null!==t[c]&&void 0===t[c].destructorFunction){l=!0;break}var d="void"!==t[0].name,u="",h="";for(c=0;c<a-2;++c)u+=(0!==c?", ":"")+"arg"+c,h+=(0!==c?", ":"")+"arg"+c+"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 }");l&&(p+="var destructors = [];\n");var m=l?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[pe,r,o,Ye,t[0],t[1]];for(s&&(p+="var thisWired = classParam.toWireType("+m+", this);\n"),c=0;c<a-2;++c)p+="var arg"+c+"Wired = argType"+c+".toWireType("+m+", arg"+c+"); // "+t[c+2].name+"\n",f.push("argType"+c),_.push(t[c+2]);if(s&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||n?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",l)p+="runDestructors(destructors);\n";else for(c=s?1:2;c<t.length;++c){var g=1===c?"thisWired":"arg"+(c-2)+"Wired";null!==t[c].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[c].name+"\n",f.push(g+"_dtor"),_.push(t[c].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),Je(Function,f).apply(null,_)}function Qe(){this.allocated=[void 0],this.freelist=[]}var $e=new Qe;function Ze(e){e>=$e.reserved&&0==--$e.get(e).refcount&&$e.free(e)}var et={toValue:e=>(e||pe("Cannot use deleted val. handle = "+e),$e.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 $e.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 it(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 rt(e,t,i){switch(t){case 0:return i?function(e){return _[e]}:function(e){return g[e]};case 1:return i?function(e){return E[e>>1]}:function(e){return v[e>>1]};case 2:return i?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 i=e,r=i>>1,o=r+t/2;!(r>=o)&&v[r];)++r;if((i=r<<1)-e>32&&at)return at.decode(g.subarray(e,i));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},lt=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<2)return 0;for(var r=t,o=(i-=2)<2*e.length?i/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-r},ct=e=>2*e.length,dt=(e,t)=>{for(var i=0,r="";!(i>=t/4);){var o=y[e+4*i>>2];if(0==o)break;if(++i,o>=65536){var n=o-65536;r+=String.fromCharCode(55296|n>>10,56320|1023&n)}else r+=String.fromCharCode(o)}return r},ut=(e,t,i)=>{if(void 0===i&&(i=2147483647),i<4)return 0;for(var r=t,o=r+i-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-r},ht=e=>{for(var t=0,i=0;i<e.length;++i){var r=e.charCodeAt(i);r>=55296&&r<=57343&&++i,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",_:l||"./this.program"};for(var t in _t)void 0===_t[t]?delete e[t]:e[t]=_t[t];var i=[];for(var t in e)i.push("".concat(t,"=").concat(e[t]));gt.strings=i}return gt.strings},Et=function(e,t,i,r){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=re.nextInode++,this.name=t,this.mode=i,this.node_ops={},this.stream_ops={},this.rdev=r};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 re.isDir(this.mode)}},isDevice:{get:function(){return re.isChrdev(this.mode)}}}),re.FSNode=Et,re.createPreloadedFile=function(e,t,i,r,o,a,s,l,c,d){var u=t?z.resolve(G.join2(e,t)):e;function h(i){function n(i){d&&d(),l||re.createDataFile(e,t,i,r,o,c),a&&a(),x()}(function(e,t,i,r){"undefined"!=typeof Browser&&Browser.init();var o=!1;return te.forEach((function(n){o||n.canHandle(t)&&(n.handle(e,t,i,r),o=!0)})),o})(i,u,n,(()=>{s&&s(),x()}))||n(i)}L(),"string"==typeof i?((e,t,i,r)=>{var o=r?"":"al ".concat(e);n(e,(i=>{var r;r='Loading data file "'.concat(e,'" failed (no arrayBuffer).'),i||U(r),t(new Uint8Array(i)),o&&x()}),(t=>{if(!i)throw'Loading data file "'.concat(e,'" failed.');i()})),o&&L()})(i,(e=>h(e)),s):h(i)},re.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);se=e}(),he=r.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},me=r.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,i=this.$$.ptr,r=e.$$.ptrType.registeredClass,o=e.$$.ptr;t.baseClass;)i=t.upcast(i),t=t.baseClass;for(;r.baseClass;)o=r.upcast(o),r=r.baseClass;return t===r&&i===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},r.getInheritedInstanceCount=function(){return Object.keys(we).length},r.getLiveInheritedInstances=function(){var e=[];for(var t in we)we.hasOwnProperty(t)&&e.push(we[t]);return e},r.flushPendingDeletes=Re,r.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 i=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!==i){if(0===i.$$.count.value)return i.$$.ptr=t,i.$$.smartPtr=e,i.clone();var r=i.clone();return this.destructor(e),r}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 l=Ie(t,this.registeredClass,n.registeredClass);return null===l?o.call(this):this.isSmartPointer?Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:l,smartPtrType:this,smartPtr:e}):Ce(n.registeredClass.instancePrototype,{ptrType:n,ptr:l})},je=r.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(Qe.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)}}),$e.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),$e.reserved=$e.allocated.length,r.count_emval_handles=function(){for(var e=0,t=$e.reserved;t<$e.allocated.length;++t)void 0!==$e.allocated[t]&&++e;return e};var vt,yt={p:function(e,t,i){throw new W(e).init(t,i),e},C:function(e,t,i){ne.varargs=i;try{var r=ne.getStreamFromFD(e);switch(t){case 0:return(o=ne.get())<0?-28:re.createStream(r,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return r.flags;case 4:var o=ne.get();return r.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===re||"ErrnoError"!==n.name)throw n;return-n.errno}},w:function(e,t,i,r){ne.varargs=r;try{t=ne.getStr(t),t=ne.calculateAt(e,t);var o=r?ne.get():0;return re.open(t,i,o).fd}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return-n.errno}},t:function(e,t,i,r,o){},n:function(e,t,i,r,o){var n=ae(i);ge(e,{name:t=le(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?r:o},argPackAdvance:8,readValueFromPointer:function(e){var r;if(1===i)r=_;else if(2===i)r=E;else{if(4!==i)throw new TypeError("Unknown boolean type size: "+t);r=y}return this.fromWireType(r[e>>n])},destructorFunction:null})},r:function(e,t,i,o,n,a,s,l,c,d,u,h,p){u=le(u),a=Ge(n,a),l&&(l=Ge(s,l)),d&&(d=Ge(c,d)),p=Ge(h,p);var m,f,_,g=ke(u);m=g,f=function(){Ke("Cannot construct ".concat(u," due to unbound types"),[o])},r.hasOwnProperty(m)?(pe("Cannot register public name '".concat(m,"' twice")),Me(r,m,m),r.hasOwnProperty(_)&&pe("Cannot register multiple overloads of a function with the same number of arguments (".concat(_,")!")),r[m].overloadTable[_]=f):r[m]=f,_e([e,t,i],o?[o]:[],(function(t){var i,n;t=t[0],n=o?(i=t.registeredClass).instancePrototype:Ne.prototype;var s=Oe(g,(function(){if(Object.getPrototypeOf(this)!==c)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)})),c=Object.create(n,{constructor:{value:s}});s.prototype=c;var h=new Pe(u,s,c,p,i,a,l,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,r.hasOwnProperty(m)||fe("Replacing nonexistant public symbol"),r[m].overloadTable,r[m]=f,r[m].argCount=_,[E,v,y]}))},q:function(e,t,i,r,o,n){var a=qe(t,i);o=Ge(r,o),_e([],[e],(function(e){var i="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(r){return r.splice(1,0,null),e.registeredClass.constructor_body[t-1]=Xe(i,r,null,o,n),[]})),[]}))},d:function(e,t,i,r,o,n,a,s,l){var c=qe(i,r);t=le(t),n=Ge(o,n),_e([],[e],(function(e){var r="".concat((e=e[0]).name,".").concat(t);function o(){Ke("Cannot call ".concat(r," due to unbound types"),c)}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===i-2?(o.argCount=i-2,o.className=e.name,d[t]=o):(Me(d,t,r),d[t].overloadTable[i-2]=o),_e([],c,(function(o){var s=Xe(r,o,e,n,a,l);return void 0===d[t].overloadTable?(s.argCount=i-2,d[t]=s):d[t].overloadTable[i-2]=s,[]})),[]}))},D:function(e,t){ge(e,{name:t=le(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,i){var r=ae(i);ge(e,{name:t=le(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:it(t,r),destructorFunction:null})},c:function(e,t,i,r,o){t=le(t);var n=ae(i),a=e=>e;if(0===r){var s=32-8*i;a=e=>e<<s>>>s}var l=t.includes("unsigned");ge(e,{name:t,fromWireType:a,toWireType:l?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:rt(t,n,0!==r),destructorFunction:null})},b:function(e,t,i){var r=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function o(e){var t=T,i=t[e>>=2],o=t[e+1];return new r(t.buffer,o,i)}ge(e,{name:i=le(i),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var i="std::string"===(t=le(t));ge(e,{name:t,fromWireType:function(e){var t,r=T[e>>2],o=e+4;if(i)for(var n=o,a=0;a<=r;++a){var s=o+a;if(a==r||0==g[s]){var l=oe(n,s-n);void 0===t?t=l:(t+="\0",t+=l),n=s+1}}else{var c=new Array(r);for(a=0;a<r;++a)c[a]=String.fromCharCode(g[o+a]);t=c.join("")}return It(e),t},toWireType:function(e,t){var r;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"),r=i&&o?J(t):t.length;var n=Tt(4+r+1),a=n+4;if(T[n>>2]=r,i&&o)X(t,g,a,r+1);else if(o)for(var s=0;s<r;++s){var l=t.charCodeAt(s);l>255&&(It(a),pe("String has UTF-16 code units that do not fit in 8 bits")),g[a+s]=l}else for(s=0;s<r;++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,i){var r,o,n,a,s;i=le(i),2===t?(r=st,o=lt,a=ct,n=()=>v,s=1):4===t&&(r=dt,o=ut,a=ht,n=()=>T,s=2),ge(e,{name:i,fromWireType:function(e){for(var i,o=T[e>>2],a=n(),l=e+4,c=0;c<=o;++c){var d=e+4+c*t;if(c==o||0==a[d>>s]){var u=r(l,d-l);void 0===i?i=u:(i+="\0",i+=u),l=d+t}}return It(e),i},toWireType:function(e,r){"string"!=typeof r&&pe("Cannot pass non-string to C++ string type ".concat(i));var n=a(r),l=Tt(4+n+t);return T[l>>2]=n>>s,o(r,l+4,n+t),null!==e&&e.push(It,l),l},argPackAdvance:8,readValueFromPointer:Fe,destructorFunction:function(e){It(e)}})},o:function(e,t){ge(e,{isVoid:!0,name:t=le(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,i,r){var o,n;(e=mt[e])(t=et.toValue(t),i=void 0===(n=pt[o=i])?le(o):n,null,r)},m:Ze,l:function(e,t){var i=function(e,t){for(var i,r,o,n=new Array(e),a=0;a<e;++a)n[a]=(i=T[t+4*a>>2],r="parameter "+a,void 0===(o=de[i])&&pe(r+" has unknown type "+ze(i)),o);return n}(e,t),r=i[0],o=r.name+"_$"+i.slice(1).map((function(e){return e.name})).join("_")+"$",n=ft[o];if(void 0!==n)return n;for(var a=["retType"],s=[r],l="",c=0;c<e-1;++c)l+=(0!==c?", ":"")+"arg"+c,a.push("argType"+c),s.push(i[1+c]);var d,u,h="return function "+ke("methodCaller_"+o)+"(handle, name, destructors, args) {\n",p=0;for(c=0;c<e-1;++c)h+=" var arg"+c+" = argType"+c+".readValueFromPointer(args"+(p?"+"+p:"")+");\n",p+=i[c+1].argPackAdvance;for(h+=" var rv = handle[name]("+l+");\n",c=0;c<e-1;++c)i[c+1].deleteObject&&(h+=" argType"+c+".deleteObject(arg"+c+");\n");return r.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,i)=>g.copyWithin(e,t,t+i),u:e=>{g.length,U("OOM")},y:(e,t)=>{var i=0;return gt().forEach((function(r,o){var n=t+i;T[e+4*o>>2]=n,((e,t)=>{for(var i=0;i<e.length;++i)_[0|t++]=e.charCodeAt(i);_[0|t]=0})(r,n),i+=r.length+1})),0},z:(e,t)=>{var i=gt();T[e>>2]=i.length;var r=0;return i.forEach((function(e){r+=e.length+1})),T[t>>2]=r,0},i:function(e){try{var t=ne.getStreamFromFD(e);return re.close(t),0}catch(i){if(void 0===re||"ErrnoError"!==i.name)throw i;return i.errno}},x:function(e,t){try{var i=ne.getStreamFromFD(e),r=i.tty?2:re.isDir(i.mode)?3:re.isLink(i.mode)?7:4;return _[0|t]=r,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===re||"ErrnoError"!==o.name)throw o;return o.errno}},B:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=re.read(e,_,a,s,r);if(l<0)return-1;if(o+=l,l<s)break;void 0!==r&&(r+=l)}return o})(ne.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return n.errno}},s:function(e,t,i,r,o){var n,a,s=(a=i)+2097152>>>0<4194305-!!(n=t)?(n>>>0)+4294967296*a:NaN;try{if(isNaN(s))return 61;var l=ne.getStreamFromFD(e);return re.llseek(l,s,r),C=[l.position>>>0,(w=l.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],l.getdents&&0===s&&0===r&&(l.getdents=null),0}catch(c){if(void 0===re||"ErrnoError"!==c.name)throw c;return c.errno}},h:function(e,t,i,r){try{var o=((e,t,i,r)=>{for(var o=0,n=0;n<i;n++){var a=T[t>>2],s=T[t+4>>2];t+=8;var l=re.write(e,_,a,s,r);if(l<0)return-1;o+=l,void 0!==r&&(r+=l)}return o})(ne.getStreamFromFD(e),t,i);return T[r>>2]=o,0}catch(n){if(void 0===re||"ErrnoError"!==n.name)throw n;return n.errno}}},Tt=(function(){var e,t,o,n,a={a:yt};function s(e,t){var i,o,n=e.exports;return i=(p=n).E.buffer,r.HEAP8=_=new Int8Array(i),r.HEAP16=E=new Int16Array(i),r.HEAP32=y=new Int32Array(i),r.HEAPU8=g=new Uint8Array(i),r.HEAPU16=v=new Uint16Array(i),r.HEAPU32=T=new Uint32Array(i),r.HEAPF32=I=new Float32Array(i),r.HEAPF64=A=new Float64Array(i),S=p.H,o=p.F,k.unshift(o),x(),n}if(L(),r.instantiateWasm)try{return r.instantiateWasm(a,s)}catch(l){f("Module.instantiateWasm callback failed with error: "+l),i(l)}(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(i)}(),e=>(Tt=p.G)(e)),It=e=>(It=p.I)(e),At=()=>(At=p.J)(),St=e=>(St=p.K)(e),Rt=(r.__embind_initialize_bindings=()=>(r.__embind_initialize_bindings=p.L)(),e=>(Rt=p.M)(e));function bt(){function e(){vt||(vt=!0,r.calledRun=!0,D||(r.noFSInit||re.init.initialized||re.init(),re.ignorePermissions=!1,H(k),t(r),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for("function"==typeof r.postRun&&(r.postRun=[r.postRun]);r.postRun.length;)e=r.postRun.shift(),O.unshift(e);var e;H(O)}()))}M>0||(function(){if(r.preRun)for("function"==typeof r.preRun&&(r.preRun=[r.preRun]);r.preRun.length;)e=r.preRun.shift(),N.unshift(e);var e;H(N)}(),M>0||(r.setStatus?(r.setStatus("Running..."),setTimeout((function(){setTimeout((function(){r.setStatus("")}),1),e()}),1)):e()))}if(r.dynCall_jiji=(e,t,i,o,n)=>(r.dynCall_jiji=p.N)(e,t,i,o,n),r._ff_h264_cabac_tables=67061,P=function e(){vt||bt(),vt||(P=e)},r.preInit)for("function"==typeof r.preInit&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return bt(),e.ready}),FH=VH,BH=class extends xH{constructor(e){super(FH,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 HH=(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.SEI_MESSAGE="267",e.USER_PAUSE_IN_PIP="268",e.USER_RESUME_IN_PIP="269",e.ENTER_PICTURE_IN_PICTURE="270",e.LEAVE_PICTURE_IN_PICTURE="271",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(HH||{}),WH="undefined"!=typeof importScripts,GH="undefined"!=typeof registerProcessor,jH="jssdk_log",zH=(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))(zH||{}),KH=Symbol(32),qH=Symbol(16),YH=Symbol(8),JH=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 function(e,t,i,r){return new(i||(i=Promise))((function(o,n){function a(e){try{l(r.next(e))}catch(t){n(t)}}function s(e){try{l(r.throw(e))}catch(t){n(t)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,s)}l((r=r.apply(e,t||[])).next())}))}(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(KH)}readU16(){return this.read(qH)}readU8(){return this.read(YH)}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===KH){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===qH){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===YH){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}};JH.U32=KH,JH.U16=qH,JH.U8=YH;function XH(e){let t=new JH;for(;e>=128;)t.malloc(1)[0]=255&e|128,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function QH(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new JH,r=t<<3;switch(typeof e){case"boolean":let o=i.malloc(2);o[0]=r,o[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(XH(e));break;case"string":i.malloc(1)[0]=2|r;let n=(new TextEncoder).encode(e);i.write(XH(n.length));let a=i.malloc(n.length);for(let e=0;e<n.length;e++)a[e]=n[e];break;case"object":let s=new JH;if(Array.isArray(e))for(let t=0;t<e.length;t++){let i=QH(e[t],t+1);i&&s.write(i)}else{let t=1;for(let i in e){let r=QH(e[i],t++);r&&s.write(r)}}0===t?s.buffer&&i.write(s.buffer):(i.malloc(1)[0]=2|r,s.buffer&&(i.write(XH(s.buffer.length)),i.write(s.buffer)))}return i.buffer||new Uint8Array(0)}var $H=class{constructor(){IH(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 ZH(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 eW(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function tW(e,t){return e[t]}function iW(e,t,i){return(new TextDecoder).decode(function(e,t,i){return e.slice(t,t+i)}(e,t,i))}var rW=0,oW=2654435769;function nW(e,t){let i=new $H,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,rW);rW=rW+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let o=(new TextEncoder).encode(r.d2);i.writeInt32(o.length+4),o&&i.writeBytes(o),i.writeByte(r.uinType);let n=(new TextEncoder).encode(r.uin);i.writeInt32(n.length+4),n.length&&i.writeBytes(n);let a=new $H;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let E=4;E<16;E++)a.writeByte(0);let s=(new TextEncoder).encode(r.reqHead.a2);a.writeInt32(s.length+4),s.length&&a.writeBytes(s);let l=(new TextEncoder).encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=(new TextEncoder).encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=(new TextEncoder).encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let u=(new TextEncoder).encode(r.reqHead.ksid);a.writeInt32(u.length+4),u.length&&a.writeBytes(u);let h=(new TextEncoder).encode(r.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,wG(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===r.encryption?f=(new TextEncoder).encode(r.uin):2===r.encryption&&(f=new Uint8Array(16)),f&&(m=function(e,t){let i=e.length,r=(i+1+2+7)%8;r&&(r=8-r);let o=new Uint8Array(i+1+2+7+r),n=0,a=new Uint8Array(8),s=new Uint8Array(8),l=new Uint8Array(8),c=0;a[0]=248&Math.floor(256*Math.random())|r,c=1;for(let u=0;u<r;u++)a[c]=255&Math.floor(256*Math.random()),c+=1;for(let u=0;u<2;)if(c<8&&(a[c]=255&Math.floor(256*Math.random()),c+=1,u+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}let d=0;for(;d<i;)if(c<8&&(a[c]=e[d],c+=1,d+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}for(let u=0;u<7;)if(c<8&&(a[c]=0,c+=1,u+=1),8===c){aW(a,t,s,l,o,n),n+=8,c=0;for(let e=0;e<8;e++)l[e]=o[n-8+e]}return o}(m,f)),i.writeBytes(m);let _=new Uint8Array(i.data),g=_.length;return _[0]=g>>>24&255,_[1]=g>>>16&255,_[2]=g>>>8&255,_[3]=255&g,_}function aW(e,t,i,r,o,n){for(let a=0;a<8;a++)e[a]^=r[a];!function(e,t,i,r){let o=eW(e,0),n=eW(e,4),a=[];for(let l=0;l<4;l++)a[l]=eW(t,4*l);let s=0;for(let l=0;l<16;l++)s+=oW,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;ZH(i,o,r),ZH(i,n,r+4)}(e,t,o,n);for(let a=0;a<8;a++)o[n+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var sW=function(){return Date.now()+0},lW=function(){let e=new Date;return e.setTime(sW()),e.toLocaleString()};function cW(e){let t=function(e){try{let t={},i=0;t.totalLength=eW(e,i),i+=4,t.version=eW(e,i),i+=4,t.encryption=tW(e,i),i+=1,t.uinType=tW(e,i),i+=1,t.uinLength=eW(e,i),i+=4,t.uin=t.uinLength>4?iW(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),o=dW(new Uint8Array(e.slice(0,8)),t),n=7&o[0],a=e.length-1-n-2-7,s=new Uint8Array(a),l=0,c=r,d=e.slice(0,8);i=8;let u=1;u+=n;for(let p=1;p<=2;)if(u<8)u++,p++;else if(8===u){let r=uW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}let h=a;for(;h>0;)if(u<8)s[l++]=o[u]^c[u],u++,h--;else if(8===u){let r=uW(e,i,c,d,o,t);c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}for(let p=1;p<=7;)if(u<8)o[u],c[u],u++,p++;else if(8===u){if(i>=e.length)break;let r=uW(e,i,c,d,o,t);if(!r.success)break;c=r.ivPreCrypt,d=r.ivCurCrypt,o=r.debiBuf,i=r.bufPos,u=0}return s}(r,new Uint8Array(16).fill(0)),t.decrypted=!0,i=0}else e=r,i=0;return t.rspHeadLength=eW(e,i),i+=4,t.seqNo=eW(e,i),i+=4,t.retCode=eW(e,i),i+=4,t.retStrLength=eW(e,i),i+=4,t.retStr=t.retStrLength?iW(e,i,t.retStrLength-4):"",i+=t.retStrLength-4,t.serviceCmdLength=eW(e,i),i+=4,t.serviceCmd=t.serviceCmdLength?iW(e,i,t.serviceCmdLength-4):"",i+=t.serviceCmdLength-4,t.cookieLength=eW(e,i),i+=4,t.cookie=t.cookieLength?iW(e,i,t.cookieLength-4):"",i+=t.cookieLength-4,t.flag=eW(e,i),i+=4,t.busiBuffLength=eW(e,i),i+=4,t.busiBuff=t.busiBuffLength?iW(e,i,t.busiBuffLength-4):"",i+=t.busiBuffLength-4,t}catch(t){}}(e);return null==t?void 0:t.busiBuff}function dW(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 o=16*oW>>>0;for(let n=0;n<16;n++)r-=(i<<4)+t[2]^i+o^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+o^(r>>>5)+t[1],i>>>=0,o-=oW,o>>>=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 uW(e,t,i,r,o,n){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),s=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=o[c]^s[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:s,debiBuf:dW(l,n),bufPos:t+8}}var hW="undefined"!=typeof TextDecoder?new TextDecoder:void 0;var pW=Object.prototype.hasOwnProperty,mW=e=>"function"==typeof e,fW=e=>void 0===e;function _W(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(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)}(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(pW.call(e,t))return!1;return!0}return!1}var gW=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:o,onRetryFailed:n,onRetrySuccess:a,context:s}=e;return function(){for(var e=arguments.length,l=new Array(e),c=0;c<e;c++)l[c]=arguments[c];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,f=(e,i)=>nw(this,null,(function*(){let c=s||this;try{let i=yield t.apply(c,l);h>0&&a&&a.call(this,h),h=0,e(i)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,i(_)},a=()=>{2!==m&&h<(mW(d)?d():d)?(h++,m=1,mW(o)&&o.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,i)}),mW(u)?u(h):u)):(t(),mW(n)&&n.call(this,_))};mW(r)?r.call(this,{error:_,retry:a,reject:i,retryFuncArgs:l,retriedCount:h}):a()}}));return new Promise(f)}},EW=class e{constructor(e){IH(this,"_parentPath"),IH(this,"userId"),IH(this,"remoteUserId"),IH(this,"id"),IH(this,"sdkAppId"),IH(this,"type"),IH(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!(e=>"boolean"==typeof e)(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new e({id:t.id,userId:fW(t.userId)?this.userId:t.userId,sdkAppId:fW(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:fW(t.type)?this.type:t.type,isLocal:fW(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:fW(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(e){let t=e.getFullId();this._parentPath!==t&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=t,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(r).concat(i?"|".concat(i):"","]")),SG.log(e,t,fW(this.userId)||_W(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)}},vW="undefined"==typeof navigator?"":navigator.userAgent,yW=e=>new RegExp(e,"i").test(vW),TW=e=>{if(yW(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=vW.match(t);if(i&&i[1])return i[1]}return""},IW=e=>{if(yW(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=vW.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},AW=/AppleWebKit\/([\d.]+)/i.exec(vW);AW&&parseFloat(AW[1]);var SW=yW("iPad"),RW="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&yW("Macintosh"),bW=yW("iPhone")&&!SW,wW=yW("iPod"),CW=bW||SW||wW||RW,DW=yW("Android");!function(){if(DW){let e=vW.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}}}();DW&&yW("webkit");var NW=yW("Firefox"),kW=TW("Firefox");IW("Firefox");var OW=yW("Edge"),MW=TW("Edge"),PW=yW("Edg"),LW=TW("Edg");IW("Edg");var xW=yW("SogouMobileBrowser"),UW=TW("SogouMobileBrowser"),VW=yW("MetaSr\\s"),FW=TW("MetaSr\\s"),BW=yW("TBS"),HW=TW("TBS"),WW=yW("XWEB"),GW=TW("XWEB");yW("MSIE\\s8\\.0");var jW=yW("MSIE\\/\\d+");!function(){if(jW){let e=/MSIE\s(\d+)\.\d/.exec(vW),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(vW)&&/rv:11.0/.test(vW)&&(t=11),t}}();var zW=yW("(micromessenger|webbrowser)"),KW=TW("MicroMessenger"),qW=!BW&&yW("MQQBrowser")&&yW("COVC"),YW=!BW&&yW("MQQBrowser")&&!yW("COVC"),JW=YW||qW?TW("MQQBrowser"):"",XW=!BW&&yW(" QQBrowser"),QW=TW(" QQBrowser"),$W=!BW&&yW("QQBrowserLite"),ZW=TW("QQBrowserLite"),eG=!BW&&yW("MQBHD"),tG=TW("MQBHD");yW("Windows"),!CW&&yW("MAC OS X"),!DW&&yW("Linux"),yW("CrOS"),yW("MicroMessenger"),yW("UCBrowser"),yW("Electron");var iG=yW("MiuiBrowser"),rG=TW("MiuiBrowser"),oG=yW("HuaweiBrowser");yW("Huawei")||yW("HUAWEI"),yW("Honor")||yW("HONOR");var nG=TW("HuaweiBrowser"),aG=yW("SamsungBrowser"),sG=TW("SamsungBrowser"),lG=yW("HeyTapBrowser"),cG=TW("HeyTapBrowser"),dG=yW("VivoBrowser"),uG=TW("VivoBrowser");yW("OpenHarmony"),TW("OpenHarmony");var hG=yW("CriOS"),pG=yW("Chrome"),mG=!OW&&!VW&&!xW&&!BW&&!WW&&!PW&&!XW&&!iG&&!oG&&!aG&&!lG&&!dG&&pG,fG=yW("HeadlessChrome");IW("Chrome");var _G=TW("Chrome");IW("Electron");var gG=!pG&&!YW&&!qW&&!$W&&!eG&&yW("Safari"),EG=TW("Version");/Android.*(wv|.0.0.0)/.test(vW);var vG=(()=>{if(RW)return EG;if(CW){let e=vW.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();Number(vG.split(".")[0]),(()=>{let e=Number(vG.split(".")[0])})(),function(){let e=new Map([[NW,["Firefox",kW]],[PW,["Edg",LW]],[mG,["Chrome",_G]],[hG,["ChiOS",TW("CriOS")]],[gG&&!hG,["Safari",EG]],[BW,["TBS",HW]],[WW,["XWEB",GW]],[zW&&bW,["WeChat",KW]],[XW,["QQ(Win)",QW]],[YW,["QQ(Mobile)",JW]],[qW,["QQ(Mobile X5)",JW]],[$W,["QQ(Mac)",ZW]],[eG,["QQ(iPad)",tG]],[iG,["MI",rG]],[oG,["HW",nG]],[aG,["Samsung",sG]],[lG,["OPPO",cG]],[dG,["VIVO",uG]],[OW,["EDGE",MW]],[xW,["SogouMobile",UW]],[VW,["Sogou",FW]]]),t="unknown",i="unknown";e.has(!0)&&([t,i]=e.get(!0))}();var yG=new(yH(AH(),1).default),TG=HH,IG=new class{constructor(){IH(this,"enable",!1),IH(this,"ssoFailCount",0),yG.on("22",(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.sso&&yG.emit("266",{enable:!0})})),yG.on("266",(e=>{let{enable:t}=e;this.enable=t}))}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&yG.emit("266",{enable:!1})}},AG=class e{constructor(){IH(this,"_isEnableUploadLog",!0),IH(this,"_localJoinedUser",new Map),IH(this,"_queue",[]),IH(this,"_timeoutId",-1),IH(this,"_logLevel",1),IH(this,"_logLevelToUpload",2),WH||GH||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){yG.on(TG.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;null!=(i=null==t?void 0:t.config)&&i.logLevelToUpload&&zH[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),yG.on(TG.JOIN_START,(e=>{let{params:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),yG.on(TG.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:o}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:o,logs:[i]})}));else if(wG(i.userId)&&CG(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 nw(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:o}=t[e],n={timestamp:lW(),sdkAppId:String(r),userId:i,version:"5.0.0",log:o.map((e=>e.log)).join("\n")},a=JSON.stringify(n),s=IG.enable?DG(n,2002,r):a;yield this.uploadLogWithRetry(s,r,s instanceof Uint8Array,a),o.forEach((e=>e.uploaded=!0))}}catch(cM){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t,i,r){return gW({retryFunction:()=>function(e){let{url:t,body:i,method:r="POST",timeout:o,priority:n}=e;return new Promise(((e,a)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:n}).then((e=>e.clone().json().then((e=>({data:e})),(()=>e.arrayBuffer().then((e=>({data:cW(new Uint8Array(e))||(hW?hW.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(hM){e({data:s.response})}else a({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=o||5e3,s.open(r,t,!0),s.send(i)}))}({url:RG(t,jH),body:e,timeout:5e3,priority:"low"}).then((e=>{i&&"ok"!==e.data&&(IG.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(sW()),"[".concat(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)}(t),"] <").concat(zH[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){bG(zH[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(wG(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Sw){return""}}addLogToQueue(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=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:r,sdkAppId:o,forAllJoinedClients:i};yG.emit(TG.LOG,{log:n}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(n)}log(t,i){let r=!(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(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,o,n),t<this._logLevel)return;let s=(null==(a=zH[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",...i):console[s](...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){if(e.parent instanceof EW){let t=e,{parent:i}=t,r=((e,t)=>{var i={};for(var r in e)fH.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&pH)for(var r of pH(e))t.indexOf(r)<0&&_H.call(e,r)&&(i[r]=e[r]);return i})(t,["parent"]),o=new EW(r);return o.bindParent(i),o}return new EW(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;zH[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};IH(AG,"PRINT_LOG_TAG",!(CW||DW||fG));var SG=new AG,RG=function(e,t){let i;return i=(e=>Number(e)<14e8)(e)?"https://apisgp.my-imcloud.com":"https://yun.tim.qq.com","".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(Math.floor(Math.random()*Jb(2,31)),"&sdkappid=").concat(e,"&cmdtype=").concat(t)},bG=e=>void 0===e,wG=e=>"string"==typeof e,CG=e=>"number"==typeof e;function DG(e,t,i,r){try{let o=function(e,t,i,r){let o={data:e,random:Math.floor(2147483648*Math.random()),sdkAppId:i};return bG(r)||(o=vH(EH({},o),{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(o)}}}(e,t,i,r);return nW(QH(o),i)}catch(cM){return JSON.stringify(e)}}var NG=class e{constructor(e){this.core=e,IH(this,"contextMap",new Map),IH(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 i;switch(e){case"wasm":let e=(null==(i=this.core.assetsPath)?void 0:i.replace(/\/+$/,""))||".";return new BH(vH(EH({},t),{wasmPath:"".concat(e,"/videodec.wasm")}));case"webCodecs":return new PH;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:i}=e;var r;return(null==(r=this.decodeProcessorMap.get(i))?void 0:r({frame:t,track:i}))||t},type:3})}decode(e){let{pipe:t,take:i,subscribe:r}=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(vH(EH({},e),{createDecoder:this.createDecoder}));return t(s.trackDoneOB,i(1),r((()=>{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 i=(performance&&performance.now?Math.floor(performance.now()):Date.now())-e.startPerformanceTime,{renderFreezeTotal:r,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):"");i&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(r/i*100),split:1,max:100}),n+=" RENDER_FREEZE_RATE: ".concat(Math.floor(r/i*100),"%")),i&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(o/i*100),split:1,max:100}),n+=" DATA_FREEZE_RATE: ".concat(Math.floor(o/i*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(vH(EH({},e),{createDecoder:this.createDecoder})))):t.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(e,t){let i=this.core.room.badCaseDetector.getDataFreezeMap().get("".concat(e.userId,"_").concat(e.streamType)),r=this.core.room.badCaseDetector.getRenderFreezeDuration("".concat(e.userId,"_").concat(e.streamType)),o=0;return i&&i.durationItemList.forEach((e=>{e.startTime>t.startPerformanceTime&&(o+=e.getDuration())})),{renderFreezeTotal:r,dataFreezeTotal:o}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};IH(NG,"Name","TRTCVideoDecoder");var kG=NG,OG=tw(aw());function MG(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return OU(((e,o)=>{let n=new WeakMap;return JO.on(QO.ROOM_DESTROY,(e=>{let{room:t}=e;return n.delete(t)})),function(){let a=n.get(this);for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];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),r&&(a.totalSizeInSecond+=r(...l)),0!==a.timestamp&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=t||a.totalSizeInSecond>i))throw new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=t,isSize:a.totalSizeInSecond>i,name:o,timesInSecond:t,maxSizeInSecond:i}})});a.callCountInSecond++,e.call(this,...l)}}))}var PG,LG=!0,xG={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"},UG={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},VG=((PG=VG||{})[PG.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",PG[PG.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",PG[PG.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",PG[PG.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",PG[PG.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",PG[PG.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",PG[PG.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",PG[PG.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",PG[PG.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",PG[PG.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",PG[PG.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",PG[PG.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",PG[PG.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",PG[PG.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",PG[PG.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",PG[PG.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",PG[PG.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",PG[PG.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",PG[PG.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",PG[PG.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",PG[PG.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",PG[PG.INVALID_OPERATION=5100]="INVALID_OPERATION",PG[PG.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",PG[PG.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",PG[PG.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",PG[PG.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",PG[PG.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",PG[PG.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",PG[PG.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",PG[PG.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",PG[PG.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",PG[PG.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",PG[PG.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",PG[PG.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",PG[PG.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",PG[PG.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",PG[PG.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",PG[PG.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",PG[PG.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",PG[PG.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",PG[PG.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",PG[PG.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",PG[PG.DEVICE_ERROR=5300]="DEVICE_ERROR",PG[PG.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",PG[PG.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",PG[PG.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",PG[PG.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",PG[PG.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",PG[PG.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",PG[PG.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",PG[PG.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",PG[PG.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",PG[PG.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",PG[PG.SERVER_ERROR=5400]="SERVER_ERROR",PG[PG.NEED_TO_BUY=5401]="NEED_TO_BUY",PG[PG.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",PG[PG.OPERATION_FAILED=5500]="OPERATION_FAILED",PG[PG.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",PG[PG.REJOIN_FAILED=5502]="REJOIN_FAILED",PG[PG.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",PG[PG.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",PG[PG.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",PG[PG.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",PG[PG.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",PG[PG.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",PG[PG.OPERATION_ABORT=5998]="OPERATION_ABORT",PG[PG.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",PG);var FG=$b(Qb({},hP),{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:o}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(o,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(n,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' cannot be '").concat(o,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:o}=e,n="".concat(t||i.name),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(n,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(WD(o),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:o}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(o,".")},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=BG(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=BG(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=BG(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=BG(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=BG(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=BG(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=BG(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 BG(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var HG=class e extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:o,fnName:n="",originError:a,data:s}=e;var l;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:o=!1}=e,a="",s=VG[i];try{t=FG[s]}catch(n){t=FG.UNKNOWN_ERROR}return GD(t)?a=t(r):zD(t)&&(a=t),r.fnName&&!a.includes(r.fnName)&&("."!==a[a.length-1]&&(a+="."),a+=" thrown from ".concat(r.fnName,"()")),o&&(a+=" doc:"),a}({code:t===UG.SERVER_ERROR?t:i||t,params:Qb({fnName:n,error:a},o)}),super(c),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=VG[t],this.code=t,this.extraCode=i,this.functionName=n,this.originError=a,this.message=c,this.data=s,5302===this.extraCode&&null!=(l=this.originError)&&l.message.includes("system")&&(this.handler=()=>{let e=document.createElement("a");Gk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):jk&&(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 o=t;if(t instanceof mw){let{stack:n}=t,a={code:UG.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case hw.INVALID_PARAMETER:a.code=UG.INVALID_PARAMETER,a.message=t.message;break;case hw.INVALID_OPERATION:a.code=UG.INVALID_OPERATION;break;case hw.NOT_SUPPORTED:case hw.NOT_SUPPORTED_H264:a.code=UG.ENV_NOT_SUPPORTED,t.getCode()===hw.NOT_SUPPORTED_H264&&(a.extraCode=t.message.includes(hP.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case hw.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case hw.SERVER_TIMEOUT:case hw.SWITCH_ROLE_FAILED:case hw.SWITCH_ROOM_FAILED:a.code=UG.SERVER_ERROR,a.extraCode=t.getExtraCode();break;case hw.API_CALL_ABORTED:a.code=UG.OPERATION_ABORT;break;case hw.DEVICE_NOT_FOUND:case hw.DEVICE_AUTO_RECOVER_FAILED:case hw.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 hw.VIDEO_ENCODE_FAILED:a.extraCode=5505;case hw.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=UG.OPERATION_FAILED;break;case hw.UNKNOWN:break;default:a.code=UG.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:UG.UNKNOWN_ERROR,fnName:i,originError:t})}return o}};var WG=HG;function GG(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function jG(e){return e===xG.QOS_PREFERENCE_CLEAR?"detail":e===xG.QOS_PREFERENCE_SMOOTH?"motion":""}function zG(e,t){let i=t?$w:Qw;return qN(e)?Qb(Qb({},i),e):Xw[e]?Xw[e]:i}var KG={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}}},qG={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}}},YG={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(zD(e)&&!document.getElementById(e))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},JG={name:"userId",required:!0,type:"string"},XG={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 QG(e,t){if(!e)throw new WG({code:UG.INVALID_OPERATION,extraCode:5101,fnName:t})}function $G(e,t,i){if(!e)throw new WG({code:UG.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function ZG(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function ej(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function tj(e){var t;if(null==(t=null==e?void 0:e.option)||!t.small)return;if(!tL())return eM.warn("small stream is not supported"),void delete e.option.small;let i=zG(e.option.profile),r=zG(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:(eM.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 ij={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 WG({code:UG.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(zD(e.roomId))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});ZG(e.roomId,i,t)}else{if(!e.strRoomId)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5015,fnName:i});ej(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:YG,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:KG},validate(e){var t,i;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201});null!=(i=null==e?void 0:e.option)&&i.small&&tj(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:$b(Qb({},YG),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:KG},validate(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&tj(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:XG},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:XG}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:YG,publish:{type:"boolean"},option:qG},validate(e,t,i,r,o){var n;if(null==(n=null==e?void 0:e.option)||!n.videoTrack){if(xP())throw new WG({code:UG.ENV_NOT_SUPPORTED,extraCode:5201});if(!GP())throw new WG({code:UG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:YG,publish:{type:"boolean"},option:qG}},muteRemoteAudio:[JG,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[JG,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:YG,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){QG(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if($G(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new WG({code:UG.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:$b(Qb({},YG),{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){QG(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if($G(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new WG({code:UG.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&&jD(e.streamType))throw new WG({code:UG.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){QG(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(!EL)throw new WG({code:UG.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new WG({code:UG.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});QG(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 WG({code:UG.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 WG({code:UG.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(QG(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new WG({code:UG.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(QG(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new WG({code:UG.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 WG({code:UG.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)ZG(e.roomId,i,t);else{if(!e.strRoomId)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5015,fnName:i});ej(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}}}},rj={TRTC:ij},oj=class extends Error{};function nj(e,t){let i=pN(e);for(let r=0;r<t.length;r++)hN(i[r],t[r]);return i}function aj(e){this._resolve=Promise.resolve(e)}function sj(e){this._reject=Promise.reject(e)}var lj=class e{constructor(t,i){this.instance=t,this.group=i,rw(this,"started",!1),rw(this,"ops",[]),rw(this,"startSame",(()=>!0)),rw(this,"mergeUpdate",nj);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),o=[];return r&&r.forEach(((e,t)=>{i.test(t)&&o.push(e)})),o}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},o=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new oj("start failed")),null==(r=this.currentOp)||r.action(),t},n={type:e,action:()=>t(...n.args).then(r,o),args:i,resolve:aj,reject:sj};try{switch(this.state){case 1:if(0===e)throw new oj("already started");break;case 4:if(2===e)throw new oj("not started");break;default:return this.cacheOp(n)}}catch(dM){return Promise.reject(dM)}return this.ops.push(n),n.promise=t(...n.args).then(r,o)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new oj("already start");break;case 3:switch(e.type){case 2:throw new oj("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new oj("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new oj("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 oj("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new oj("start not allowed after update");case 0:throw new oj("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new oj("keep start")),new oj("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}};rw(lj,"instances",new WeakMap);var cj=lj,dj=new WeakMap,uj=(e,t)=>{if(t instanceof oj){let{stack:i}=t;t=new WG({code:UG.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function hj(e,t){return OU(((i,r)=>function(){for(var o=arguments.length,n=new Array(o),a=0;a<o;a++)n[a]=arguments[a];let s=cj.get(this,"string"==typeof e?e:e.call(this,...n));return s?(t&&(s.startSame=t.bind(this)),s.action(0,i.bind(this),n).catch(uj.bind(null,r))):i.apply(this,n)}))}function pj(e,t){let{merge:i,debounce:r}=t||{};return OU(((t,o)=>function(){for(var n=arguments.length,a=new Array(n),s=0;s<n;s++)a[s]=arguments[s];let l=cj.get(this,"string"==typeof e?e:e.call(this,...a));if(!l)return t.apply(this,a);if(i&&(l.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,a)){let{delay:e,getKey:i}=r;return new Promise(((r,n)=>{var s,c;let d=null==(s=dj.get(this))?void 0:s.get(i(...a));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===l.state||4===l.state)return r();l.action(2,t.bind(this),a).catch(uj.bind(null,o)).then(r,n)}),e);dj.has(this)?null==(c=dj.get(this))||c.set(i(...a),{timeoutId:u,resolve:r}):dj.set(this,new Map([[i(...a),{timeoutId:u,resolve:r}]]))}))}return l.action(2,t.bind(this),a).catch(uj.bind(null,o))}))}function mj(e){return OU(((t,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a="function"==typeof e?e.call(this,...o):e;if(a instanceof RegExp)return Promise.all(cj.gets(this,a).map((e=>e.action(3,(()=>Promise.resolve()),o)))).then((()=>t.call(this,...o)));let s=cj.get(this,a);return s?s.action(3,t.bind(this),o).catch(uj.bind(null,i)):t.apply(this,o)}))}function fj(){return function(e,t,i){return e.prototype[t]=function(){let e=this._log||console,i='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(Lw,"/en/TRTC.html#.").concat(t);e.warn(i)},i}}var _j={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"},gj=new Set([_j.AUDIO_VOLUME,_j.AUDIO_FRAME,_j.NETWORK_QUALITY,_j.STATISTICS,_j.SEI_MESSAGE,_j.CUSTOM_MESSAGE,_j.LAYER_DATA]),Ej={};ew(Ej,{ScheduleRequestType:()=>wj,getAbilityConfig:()=>Dj,getScheduleDomain:()=>Nj,isNeedToSchedule:()=>Ij,scheduleProxy:()=>Rj,sendScheduleRequest:()=>Sj,setIsNeedToSchedule:()=>Aj,setScheduleProxy:()=>bj});var vj=null,yj=0,Tj=1728e5,Ij=!0;function Aj(e){qD(e)&&e!==Ij&&(Ij=e,eM.info("setIsNeedToSchedule ".concat(e)),e||(yj=Date.now()+Tj))}function Sj(e){return nw(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:o,userSig:n,version:a,frameWorkType:s,role:l,latencyLevel:c}=e;return function*(){var e;if(!Ij&&vj&&yj>Date.now())return{isCached:!0,result:vj};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(o)),u.append("sdkVersion",a),u.append("userSig",String(n));let h=(null==(e=yield UO())?void 0:e.model)||BO();h&&u.append("model",h);let p=zO();p&&u.append("osString",p),l&&u.append("role",String(l)),c&&u.append("latencyLevel",String(c)),s&&u.append("frameWorkType",String(s));let m=oN(),f=yield function(e,t,i){return new Promise(((r,o)=>{let n=null;rN([Oj((e=>t.count[0]=e+1),(e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[0]=r.message,n||(a>=1&&(s[0]=Cj(i,"config",eC.MAIN,!0)),o())}))(Cj(i,"config",eC.MAIN),e,{get timeout(){return 1e3*BD(2+t.count[0])}}),Oj((e=>t.count[1]=e+1),(e=>{let{error:r,retry:o,retriedCount:a,retryFuncArgs:s}=e;t.msg[1]=r.message,n||(a>=2&&(s[0]=Cj(i,"config",eC.BACKUP,!0)),o())}))(Cj(i,"config",eC.BACKUP),e,{get timeout(){return 1e3*BD(2+t.count[1])}})]).then((e=>{n=e,r(n)})).catch(o)}))}(u,d,i);f.config&&(f.config.loggerDomain&&Nw(f.config.loggerDomain),qD(f.config.scheduleCache)&&Aj(!f.config.scheduleCache)),d.delta=oN()-m;let _=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),n=Cj(e,"config",eC.MAIN),a=Cj(e,"config",eC.BACKUP);for(let e of o)if(e.startTime>=i&&(e.name===n||e.name===a)&&e.transferSize>0){let i=e.name===n?eC.MAIN:eC.BACKUP,o=Math.round(e.duration),a=Math.round(e.domainLookupStart-e.startTime),s=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,l=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,c=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=[c,d,u,h,p];rx.uploadEvent({log:"stat-schedule-net:".concat(o,"(").concat(a,"(").concat(s,"->").concat(l,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=$b(Qb({},r),{totalCost:o,local:a,dns:c,tcp:u,tls:d,request:h,response:p});break}}catch(n){eM.error("getScheduleDetailCost error",n)}return r}(Number(i),t,m);return vj=f,{isCached:!1,result:f,detailCost:_}}catch(nM){let t=JD(nM)?nM[0]:nM,i=KD(t.code)?t.code:0,r="schedule failed".concat(t.message?": ".concat(t.message):""),o=new mw({code:hw.SCHEDULE_FAILED,extraCode:i,message:fP({key:uP.JOIN_ROOM_FAILED,data:{error:r,code:i}})});throw eM.error(r,i),o}}()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(GC).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),JO.on("28",(()=>Aj(!0))),JO.on("63",(()=>Aj(!0))),JO.on("84",(()=>Aj(!0))),JO.on("201",(e=>{"RECONNECTING"===e.state&&Aj(!0)})),JO.on("202",(e=>{"RECONNECTING"===e.state&&Aj(!0)}));var Rj={main:"",backup:""};function bj(e){JD(e)?(Rj.main=e[0],Rj.backup=e[1]):Rj.main=e}var wj=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(wj||{});function Cj(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:eC.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(Rj[i]||Nj(e,i,r),"/api/v1/").concat(t)}function Dj(e,t,i){let r=Cj(e,t),o=Cj(e,t,eC.BACKUP),n=new URLSearchParams(i).toString(),a=fetch("".concat(r,"?").concat(n)).then((e=>e.json())),s=fetch("".concat(o,"?").concat(n)).then((e=>e.json()));return rN([a,s])}function Nj(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=AD(e)?r?i===eC.MAIN?GC.MAIN_OVERSEA_BACKUP:GC.BACKUP_OVERSEA:i===eC.MAIN?GC.MAIN_OVERSEA:GC.BACKUP_OVERSEA:i===eC.MAIN?GC.MAIN:GC.BACKUP,t}function kj(e,t,i){return new Promise(((r,o)=>{HN({url:e,body:t,timeout:i.timeout,priority:"high"}).then((e=>{0===e.data.code?r(e.data.data):o({code:e.data.code,message:e.data.msg})})).catch(o)}))}var Oj=(e,t)=>YN({retryFunction:kj,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var Mj=class{constructor(){rw(this,"_log"),this._log=eM.createLogger({id:"fd"})}download(e,t){return nw(this,null,(function*(){let{type:i="blob"}=t||{};e=bN(e);try{let t,r=oN();if(t=GD(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let o=oN()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(o,"ms")),CP.addSuccessEvent({key:522700,cost:oN()-r}),t.data}catch(cM){throw this._log.error("failed to download: ".concat(e,", error: ").concat(cM)),CP.addFailedEvent({key:522700,error:cM}),cM}}))}downloadWithFetch(e,t){return nw(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(CC){throw CC}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType=t,o.onload=()=>{if(200===o.status||0===o.status&&o.response)i({data:o.response});else{let e=new Error("XHR failed, status: ".concat(o.status));e.status=o.status,r(e)}},o.onerror=r,o.send(null)}))}loadWasm(e,t){return nw(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=oN(),r=null,o=null;if(GD(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&GD(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Rw){o=Rw}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Rw){o=Rw}if(r){let t=oN()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),CP.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(o)),CP.addFailedEvent({key:522701,error:o}),o}))}loadScript(e){this._log.info("loadScript ".concat(e));let t=oN();return new Promise(((i,r)=>{let o=document.createElement("script");o.type="text/javascript",o.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(oN()-t,"ms")),CP.addSuccessEvent({key:522702,cost:oN()-t,split:1e3}),i(o)},o.onerror=t=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((null==t?void 0:t.message)||JSON.stringify(t))),CP.addFailedEvent({key:522702}),r(t)},o.crossOrigin="anonymous",o.src=e,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)}))}};iw([nx({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))}})],Mj.prototype,"download",1),iw([nx({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],Mj.prototype,"loadScript",1);var Pj=new Mj;function Lj(e){let[t,i]=e,r=i.byteLength,o=parseInt(String(r/255),10),n=r%255,a=[];a.push(0,0,0,1,6,t);for(let l=0;l<o;l++)a.push(255);a.push(n);let s=new DataView(i);return a.push(...new Uint8Array(s.buffer)),a.push(128),new hB(new DataView(new Uint8Array(a).buffer),!0)}function xj(e){return"empty"===e.type||0===e.data.byteLength}function Uj(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let e=dB(t,i);if(0===e){i+=1;continue}let r=i+e;if(r<t.byteLength&&6==(31&t.getUint8(r)))return!0;i+=e+1}return!1}function Vj(e){let t=0,i=0,r=new DataView(e);for(let o=0;o<e.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function Fj(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-Vj(t.data);if(r<=0)return t;let o=i.splice(0,r).reverse().map(Lj),n=o.reduce(((e,t)=>e+t.dataView.byteLength),0),a=new ArrayBuffer(n+t.data.byteLength),s=new DataView(a),l=new DataView(t.data),c=0;for(let d=0;d<o.length;d++)for(let e=0;e<o[d].dataView.byteLength;e++)s.setInt8(c++,o[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)s.setInt8(c++,l.getInt8(d));return t.data=a,t}function Bj(e){let{frame:t,onSEI:i}=e;try{if(xj(t)||!Uj(t.data))return t;let e=uB(t.data,!1).filter((e=>e.isSEI));null==i||i(e.reverse())}catch(Sw){}return t}function Hj(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:o}=e;return new TransformStream({transform(e,n){let a=e;i?audioEncodePipeline.forEach((e=>{a=e({frame:a,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:""})}})})):videoEncodePipeline.forEach((e=>{a=e({frame:a,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:a.data,userId:"",streamType:o?"main":"auxiliary"})}})})),n.enqueue(a)}})}function Wj(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(e,o){let n=e;r?(audioDecodePipeline.forEach((e=>{n=e({frame:n,onAudioFrameNTPTime:e=>{self.postMessage({type:"audio-ntp",data:e,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t})}})})),o.enqueue(n)):videoDecodePipeline.forEach((e=>{n=e({frame:n,onSEI:e=>{e.forEach((e=>{self.postMessage({type:"sei",seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:t,streamType:i})}))},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:n.data,userId:t,streamType:i})}})})),o.enqueue(n)}})}function Gj(e){let t=[hB],i=[Vj,xj,uB,Uj,Lj,Hj,Wj,LN,PN],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(),"];"),o="(()=>{".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=o=>{switch(o.data.type){case"sei":o.data.isMain?(e.push(o.data.data),o.data.small&&i.push(o.data.data)):t.push(o.data.data);break;case"ntp-offset":r=o.data.data}},self.onrtctransform=o=>{let{options:n}=o.transformer,a=n.isReceiver?Wj({userId:n.userId,streamType:n.streamType,isAudio:n.isAudio}):Hj({getNtpTime:()=>Date.now()+r,isAudio:n.isAudio,isMain:n.isMain,seiMessageList:n.isMain?n.small?i:e:t});o.transformer.readable.pipeThrough(a).pipeTo(o.transformer.writable)}}),")();").concat(r,"})()"),n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),s=new Worker(a);return URL.revokeObjectURL(a),s}var jj,zj=!1;function Kj(e){var t=this;let{TRTC:i,room:r,errorModule:o,assetsPath:n}=e;return{TRTC:i,LocalMixVideoTrack:WB,LocalVideoTrack:fB,LocalScreenTrack:zB,room:r,assetsPath:n,fileDownloader:Pj,innerEmitter:JO,INNER_EVENT:QO,constants:yw,environment:XN,utils:_B,eventLogger:rx,log:this.room.getLogger(),loggerManager:eM,errorModule:o,kvStatManager:CP,rtcDectection:rM,trtc:this,rx:HU,enums:oM,schedule:Ej,getDevices:uU,initVisionTaskRegistry:function(e,i){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"/mediapipe/vision.js";return nw(t,null,(function*(){!window.VisionTaskRegistry&&!zj&&(zj=!0,jj=Pj.loadScript("".concat(e,"/").concat(r).replace(/([^:]\/)\/+/g,"$1"))),yield jj,yield(yield window.VisionTaskRegistry.getInstance(e)).preloadModels(i)}))},audioContext:qx(),deviceDetector:cU,AudioPlayer:yU,RemoteAudioPlayer:IU,VideoPlayer:Ox,showAutoPlayDialog:Nx,Timer:QL,clearStarted:(e,t)=>{let i=e.getAlias(),r=cj.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:YB,createAudioNode:eU,getNetworkTimeOffset:fw,validateSourceNode:()=>{var e;if(pk&&(null==(e=this.room.audioManager._localAudioPipline)||!e.source.node))throw new WG({code:UG.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."})},createScriptTransformWorker:Gj}}var qj=new WeakMap;var Yj="5.15.0-wasm.2";function Jj(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{Qj.call(this,t,o,i,this._name)}catch(cM){return Promise.reject(cM)}return e.apply(this,o)}))}function Xj(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{Qj.call(this,t,o,i,this._name)}catch(cM){throw cM}return e.apply(this,o)}))}function Qj(e,t,i,r){if(JD(e))for(let o=0;o<e.length;o++)$j.call(this,{rule:e[o],value:t[o],key:e[o].name,fnName:i,className:r});else $j.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function $j(e){let{rule:t,value:i,key:r,fnName:o,className:n}=e;function a(e){return{code:UG.INVALID_PARAMETER,extraCode:e,fnName:o,messageParams:{key:r,rule:t,value:i}}}if(jD(i)){if(t.required)throw new WG(a(5001));if(jD(t.defaultValue))return void(GD(t.validate)&&t.validate.call(this,i,r,o,n,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),GD(t.type[r])&&i instanceof t.type[r]&&(e=!0),zD(t.type[r])&&WD(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new WG({code:UG.INVALID_PARAMETER,extraCode:5002,fnName:o,messageParams:{key:r,rule:{type:t.type.map((e=>ZD(e)?eN(e):zD(e)?e:WD(e)))},value:i}})}else if(!jD(t.type)&&WD(i)!==t.type)throw new WG(a(5002));if(!1===t.allowEmpty){let e=KD(i)&&(0===i||Number.isNaN(i)),t=zD(i)&&""===i.trim();if(e||t)throw new WG(a(5003))}if(t.notLessThanZero&&KD(i)&&i<0)throw new WG(a(5006));if(!jD(t.min)&&KD(i)&&i<t.min)throw new WG(a(5007));if(!jD(t.max)&&KD(i)&&i>t.max)throw new WG(a(5008));if(zD(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new WG(a(5004))}else if(GD(t.instanceOf)&&!(i instanceof t.instanceOf))throw new WG(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new WG(a(5005));let{properties:s}=t;FD(s)&&YD(i)&&Object.keys(s).forEach((e=>{$j.call(this,{rule:s[e],value:i&&i[e],key:"".concat(e),fnName:o,className:n})}));let{arrayItem:l}=t;FD(l)&&JD(i)&&i.forEach(((e,t)=>{$j.call(this,{rule:l,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:o,className:n})})),GD(t.validate)&&t.validate.call(this,i,r,o,n,this)}var Zj=0;function ez(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:n}=e;return OU(((e,a)=>function(){for(var s=arguments.length,l=new Array(s),c=0;c<s;c++)l[c]=arguments[c];var d,u,h;function p(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...l);if(l[e.argIndex]===t)return e.value}if(t===l||e in l)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(WD(t)):t instanceof MediaStreamTrack?wN(t):(JSON.stringify(t),t)}catch(o){return"type:".concat(WD(t))}}let m=(null==this?void 0:this._log)||eM,f=++Zj;if(null!=o&&o(...l))return e.apply(this,l);l.length>0?m.info("".concat(a,"() ").concat(f," ").concat(JSON.stringify(l,((e,t)=>p(e,t,["userSig","privateMapKey"]))))):m.info("".concat(a,"() ").concat(f));let _=r?r(...l):TP[a],g=(null==n?void 0:n(...l))||!1;try{let i=e.apply(this,l),r=oN();if($D(i)){let e="".concat(a.includes("Plugin")?"".concat((null==(u=(d=l[0]).getName)?void 0:u.call(d))||""," "):" ");return i.then((i=>(m.info("".concat(a,"() success ").concat(f," ").concat(e).concat(t.call(this,...l))),CP.addSuccessEvent({key:_,cost:oN()-r}),i))).catch((i=>{var r;let o=(i=WG.convertFrom.call(this,i,a,1===l.length?l[0]:l)).extraCode||i.code,n=null!=(r=i.message)&&r.includes(o)?"":" code:".concat(o),s=(null==i?void 0:i.code)===UG.OPERATION_ABORT;throw g||m[s?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(e).concat(t.call(this,...l)," ").concat(i).concat(n," params: ").concat(JSON.stringify(l,p))),CP.addFailedEvent({key:_,error:i}),i}))}return CP.addSuccessEvent({key:_}),i}catch(E){let e=(E=WG.convertFrom.call(this,E,a)).extraCode||E.code,t=null!=(h=E.message)&&h.includes(e)?"":" code:".concat(e),i=(null==E?void 0:E.code)===UG.OPERATION_ABORT;throw g||m[i?"warn":"error"]("".concat(a,"() failed ").concat(f," ").concat(E).concat(t," params: ").concat(JSON.stringify(l,p))),CP.addFailedEvent({key:_,error:E}),E}}))}var tz,iz=e=>OU(((t,i)=>function(r,o){return nw(this,null,(function*(){let n=this._plugins.get(r);if(!n)throw this._log.error("plugin ".concat(String(r)," is not found")),new WG({code:UG.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(GD(n.constructor.isSupported)&&!n.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new WG({code:UG.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return Qj.call(this,n.getValidateRule(e),[o],i,"TRTC"),t.call(this,n,o)}))})),rz=0,oz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"customAudioReferenceMap",new Map),rw(this,"audioRefId",0),rw(this,"audioContext",qx()),rw(this,"localAudioWorkletNode"),rw(this,"screenAudioWorkletNode"),rw(this,"mixNode"),rw(this,"silentNode"),rz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(rz)}),this.log.info("created id=".concat(this.getAlias()).concat(rz)),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,o){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new WG({code:UG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return tz||(tz=this.doPreload(e)),tz}doPreload(e){return nw(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Mx(this.audioContext,i)}catch(cM){this.log.error("preload audioProcessor failed. ".concat(cM))}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 nw(this,null,(function*(){var t,i,r,o;let{room:n}=this.core,{sdkAppId:a,userId:s,userSig:l,assetsPath:c=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,!c)throw new WG({code:UG.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(c,"/audioProcessor-wasm.js")),p&&!this.localAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",a,s,i,e,t,n)}if(m&&!this.screenAudioWorkletNode){let{sign:e,status:t,timestamp:i}=yield this.getAuthData(a,s,l);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",a,s,i,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==(i=this.screenAudioWorkletNode)||i.port.postMessage({type:"enable"}),n.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),jD(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++)})})),jD(u)||null==(r=this.localAudioWorkletNode)||r.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),jD(h)||null==(o=this.localAudioWorkletNode)||o.port.postMessage({type:"dump",data:{enable:h}})}))}update(e){return nw(this,null,(function*(){var t,i,r;let{audioReference:o,enableDump:n,processLevel:a}=e;jD(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++)})}))),jD(a)||null==(t=this.localAudioWorkletNode)||t.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),jD(n)||(null==(i=this.localAudioWorkletNode)||i.port.postMessage({type:"dump",data:{enable:n}}),null==(r=this.screenAudioWorkletNode)||r.port.postMessage({type:"dump",data:{enable:n}}))}))}stop(){return nw(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 nw(this,null,(function*(){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:s}=yield function(e){return nw(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:o}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:eC.MAIN;return"https://".concat(Rj[t]||Nj(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(o),n=yield fetch(e),{data:{errCode:a,errMsg:s,sign:l,status:c}}=yield n.json();if("1"===c)return{auth:!0,sign:l,status:c,message:s};let d=AD(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:c,message:s?"".concat(u," Reason: ").concat(s,". ").concat(h):"".concat(u,", ").concat(h)}}()}))}({sdkAppId:e,userSig:i,userId:t,timestamp:r});if(!o)throw this.log.info("audioProcessor: ".concat(t," auth result: ").concat(o,". Message: ").concat(s)),new WG({code:UG.INVALID_PARAMETER,message:s});return{sign:n,status:a,timestamp:r}}))}initWorkletNode(e,t,i,r,o,n,a,s){e.port.postMessage({type:"init",data:{sdkAppId:String(i),userId:r,timestamp:o,sign:n,status:a}}),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(Ew(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 JO.emit("265",{room:s,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(e){return nw(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(CC){this.log.warn("audio processor auto start failed, error: ".concat(CC))}}))}handleLocalAudioStopped(e){return nw(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(oz,"updateValidateRule",{type:"object"}),rw(oz,"stopValidateRule",{type:"object"}),rw(oz,"Name","AudioProcessor");var nz=oz;var az=0,sz=class{constructor(e,t){rw(this,"audioObjectURL"),rw(this,"player"),rw(this,"publisher"),rw(this,"mixInput"),this.mixInput=new Qx(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&&(jD(e.volume)||(this.volume=e.volume),jD(e.loop)||(this.loop=e.loop),jD(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 nw(this,null,(function*(){if(e.url){let t=yield Pj.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 lz(e,t){if(t&&"function"!=typeof t)throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var cz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"mixedMusicMap",new Map),rw(this,"cacheMusicMap",new Map),az+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(az)}),this.log.info("created id=".concat(this.getAlias()).concat(az))}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 nw(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 o=this.cacheMusicMap.get(i);o?e.url?o.reset():(o.mixInput.replaceSource(e.track),o.mixInput.connect()):(o=new sz(e,t.audioManager),this.cacheMusicMap.set(i,o)),o.updateListener(e),o.updateSettings(e);try{yield o.play()}catch(Rw){yield this.handleAutoPlayFailed(o,e,Rw)}this.mixedMusicMap.set(i,o),o.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:o.mixInput.source.node,refId:"ax-".concat(i)}),this.log.info("start mix audio track ".concat(i," success.")),CP.addEnum({key:502700,value:3}),this.kvUpload(e)}))}handleAutoPlayFailed(e,t,i){return nw(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((()=>{JO.off("154",t,this)}))};JO.on("154",t,this),Nx()}else this.core.trtc.emit(_j.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>nw(this,null,(function*(){return e.play()}))})}}))}update(e){return nw(this,null,(function*(){let{id:t,operation:i,seekFrom:r,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),jD(i)||n.setOperation(i),jD(r)||n.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return nw(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:o,operation:n,seekFrom:a,onTimeUpdate:s,onDurationChange:l,onEnded:c}=e;t&&CP.addCount({key:502009}),i&&CP.addCount({key:502001}),r&&CP.addCount({key:502002}),o&&CP.addCount({key:502003}),n&&CP.addCount({key:502004}),a&&CP.addCount({key:502005}),"function"!=typeof s&&CP.addCount({key:502007}),"function"!=typeof c&&CP.addCount({key:502008}),"function"!=typeof l&&CP.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(cz,"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"],o=t.split(".").pop(),n=r.indexOf(o)>=0,a=t.startsWith("blob"),s=t.startsWith("data");if(!(n||a||s))throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new WG({code:UG.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});lz("onTimeUpdate",e.onTimeUpdate),lz("onEnded",e.onEnded),lz("onDurationChange",e.onDurationChange)}}),rw(cz,"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){lz("onTimeUpdate",e.onTimeUpdate),lz("onEnded",e.onEnded),lz("onDurationChange",e.onDurationChange)}}),rw(cz,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),rw(cz,"Name","AudioMixer");var dz,uz=cz,hz=0,pz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"audioContext",qx()),rw(this,"workletNode"),rw(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),hz+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(hz)}),this.log.info("created id=".concat(this.getAlias()).concat(hz))}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,o){if(!e.room.audioManager.hasAudioTrack)throw new WG({code:UG.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return dz||(dz=this.doPreload(e)),dz}doPreload(e){return nw(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield Mx(this.audioContext,i)}catch(cM){throw this.log.error("load worklet failed",cM),cM}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 nw(this,null,(function*(){let{room:t,schedule:i}=this.core,{assetsPath:r=this.core.assetsPath}=e;if(!r)throw new WG({code:UG.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(AL()?"":"-nosimd",".js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield function(e,t){return nw(this,arguments,(function(e,t){let{sdkAppId:i,userId:r,userSig:n,timestamp:a}=t;return function*(){try{let{data:{errCode:t,errMsg:o,sign:s,status:l}}=yield e.getAbilityConfig(i,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:r,userSig:n,timestamp:a});if("1"===l)return{auth:!0,sign:s,status:l,message:o};let c=AD(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(c);break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: ".concat(c);break;case 5:u="Your packages is expired. Refer to: ".concat(c);break;case 6:u="Your version is not supported."}return{auth:!1,status:l,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)}}}()}))}(i,$b(Qb({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(a)),new WG({code:UG.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: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(Ew(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 nw(this,null,(function*(){this.updateConfig(e)}))}stop(){return nw(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;jD(e.mode)||(0===e.mode?this.config.enableFarFieldReduce=!1:1===e.mode&&(this.config.enableFarFieldReduce=!0),t=!0),jD(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(pz,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),rw(pz,"stopValidateRule",{type:"object"}),rw(pz,"Name","AIDenoiser");var mz=pz;var fz=tw(aw(),1),_z=class extends fz.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 nw(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!ck&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(Sw){rx.uploadEvent({log:"stat-pressure-detector-start-failed",error:Sw})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&eM.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(CC){rx.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:CC})}}},gz=new _z,Ez=0,vz=class e{constructor(e){this.core=e,rw(this,"log"),rw(this,"_seiMessageList",[]),rw(this,"_smallSeiMessageList",[]),rw(this,"_subStreamSeiMessageList",[]),Ez++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Ez)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Ez)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return Fj({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(CC){this.log.warn(CC)}return t}decode(e){let{frame:t,track:i}=e;return Bj({frame:t,onSEI:e=>{e.forEach((e=>{null!=i&&i.userId?this.core.trtc.emit(_j.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:e})}))}})}destroy(){this.log.debug("destroy"),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:_L?this.encode:Fj,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:_L?this.decode:Bj,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 o=[i.seiPayloadType,t],n=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(o):(this._seiMessageList.push(o),n&&this._smallSeiMessageList.push(o)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:o,isMain:!i.toSubStream,small:n})}getName(){return e.Name}getAlias(){return"sei"}getGroup(){return"sei"}};rw(vz,"autoStart",!0),rw(vz,"Name","SEI");var yz,Tz=vz,Iz=0,Az=class e{constructor(e){this.core=e,rw(this,"_core"),rw(this,"log"),rw(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++Iz)}),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 nw(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())}))}update(e){return nw(this,arguments,(function(e){var t=this;let{visible:i}=e;return function*(){i?yield t.openDebugDiaLog():t.closeDebugDiaLog()}()}))}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return nw(this,null,(function*(){var e;if(!this.dialog)try{if(yz)yield yz;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(Iw,"/assets/debug-dialog.js");yz=this._core.fileDownloader.loadScript(t),yield yz}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(Sw){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(Sw))}}))}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};rw(Az,"Name","Debug"),rw(Az,"autoStart",!0);var Sz=Az,Rz=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},bz=class{constructor(e,t,i){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:r,trtc:o}=e;this.config=i.config,this.trackDoneOB=OV(t,zL.INIT),this.stopOB=vV(),this.startOB=vV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let n=vV();$U(this.startOB,mV(0),kF((e=>{let i=this.pipe(t);return n.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),$U(i,eF(this.stopOB),tB((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:Rz(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),$U(i,ZV(1),XF(jV))})),eF(this.stopOB),tB((()=>{t.player.setOutput(),n.next("STARTED")}),(e=>{n.next("FAILED")}),(()=>{r.addSuccessEvent({key:Rz(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 aV()((t=>nw(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(cM){e.log.error(cM),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"}))}},wz={type:"object"},Cz=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 wz}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 o=new bz(this.core,r,e);return $U(o.trackDoneOB,ZV(1),tB((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,o),o.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 bz(this.core,e.track,e))}}};rw(Cz,"Name","TRTCAudioDecoder");var Dz=Cz,Nz=class{constructor(){rw(this,"log"),this.log=eM.createLogger({id:"exp"})}call(e,t){return nw(this,null,(function*(){return GD(this[e])?this[e](t):Promise.reject(new mw({code:hw.INVALID_PARAMETER,message:fP({key:uP.API_NOT_EXIST,data:{name:e}})}))}))}enableAudioFrameEvent(e){return nw(this,null,(function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:o=48e3,channelCount:n=1,port:a}=e,{audioManager:s}=t.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:c}=s;if(c.set(r,{enable:i,sampleRate:o,channelCount:n,port:a}),i)if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isAvailable){if(l.get(e.userId))return;let i=s.getPCM((e=>{t.emit(_j.AUDIO_FRAME,e)}),e.userId);l.set(e.userId,i)}}));else{if(l.get(r))return;let e=s.getPCM((e=>{t.emit(_j.AUDIO_FRAME,e)}),r);l.set(r,e)}else if("*"===r)t.room.remotePublishedUserMap.forEach((e=>{if(e.remoteAudioTrack.isSubscribed){let{userId:t}=e,i=l.get(t);null==i||i.abort("disable"),l.delete(t)}}));else{let e=l.get(r);null==e||e.abort("disable"),l.delete(r)}}))}resumeRemotePlayer(e){return nw(this,null,(function*(){if("*"===e.userId){let t=[];return e.trtcInstance.room.remotePublishedUserMap.forEach((i=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=i;e.streamType?"main"===e.streamType?(r.isAvailable&&t.push(r.player.resume()),o.isAvailable&&t.push(o.player.resume())):n.isAvailable&&t.push(n.player.resume()):(r.isAvailable&&t.push(r.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:i,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=t;e.streamType?"main"===e.streamType?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1)):o.isAvailable&&o.player.pause(!1):(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1),o.isAvailable&&o.player.pause(!1))}));else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&("main"===e.streamType?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}};iw([function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return OU(((e,i)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];return nH.call(this,t,o,i,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"}}})],Nz.prototype,"enableAudioFrameEvent",1);var kz=new Nz,Oz=tw(aw(),1),Mz=class extends Oz.EventEmitter{constructor(){super(),rw(this,"states",{}),rw(this,"permissionChangeHandler"),rw(this,"log"),this.log=eM.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 nw(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 nw(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(CC){return this.log.error("get ".concat(e," permission failed, error: ").concat(CC instanceof Error?CC.message:CC)),null}}))}destroy(){Object.values(this.states).forEach((e=>{null==e||e.removeEventListener("change",this.permissionChangeHandler)})),this.states={}}},Pz=new Mz,Lz=0,xz=new Set,Uz=null;Aw(Yj),iM.checkStorage();var Vz=class e extends OG.EventEmitter{constructor(t,i){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",eM.createLogger({id:"t".concat(++Lz)})),rw(this,"_plugins",new Map),rw(this,"_networkQuality",null),rw(this,"_speakerId"),rw(this,"enterRoomParams"),rw(this,"_enableAutoSwitchWhenRecapturing",!0),this._room=new t(Qb({logger:this._log,frameWorkType:e.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,qD(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(uz,i.assetsPath),this._use(nz,i.assetsPath),this._use(mz,i.assetsPath),this._use(Dz,i.assetsPath),this._use(Sz),i.enableSEI&&EL&&this._use(Tz),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(_j.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new WG({code:UG.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,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];try{return i.apply(e,o)}catch(cM){let i=fP({key:uP.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return eM.warn("".concat(i,"\n\n").concat(cM.stack)),!1}}})(this,"trtc")}static create(e){}static _create(t,i){!function(){var e;if(LG){LG=!1,5!==eM.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("******************************************************************************")),eM.info("TRTC Web SDK Version:",Iw),NO||eM.debug("Build Time:","2025-12-29 15:40:15");let t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(VO());if(sk&&window.screen&&(window.screen.width||window.screen.height)){let e="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);t+=", screen: ".concat(e)}let i=navigator.deviceMemory;i&&(t+=", minRAM: ".concat(i,"GB")),eM.info(t),eM.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),UO().then((e=>{e&&eM.info(xO)}))}}();let r=new e(t,i||{});return xz.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tx(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(_j.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{let{userId:t,reason:i}=e;this.emit(_j.REMOTE_USER_EXIT,{userId:t,reason:i})})).add("banned",(e=>{Aj(!0),this._exitRoom().finally((()=>{this.emit(_j.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().finally((()=>{this.emit(_j.ERROR,WG.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(_j.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=$b(Qb({},e),{uplinkRTT:Math.min(e.uplinkRTT,tD),downlinkRTT:Math.min(e.downlinkRTT,tD)});this.emit(_j.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{tx(t,t).add("player-state-changed",(i=>{let r=$b(Qb({},i),{userId:e.userId});t.kind===eC.VIDEO&&(r.streamType=GG(t.streamType)),this.emit(t.kind===eC.AUDIO?_j.AUDIO_PLAY_STATE_CHANGED:_j.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===hw.PLAY_NOT_ALLOWED&&this.emit(_j.AUTOPLAY_FAILED,{userId:t.userId,mediaType:t.strMediaType,resume:()=>t.player.resume()})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{ix(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,o=t.audioAvailable,n=t.videoAvailable,{audioAvailable:a,videoAvailable:s}=i;a||this._remoteAudioConfigMap.delete(r),s||this._removeRemoteVideoConfig(r,"main"),i.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==s&&(s?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(s?_j.REMOTE_VIDEO_AVAILABLE:_j.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i}),this.emit(a?_j.REMOTE_AUDIO_AVAILABLE:_j.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?_j.REMOTE_VIDEO_AVAILABLE:_j.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(_j.SEI_MESSAGE,$b(Qb({},e),{streamType:GG(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,o,n,a,s;let l={2:"big",3:"small",7:"sub"},c={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,tD),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)/XM},video:e.msg_up_stream_info.msg_video_status.filter((e=>l[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:l[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)/XM,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:l[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(_j.STATISTICS,c)})).add("custom-message",(e=>{this.emit(_j.CUSTOM_MESSAGE,e)})).add("layerData",(e=>this.emit(_j.LAYER_DATA,e))).add("first-video-frame",(e=>{this.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},e),{streamType:GG(e.streamType)}))})).add("audio-frame",(e=>{this.emit(_j.AUDIO_FRAME,e)})),tx(this,cU).add("audioInputAdded",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(_j.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>nw(this,null,(function*(){if(this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Uz&&Uz.deviceId===YC){let e=(yield fU()).find((e=>e.deviceId===YC));e&&Uz.groupId!==e.groupId&&(Uz=e,this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>nw(this,null,(function*(){this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield fU())[0];if(!t||!Uz||Uz.groupId===t.groupId)return;let i=Uz.deviceId===e.deviceId,r=Uz.deviceId===YC&&Uz.deviceId===t.deviceId;(i||r)&&(Uz=t,this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})))),tx(this,Pz).add("permission-state-change",(e=>{this.emit(_j.PERMISSION_STATE_CHANGE,e)})),this.room.enableSEI&&this.on(_j.SEI_MESSAGE,(e=>{var t;let i=null==(t=this.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteVideoTrack;i&&i.updateAlphaRenderInfo(e)}))}getNetworkTime(){return _w()}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 o=new t(Kj.call(this,{TRTC:e,room:this._room,assetsPath:i,errorModule:{RtcError:WG,ErrorCode:UG,CoreErrorCode:hw,ErrorCodeDictionary:VG}}));return this._plugins.set(t.Name,o),o.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),o}enterRoom(t){return nw(this,null,(function*(){var i,r;this.enterRoomParams=t;let{scene:o="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:a=!0,autoReceiveVideo:s=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!zD(t.proxy)&&t.proxy.turnServer&&(null==(r=(i=this._room).setTurnServer)||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=a,this._room.autoReceiveVideo=s,qD(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let l={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||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(l,o,e.frameWorkType),this._checkTrackToPublish(),gz.start()}))}exitRoom(){return nw(this,null,(function*(){return yield this._exitRoom()}))}switchRoom(e){return nw(this,null,(function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(CC){if(!(CC instanceof pw)||CC.code!==hw.API_CALL_TIMEOUT&&CC.code!==hw.SWITCH_ROOM_FAILED)throw CC;this._log.warn("switchRoom ".concat(CC.code===hw.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)}))}_rejoinRoom(e){return nw(this,null,(function*(){yield this.exitRoom();let t=Qb(Qb({},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=qj.get(e);t&&(t.forEach((e=>clearTimeout(e))),qj.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{ix(e.remoteAudioTrack),ix(e.remoteVideoTrack),ix(e.remoteAuxiliaryTrack)}))}switchRole(e,t){return nw(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(),ix(this),this.removeAllListeners(),this._room.destroy(),xz.delete(this),0===xz.size&&gz.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),JO.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return nw(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:o}=t,n=new cB(e._room.audioManager),a={},s={muted:!0};o&&(jD(o.microphoneId)?jD(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&KD(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),jD(o.profile)||(zD(o.profile)?Jw[o.profile]&&n.setProfile(Jw[o.profile]):n.setProfile(o.profile)),KD(o.earMonitorVolume)&&(s.muted=!(o.earMonitorVolume>0),s.volume=o.earMonitorVolume),jD(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),jD(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),jD(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl),qD(e._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),n.on("5",(t=>{e.emit(_j.ERROR,new WG({code:UG.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),n.on("2",(t=>{e.emit(_j.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),n.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),n.on("6",(()=>{})),e._listenOutputTrackChanged(n),e._speakerId&&n.setAudioOutput(e._speakerId),yield n.capture(a),jD(r)||n.setMute(r),tx(n,n).add("player-state-changed",(t=>{e.emit(_j.AUDIO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(n).catch((()=>{})),e._localAudioTrack=n,e._localAudioConfig=$b(Qb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:s,track:n}),JO.emit("113",{userId:"",room:e.room})}()}))}updateLocalAudio(e){return nw(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,o={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):jD(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),jD(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),jD(r.earMonitorVolume)||(o.muted=!(r.earMonitorVolume>0),o.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!jD(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),jD(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),hN(this._localAudioConfig,e)}))}stopLocalAudio(){return nw(this,null,(function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),JO.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ix(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return nw(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:o=!0,capture:n=!0,mute:a,option:s}=t,l=new fB(e._room.videoManager),c={},d={};s&&(qD(s.avoidCropping)&&(l.avoidCropping=s.avoidCropping),s.cameraId?c.deviceId=s.cameraId:jD(s.useFrontCamera)?jD(s.videoTrack)||(c.customSource=s.videoTrack):c.facingMode=s.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT,jD(s.retryWhenExactFailed)||(c.retryWhenExactFailed=s.retryWhenExactFailed),s.qosPreference&&(c.contentHint=jG(s.qosPreference)),jD(s.profile)||(zD(s.profile)?Xw[s.profile]&&l.setProfile(Xw[s.profile]):l.setProfile(s.profile)),jD(s.fillMode)||(d.objectFit=s.fillMode),jD(s.mirror)||(d.mirror=s.mirror),jD(s.small)||(jD(s.smallMode)||(e._room.smallMode=s.smallMode),qD(s.small)&&!1===s.small?l.stopSmall():l.updateSmallConfig(zG(s.small,!0))),jD(s.rotation)||l.setRotation(s.rotation),qD(e._enableAutoSwitchWhenRecapturing)&&(l.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),l.once("first-video-frame",(t=>{e.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},t),{streamType:GG(t.streamType)}))})),l.on("5",(t=>{e.emit(_j.ERROR,new WG({code:UG.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),l.on("2",(t=>{e.emit(_j.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),l.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),l.on("6",(()=>{})),e._listenOutputTrackChanged(l),n?yield l.capture(c):null==(i=l.manager)||i.changeInput(l),jD(a)||(yield l.setMute(a)),tx(l,l).add("player-state-changed",(t=>{e.emit(_j.VIDEO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:"",streamType:"main"}))})).add("video-size-changed",(t=>{e.emit(_j.VIDEO_SIZE_CHANGED,$b(Qb({},t),{streamType:GG(t.streamType)}))})),o&&e._room.isJoined&&e._room.publish(l).catch((()=>{})),e._localVideoTrack=l,e._localVideoConfig=$b(Qb({},t),{view:r,publish:o,capture:n}),yield e._updateVideoPlayOption({view:r,playOption:d,track:l})}()}))}updateLocalVideo(e){return nw(this,null,(function*(){var t,i,r;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:o,publish:n,mute:a,capture:s,option:l}=e,c={};if(this._localVideoConfig.capture)!1!==s?null!=l&&l.cameraId?yield this._localVideoTrack.switchDevice(null==l?void 0:l.cameraId):jD(null==l?void 0:l.useFrontCamera)?jD(null==l?void 0:l.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(null==l?void 0:l.videoTrack)):yield this._localVideoTrack.switchDevice(null!=l&&l.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(s){let e={};e.deviceId=(null==l?void 0:l.cameraId)||(null==(t=this._localVideoConfig.option)?void 0:t.cameraId),e.facingMode=null!=l&&l.useFrontCamera||null!=(i=this._localVideoConfig.option)&&i.useFrontCamera?eC.FACING_MODE_USER:eC.FACING_MODE_ENVIRONMENT,e.customSource=(null==l?void 0:l.videoTrack)||(null==(r=this._localVideoConfig.option)?void 0:r.videoTrack),yield this._localVideoTrack.capture(e)}l&&(jD(l.profile)||(zD(l.profile)?Xw[l.profile]&&this._localVideoTrack.setProfile(Xw[l.profile]):this._localVideoTrack.setProfile(l.profile),(!l.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(l.cameraId))&&jD(l.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),jD(l.fillMode)||(c.objectFit=l.fillMode),jD(l.mirror)||(c.mirror=l.mirror),jD(l.rotation)||this._localVideoTrack.setRotation(l.rotation),l.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(jG(l.qosPreference)),jD(l.small)||(qD(l.small)&&!l.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(zG(l.small,!0)))),this._room.isJoined&&jD(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((()=>{}))),jD(a)||(yield this._localVideoTrack.setMute(a)),yield this._updateVideoPlayOption({view:o,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),hN(this._localVideoConfig,e)}))}stopLocalVideo(){return nw(this,null,(function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),ix(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return nw(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:o=null,publish:n=!0,muteSystemAudio:a,option:s}=t,l=new zB(e._room.videoManager);l.on("4",(t=>{let i;t.error&&(i=WG.convertFrom(t.error)),e.emit(_j.PUBLISH_STATE_CHANGED,$b(Qb({},t),{error:i}))})),l.once("first-video-frame",(t=>{e.emit(_j.FIRST_VIDEO_FRAME,$b(Qb({},t),{streamType:GG(t.streamType)}))})),e._listenOutputTrackChanged(l),"main"===t.streamType&&(l.mediaType=4);let c=null,d={},u={};s&&(jD(s.profile)||(zD(s.profile)?Zw[s.profile]&&l.setProfile(Zw[s.profile]):l.setProfile(s.profile)),s.systemAudio&&(d.systemAudio=!0,d.echoCancellation=s.echoCancellation,d.noiseSuppression=s.noiseSuppression,d.autoGainControl=s.autoGainControl),jD(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=jG(s.qosPreference)));let h=yield l.capture(d);if(l.mediaTrack.addEventListener(eC.ENDED,(()=>{e._stopScreenShare(),e.emit(_j.SCREEN_SHARE_STOPPED)})),h.getAudioTracks()[0]){c=new qB(e._room.audioManager);let o=h.getAudioTracks()[0];null!=(i=t.option)&&i.systemAudio&&!(null!=(r=t.option)&&r.audioTrack)&&(c.sourceTrack=o),yield c.setInputMediaStreamTrack(o),qD(a)&&c.mediaTrack&&(c.mediaTrack.enabled=!a),e._speakerId&&c.setAudioOutput(e._speakerId)}if(tx(l,l).add("player-state-changed",(t=>{e.emit(_j.VIDEO_PLAY_STATE_CHANGED,$b(Qb({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[l];c&&(t.push(c),e._checkScreenAudioEchoCancellation(l,c)),t.forEach((t=>e._room.publish(t).catch((()=>{}))))}e._localScreenTrack=l,e._localScreenAudioTrack=c,e._localScreenConfig=$b(Qb({},t),{view:o,publish:n}),yield e._updateVideoPlayOption({view:o,playOption:u,track:l})}()}))}updateScreenShare(e){return nw(this,null,(function*(){var t;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:i,publish:r,muteSystemAudio:o,option:n}=e,a={};if(n&&(jD(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let e=jG(n.qosPreference);this._localScreenTrack.setContentHint(e)}if(this._room.isJoined&&!jD(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&&qD(o)&&(this._localScreenAudioTrack.mediaTrack.enabled=!o),yield this._updateVideoPlayOption({view:i,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),hN(this._localScreenConfig,e)}))}stopScreenShare(){return nw(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return nw(this,null,(function*(){let{view:t,userId:i,streamType:r,option:o}=e,n="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(n))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let a=this._room.remotePublishedUserMap.get(i);if(!a)return;let s={},l="main"===r?a.remoteVideoTrack:a.remoteAuxiliaryTrack;l.on("decode-failed",(e=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))})),l.on("video-size-changed",(e=>{this.emit(_j.VIDEO_SIZE_CHANGED,$b(Qb({},e),{streamType:GG(e.streamType)}))})),this._listenOutputTrackChanged(l),o&&(jD(o.fillMode)||(s.objectFit=o.fillMode),jD(o.mirror)||(s.mirror=o.mirror),jD(o.poster)||(s.poster=o.poster),s.canvasRender=o.canvasRender,"main"===r&&!jD(o.small)&&(!a.remoteVideoTrack.isSubscribing&&!a.remoteVideoTrack.isSubscribed&&a.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.small,l.user)),jD(o.draggable)||l.setDraggable(o.draggable)),yield this._room.subscribe(l),yield this._enableVideoDecodeFallback(l,r),yield this._updateVideoPlayOption({view:t,playOption:s,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(n,{config:e}),o&&!jD(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:null==o?void 0:o.viewRoot})}))}updateRemoteVideo(e){return nw(this,null,(function*(){var t,i;let{view:r,userId:o,streamType:n,option:a,mute:s}=e,l="".concat(o,"_").concat(n),c=this._remoteVideoConfigMap.get(l);if(!c||!this._room.remotePublishedUserMap.has(o))return;let d={};a&&(jD(a.fillMode)||(d.objectFit=a.fillMode),jD(a.mirror)||(d.mirror=a.mirror));let u=null,h=this._room.remotePublishedUserMap.get(o);if("main"===n&&null!=h&&h.muteState.hasVideo&&(u=h.remoteVideoTrack),"sub"===n&&null!=h&&h.muteState.hasAuxiliary&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:p}=c;"main"===n&&a&&!jD(a.small)&&this._room.changeType(a.small,u.user),a&&!jD(a.draggable)&&u.setDraggable(a.draggable),a&&(qD(a.pictureInPicture)&&(a.pictureInPicture?yield u.player.enterPictureInPicture():yield u.player.exitPictureInPicture()),qD(a.fullScreen)&&(a.fullScreen?yield u.player.enterFullscreen():yield u.player.exitFullscreen())),qD(s)&&(u.ignoreUpdatePlayingState=!0,s?(yield u.player.pause(),yield this.room.unsubscribe(u)):(yield this.room.subscribe(u),yield u.player.resume(!0))),yield this._updateVideoPlayOption({view:r,playOption:d,track:u,prevConfig:p}),hN(p,e);let m=jD(null==a?void 0:a.receiveWhenViewVisible)?null==(t=p.option)?void 0:t.receiveWhenViewVisible:a.receiveWhenViewVisible,f=jD(r)?p.view:r,_=jD(null==a?void 0:a.viewRoot)?null==(i=p.option)?void 0:i.viewRoot:a.viewRoot;this._observeView({remoteTrack:u,view:f,receiveWhenViewVisible:m,viewRoot:_})}))}stopRemoteVideo(e){return nw(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nw(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:o,remoteAuxiliaryTrack:n}=r;"main"===e.streamType&&(o.stop(),t.hasVideo&&i.push(o)),"sub"===e.streamType&&(n.stop(),t.hasAuxiliary&&i.push(n))}for(let e of i)t&&(delete e.ignoreUpdatePlayingState,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 nw(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)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(cM){throw cM.code!==UG.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),cM}}))}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 nw(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return nw(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return nw(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(_j.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{gj.has(e)||this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(cM){}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",o=!1;if(zD(t)?e=t:(e=t.userId,o=!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?o&&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,o=null;if(""===t)"main"===i&&this._localVideoTrack&&(o=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(o=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(o="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return o?r&&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: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 nw(this,null,(function*(){(yield fU()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),Uz=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: '.concat(Lw,"/en/TRTC.html#.setCurrentSpeaker"))}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return nw(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 o={},n=r.remoteAudioTrack;n.on("decode-failed",(e=>{this.emit(_j.ERROR,new WG({code:UG.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))})),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let r=null!=(t=this._remoteAudioVolumeMap.get(i))?t:this._remoteAudioVolumeMap.get("*"),a=KD(r)?r:100;o.volume=a,this._remoteAudioConfigMap.set(i,e),yield this._room.subscribe(n),$U(OV(n,"decode-failed"),eF(OV(n,zL.INIT)),tB((()=>{this.startPlugin(Dz.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:o,track:n}),JO.emit("115",{userId:i,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:"ra-".concat(i)})}catch(hM){throw this._remoteAudioConfigMap.delete(i),hM}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return nw(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)),JO.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),$U(OV(e,"decode-failed"),eF(OV(e,zL.INIT)),iB((()=>{"h265"!==this._room.downlinkVideoCodec&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})})),MF(OV(e,"decode-downgrade-state-changed")),tB((r=>{i=r.state,this.emit(_j.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,$b(Qb({},r),{streamType:t,userId:e.userId}))}),(t=>{e.log.error("fallback",t)}),(()=>{"STARTED"===i&&e.log.info("fallback complete")}))))}_updateVideoPlayOption(e){return nw(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:o}=e;return function*(){if(r.setMirror(i.mirror),jD(t)&&o&&o.view&&!lN(i)){let e=mN(o.view);e.length>0&&(yield r.play(e,i))}if(!jD(t)){let e=mN(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return nw(this,arguments,(function(e){var t=this;let{playOption:i={},track:r,prevConfig:o}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,i)}catch(Rw){}if(jD(i.muted)||r.setPlayerMute(i.muted),jD(i.volume)||r.setAudioVolume(i.volume/100),r instanceof cB&&r.mediaTrack){let e=!1===i.muted&&!jD(i.volume)&&i.volume>0?"add":"remove";t.room.audioManager.updateAudioReference({type:e,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof $B){let e=i.muted?0:i.volume;if(jD(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(_j.TRACK,{userId:i,streamType:GG(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,viewRoot:o}=e;if(jD(i)||jD(r))return;let n=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(GG(t.streamType)));if(!n)return;let a=n.observer||void 0;if(null===i||JD(i)&&0===i.length||!r)return null==a||a.disconnect(),void(t.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",t.userId,t.strMediaType),this._room.subscribe(t).catch((()=>{}))));let s=n.visibleViewMap||new Map,l=-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(l),l=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 c=new Set(mN(i));s.forEach(((e,t)=>{c.has(t)||(a.unobserve(t),s.delete(t))})),c.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 nw(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()}))}_stopScreenShare(){return nw(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),ix(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_checkScreenAudioEchoCancellation(e,t){return nw(this,null,(function*(){var i,r;if(!e||!t)return;let o=null==(i=e.trackSettings)?void 0:i.displaySurface;if(!1===(null==(r=t.trackSettings)?void 0:r.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(dM){this._log.warn("start audioProcessor plugin failed: ",dM)}}}))}_onLocalTrackCaptured(e){let{track:t}=e;"audio"===t.kind&&(!Uz||dU(Uz))&&(this._initActiveSpeaker(),JO.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return nw(this,null,(function*(){if(Uz&&!dU(Uz))this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:Uz});else{let e=yield fU();e[0]&&!dU(e[0])?(Uz=e[0],this.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):JO.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:$b(Qb({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),CP.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),CP.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return nw(this,null,(function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),kz.call(e,Qb({trtcInstance:this},t))}))}static setLogLevel(e,t){eM.setLogLevel(e),jD(t)||(t?eM.enableUploadLog():eM.disableUploadLog())}static isSupported(){return HP(e.frameWorkType)}static getPermissions(e){return nw(this,arguments,(function(e){let{request:t=!0,types:i=["camera","microphone"]}=e;return function*(){t&&(yield Pz.request(i).catch((e=>{var t;return eM.error("getPermissions request failed, error: ".concat(null!=(t=null==e?void 0:e.message)?t:e))})));let[e,r]=yield Promise.all([Pz.get("camera"),Pz.get("microphone")]);return{camera:e,microphone:r}}()}))}static getCameraList(){return pU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return hU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return fU(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(t){return nw(this,null,(function*(){if(!ck||t!==xG.SPEAKER&&t!==xG.HEADSET)(yield fU()).forEach((e=>{e.deviceId===t&&(xz.forEach((i=>{i._setCurrentSpeaker(t),i.emit(_j.DEVICE_CHANGED,{type:"speaker",action:"active",device:e})})),Uz=e)}));else{let i=yield e.getMicrophoneList(),r="";if(i.forEach((e=>{e.label===t&&(r=e.deviceId)})),!r)return;xz.forEach((e=>nw(this,null,(function*(){e._localAudioTrack&&(yield e.updateLocalAudio({option:{microphoneId:r}}))}))))}}))}static _addKVStat(e){let{type:t,key:i,value:r,base:o,useUV:n,version:a,max:s}=e;switch(a&&(wP.version=a),t){case"count":wP.addCount({key:i,useUV:n});break;case"enum":wP.addEnum({key:i,value:r,useUV:n});break;case"number":wP.addNumber({key:i,value:r,split:o,max:s})}}};rw(Vz,"VERSION",Yj),rw(Vz,"_loggerManager",eM),rw(Vz,"EVENT",_j),rw(Vz,"ERROR_CODE",UG),rw(Vz,"TYPE",xG),rw(Vz,"frameWorkType",30),iw([ez({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"}})})],Vz.prototype,"use",1),iw([Jj(rj.TRTC.enterRoom),hj("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})),OU((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),ez()],Vz.prototype,"enterRoom",1),iw([ez()],Vz.prototype,"exitRoom",1),iw([Jj(rj.TRTC.switchRoom),ez(),VU()],Vz.prototype,"switchRoom",1),iw([Jj(rj.TRTC.switchRole),pj("room",{merge:(e,t)=>t}),ez()],Vz.prototype,"switchRole",1),iw([ez()],Vz.prototype,"destroy",1),iw([Jj(rj.TRTC.startLocalAudio),hj("audio",((e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.microphoneId)===(null==(n=null==r?void 0:r.option)?void 0:n.microphoneId)})),ez()],Vz.prototype,"startLocalAudio",1),iw([Jj(rj.TRTC.updateLocalAudio),pj("audio",{debounce:{delay:200,getKey:()=>"".concat(Lz,"-localAudio"),isNeedToDebounce:e=>{var t;return!jD(null==(t=e.option)?void 0:t.captureVolume)}}}),ez()],Vz.prototype,"updateLocalAudio",1),iw([mj("audio"),ez()],Vz.prototype,"stopLocalAudio",1),iw([Jj(rj.TRTC.startLocalVideo),hj("video",((e,t)=>{let[i]=e,[r]=t;var o,n;return(null==(o=null==i?void 0:i.option)?void 0:o.cameraId)===(null==(n=null==r?void 0:r.option)?void 0:n.cameraId)})),ez()],Vz.prototype,"startLocalVideo",1),iw([Jj(rj.TRTC.updateLocalVideo),pj("video"),ez()],Vz.prototype,"updateLocalVideo",1),iw([mj("video"),ez()],Vz.prototype,"stopLocalVideo",1),iw([Jj(rj.TRTC.startScreenShare),hj("screen",(()=>!0)),ez()],Vz.prototype,"startScreenShare",1),iw([Jj(rj.TRTC.updateScreenShare),pj("screen"),ez()],Vz.prototype,"updateScreenShare",1),iw([ez()],Vz.prototype,"stopScreenShare",1),iw([Jj(rj.TRTC.startRemoteVideo),hj((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"startRemoteVideo",1),iw([Jj(rj.TRTC.updateRemoteVideo),pj((e=>"v".concat(e.userId).concat(e.streamType))),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"updateRemoteVideo",1),iw([Jj(rj.TRTC.stopRemoteVideo),OU((e=>function(t){return nw(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)}))})),ez({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Vz.prototype,"stopRemoteVideo",1),iw([mj((e=>"v".concat(e.userId).concat(e.streamType)))],Vz.prototype,"_stopRemoteVideo",1),iw([Jj(...rj.TRTC.muteRemoteAudio),ez({getRemoteId:e=>e})],Vz.prototype,"muteRemoteAudio",1),iw([Xj(...rj.TRTC.setRemoteAudioVolume),function(e,t){return OU(((i,r)=>function(){for(var r=arguments.length,o=new Array(r),n=0;n<r;n++)o[n]=arguments[n];let a=qj.get(this);a||(a=new Map,qj.set(this,a));let s=t(...o),l=a.get(s);if(!l||l<=0){i.apply(this,o);let t=setTimeout((()=>{var e;null==(e=qj.get(this))||e.delete(s)}),e);a.set(s,t)}else{clearTimeout(l);let t=window.setTimeout((()=>{var e;i.apply(this,o),null==(e=qj.get(this))||e.delete(s)}),e);a.set(s,t)}}))}(200,(e=>e)),ez({getRemoteId:e=>e})],Vz.prototype,"setRemoteAudioVolume",1),iw([iz("start"),kU((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),hj(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>IP[e.getName()],ignoreLog:e=>"Debug"===e.getName(),ignoreErrorLog:e=>"AudioProcessor"===e.getName()})],Vz.prototype,"startPlugin",1),iw([iz("update"),pj(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),{merge:(e,t)=>(hN(e[1],t[1]),e)}),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>AP[e.getName()]})],Vz.prototype,"updatePlugin",1),iw([iz("stop"),mj(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),ez({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>SP[e.getName()]})],Vz.prototype,"stopPlugin",1),iw([Xj(...rj.TRTC.enableAudioVolumeEvaluation)],Vz.prototype,"enableAudioVolumeEvaluation",1),iw([ez()],Vz.prototype,"getVideoSnapshot",1),iw([ez()],Vz.prototype,"_setCurrentSpeaker",1),iw([hj((e=>"a".concat(e.userId)),(()=>!0))],Vz.prototype,"_startRemoteAudio",1),iw([OU((e=>function(t){return nw(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio($b(Qb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),mj((e=>"a".concat(e.userId)))],Vz.prototype,"_stopRemoteAudio",1),iw([mj("room")],Vz.prototype,"_exitRoom",1),iw([mj("screen")],Vz.prototype,"_stopScreenShare",1),iw([Jj(...rj.TRTC.sendSEIMessage),MG({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}})],Vz.prototype,"sendSEIMessage",1),iw([Jj(rj.TRTC.sendCustomMessage),MG({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Vz.prototype,"sendCustomMessage",1),iw([fj()],Vz,"create",1),iw([Jj(rj.TRTC.create)],Vz,"_create",1),iw([fj()],Vz,"setLogLevel",1),iw([fj()],Vz,"isSupported",1),iw([fj(),ez()],Vz,"getPermissions",1),iw([fj()],Vz,"getCameraList",1),iw([fj()],Vz,"getMicrophoneList",1),iw([fj()],Vz,"getSpeakerList",1);var Fz=Vz,Bz=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 $B(e,this),this.remoteVideoTrack=new eH(e,this),this.remoteAuxiliaryTrack=new tH(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 cN(this.flag,this.userId)}get flag(){return this._flag}set flag(e){if(e===this._flag)return;let t,i=this.muteState;this._flag=e;let r=this.muteState;for(t in r)i[t]!=r[t]&&console.log(this.userId,t,i[t],"->",r[t]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}},Hz=class{constructor(){rw(this,"_set",new Set),JO.on(QO.LEAVE_SUCCESS,this.delete,this),JO.on(QO.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:o}=e;return"rtc"!==o.scene&&this._set.has(this.getKey(t,i,r,o.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 Wz(){return nw(this,null,(function*(){let e,t;try{let t=yield hU();e=t&&t.length}catch(_P){}try{let e=yield pU();t=e&&e.length}catch(_P){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:n,isVp8DecodeSupported:a,isH265EncodeSupported:s,isH265DecodeSupported:l}=this.checkSystemResult.detail,c=rM.basis(),d={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:n,vp8Encode:o,vp8Decode:a,h265Encode:s,h265Decode:l},u={browser:c.browser,os:c.os,trtc:d,devices:i},h={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};rx.uploadEvent({log:"trtcstats-".concat(JSON.stringify(u)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(u))),rx.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(h)),userId:this.userId}),OL()}))}var Gz=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=eM.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&GD(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];let n=t.apply(i,r);return $D(n)?n.catch((e=>eM.error("".concat(t.name,"() error observed ").concat(e)))):n}catch(CC){eM.error("".concat(t.name,"() error observed ").concat(CC))}}}({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:Iw,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,UO().then((()=>{this._basicInfo.string_os_version=zO(),this._basicInfo.string_device_name=FO()||this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),JO.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(QO.JOIN_START,this.handleJoinStart).addEvent(QO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(QO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(QO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(QO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(QO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(QO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(QO.JOIN_FAILED,this.handleJoinFailed).addEvent(QO.LEAVE_START,this.handleLeaveStart).addEvent(QO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(QO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(QO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(QO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(QO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(QO.PUBLISH_START,this.handlePublishStart).addEvent(QO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(QO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(QO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(QO.PLAY_TRACK_START,this.handlePlayStart).addEvent(QO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(QO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||"PLAYING"===i&&(r===eC.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(QO.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(QO.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(QO.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(QO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(QO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(QO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let o=i.hasAudio||i.hasVideo||i.hasSmall,n=i.hasAuxiliary,a=r.hasAudio||r.hasVideo||r.hasSmall,s=r.hasAuxiliary;!o&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!n&&s&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(QO.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)=>JO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),QL.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&&(jD(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),jD(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),jD(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:o,tls:n,request:a,response:s}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,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: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 mw?Number(i.getExtraCode()||i.getCode()):hw.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=oN()-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 mw?Number(i.getExtraCode()||i.getCode()):hw.UNKNOWN)}}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){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(Qb({},zz),{msg_user_info:new Kz({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};o.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,o)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:o}=e;if(!this.hitTest(t))return;let{userId:n,tinyId:a,role:s}=i,l=new Kz({userId:n,tinyId:a,role:"anchor"===s?20:21}),c=Date.now(),d="".concat(n,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=c),"main"===r?(i.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:n,sendSubscribeCMDTime:c}),i.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:n,sendSubscribeCMDTime:c})):i.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:c})}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),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=i-this._pathJoinRoom.uint64_start_time;t.uint32_video_render_first=e,CP.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:o,audioDelay:n}=e,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=t,a.totalLoss+=i,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,l;o&&(a=o,s=1),n&&(e=n,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:a,audioDelayCount:l,videoDelayCount:s})}})))}handleHeartbeatStats(e){var t;if(this.hitTest(e.room)){let{msg_device_info:i,msg_up_stream_info:r,msg_down_stream_info:o}=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/XM*100)>0&&(this._localStreamStat.totalAudioLevel+=e/XM,this._localStreamStat.audioLevelCount++)}o.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,o=t.str_identifier,n=this._room.remotePublishedUserMap.get(o);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(o,"_").concat(t?"main":"auxiliary"),a=this._remoteStreamStatMap.get(r);if(a&&(t&&null!=n&&n.remoteVideoTrack.isSubscribed||i&&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 i=t?n.remoteVideoTrack:n.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(a.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(a.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*Jb(10,6)))}})),!lN(i)){let e="".concat(o,"_main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&null!=n&&n.remoteAudioTrack.isSubscribed&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,n.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=n.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/XM*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/XM,t.audioLevelCount++),i.uint32_audio_block_time&&(t.statsToReport.uint32_audio_block_time+=i.uint32_audio_block_time))}})),i.uint32_audio_capture_cost&&(this._captureCostSum+=i.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===i.uint32_audio_capture_cost&&!1===(null==(t=this._room.audioManager.localAudioTrack)?void 0:t.muted)&&(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 mw?i.getExtraCode()||i.getCode():hw.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&oC))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&sC))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&aC))>=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:o,videoDelayCount:n,totalAudioDelay:a,totalVideoDelay:s}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),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,eC.AUDIO),e.statsToReport.uint32_video_play_time=o.getDuration(t,eC.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,jz));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:s}=n.getDataFreezeDuration(t),{renderFreeze:l}=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(l,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),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>jz&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+jz):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>jz&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+jz):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>jz&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+jz)}getReportData(){this._basicInfo.uint32_networkType=kD();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Kz({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:uN(this._signalInfo.relayIp),uint32_client_ip:uN(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Jb(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:uN(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 AN(e),e}report(){return nw(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(lM){this._log.warn(lM)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return nw(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=$O.enable?MN(e,2001,t):yield WN(e),r=i instanceof ArrayBuffer,o="".concat(SD(t,Ww.KEY_POINT),"&gzip=").concat(+r),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,i));let a=[this.uploadKVStat(CP),this.uploadKVStat(wP)];n||a.push(HN({url:o,body:i,priority:"low"})),yield Promise.all(a)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return nw(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(Qb({},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=$O.enable?MN(t,2003,this._room.sdkAppId):yield WN(t),r=i instanceof ArrayBuffer,o="".concat(SD(+this._room.sdkAppId,Ww.KV_STAT),"&gzip=").concat(+r),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,i)),n||HN({url:o,body:i})}))}};iw([nx({settings:{timeout:500,retries:3}})],Gz.prototype,"upload",1);var jz=5e3,zz={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},Kz=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}},qz=Gz,Yz=class{constructor(){rw(this,"_startTime"),rw(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=oN())}stop(){0===this._endTime&&(this._endTime=oN())}getDuration(){return 0===this._endTime?oN()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Jz=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(QO.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(QO.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var o;let{userId:n}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(n,"_main"),eC.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(n,"_main"),eC.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(n,"_auxiliary"),eC.VIDEO);let a=null==(o=this._room)?void 0:o.remotePublishedUserMap.get(n);a&&(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,eC.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,eC.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,eC.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>JO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>JO.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:o}=t;t.isSubscribed?this.addDuractionItem(i,o,r):this.stopDurationItem("".concat(i,"_").concat(r),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,i){let r="".concat(e,"_").concat(i),o=new Yz,n=this._durationMap.get(r);n?this.isRecording(n[t])||n[t].push(o):this._durationMap.set(r,{userId:e,type:i,audio:t===eC.AUDIO?[o]:[],video:t===eC.AUDIO?[]:[o]})}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()}},Xz=class{constructor(){rw(this,"renderFreezeMap",new Map),rw(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?"data"===t?r:i:(EO||pk)&&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()}},Qz=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 Xz),rw(this,"_eventMap",new Map),rw(this,"_videoEncodeFailedCount",0),rw(this,"_audioEncodeFailedCount",0),rw(this,"_encodeFailedThreshold",3),rw(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),rw(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),rw(this,"_videoAbnormalTimestampMap",new Map),rw(this,"_remoteVideoAbnormalTimestampMap",new Map),rw(this,"_audioAbnormalTimestampMap",new Map),rw(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(QO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(QO.PLAY_TRACK_START,this.onPlayTrackStart).set(QO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:o}=r,n="".concat(o,"_").concat(i);this.stopDataFreeze({key:n,userId:o,type:i})})).set(QO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:o}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:o,type:e})}})).set(QO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:o}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&o===eC.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===eC.MUTE?this.onVideoTrackMuted(t):r===eC.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(QO.HEARTBEAT_REPORT,this.onHearBeatReport).set(QO.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(QO.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach(((e,t)=>JO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>JO.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),o=this._dataFreezeMap.get(r),n=new Yz;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:t,type:i,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:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&(this.localMediaTrackDetector(i),this.remoteMediaTrackDetector(i))}remoteMediaTrackDetector(e){e.msg_down_stream_info.length>0&&e.msg_down_stream_info.forEach((e=>{var t;if(0===e.msg_video_status.length)return;let i=e.msg_user_info.str_identifier,r=null==(t=this._room.remotePublishedUserMap.get(i))?void 0:t.remoteVideoTrack;e.msg_video_status.forEach((e=>{let t=oN();if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>0&&0===e.uint32_video_receive_fps&&null!=r&&r.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-decode"))){let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-decode"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-decode"));e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&(rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-decode")))}if(void 0!==e.uint32_video_codec_bitrate&&e.uint32_video_codec_bitrate>5e5&&void 0!==e.uint32_video_dec_fps&&e.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(i,"-hardware"))){let r=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));if(r&&t-r>this.ABNORMAL_TIME_LOWER_LIMIT/2&&t-r<2*this.ABNORMAL_TIME_UPPER_LIMIT){rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_HARDWARE_DECODE_FAILED)});let t=this._room.remotePublishedUserMap.get(i);if(t){let i=2===e.uint32_video_stream_type?t.remoteVideoTrack:t.remoteAuxiliaryTrack;i&&(i.log.warn("decode failed during call"),i.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(i,"-hardware"),t);else{let e=this._remoteVideoAbnormalTimestampMap.get("".concat(i,"-hardware"));e&&t-e>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(i,"-hardware")))}}))}))}localMediaTrackDetector(e){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,i=Array.from(this._room.localTracks).find((e=>"video"===e.kind&&!e.isScreen)),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;t.forEach((e=>{let t=oN();if(2===e.uint32_video_stream_type)if(0!==e.uint32_video_capture_fps&&0===e.uint32_video_codec_bitrate&&0===e.uint32_video_enc_fps&&null!=i&&i.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>this.ABNORMAL_TIME_LOWER_LIMIT&&t-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",t);else{let e=this._videoAbnormalTimestampMap.get("local-encode");e&&t-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}}))}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,i=Array.from(this._room.localTracks).find((e=>"audio"===e.kind)),r=(null==i?void 0:i.stat.bytesSent)||0;if(!1===(null==i?void 0:i.isMediaTrackActive)||r<=0||null!=i&&i.isUseCustomSource)return;let o=oN();if(0===t.uint32_audio_codec_bitrate&&null!=i&&i.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>this.ABNORMAL_TIME_LOWER_LIMIT&&o-e<this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.AUDIO_ENCODE_FAILED_DURING_CALL)})}else this._audioAbnormalTimestampMap.set("local-encode",o);else{let e=this._audioAbnormalTimestampMap.get("local-encode");e&&o-e>=this.ABNORMAL_TIME_UPPER_LIMIT&&rx.uploadEvent({userId:this._room.userId,log:"stat-".concat(NC.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(e){let{key:t,userId:i,type:r}=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();if(a>VC){let e=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:e?e.duration+a:a},"data")}else o.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!==eC.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()<VC&&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(!CL())return;let o=0,n=()=>{document.hidden||(o=0)};document.addEventListener("visibilitychange",n);let a=(e,r)=>{var n;if(o){let e=t.decodeFPS,i=e>0&&e<=5?600+1e3/e:600,n=r.presentationTime-o;if(n>i){n=Math.min(n,5e3);let e="".concat(t.userId,"_").concat(t.streamType),i=this._monitorFreezeData.get(e,"render");i?i.duration+=n:this._monitorFreezeData.set(e,{userId:t.userId,type:t.streamType,duration:n},"render");let r=this._renderFreezeMap.get(e);r?(r.totalDuration+=n,r.count+=1):this._renderFreezeMap.set(e,{userId:t.userId,type:t.streamType,totalDuration:n,count:1})}}o=r.presentationTime,null==(n=i.element)||n.requestVideoFrameCallback(a)};null==(r=i.element)||r.requestVideoFrameCallback(a),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:n})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),o=this.eventListenerMap.get(r);o&&document.removeEventListener("visibilitychange",o.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},$z=tw(aw(),1),Zz=class{constructor(e,t,i,r,o){let n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4/3;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,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,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?CP.addSuccessEvent({key:r.key}):CP.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,o=t.originX,n=t.originY,a=t.width,s=t.height;1===this.vbMode?this.dualStageCropping(i,r,o,n,a,s):2===this.vbMode&&this.movingPortrait(i,r,o,n,a,s)}catch(pM){this.logger.error(pM)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let o,n;return e>t/2?(o=t-i-r,n=i-o):(o=i,n=0),{min:o,offset:n}}calculateTargetPosition(e,t,i,r,o,n){let a,s,l=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,c=e+i/2,d=t+r/2,{min:u,offset:h}=this.calculateBoundary(c,o,e,i),{min:p,offset:m}=this.calculateBoundary(d,n,t,r);return a=2*u+i,s=2*p+r,a/s>this.originalAspect?(a=s*this.originalAspect,h=c-a/2):(s=a/this.originalAspect,m=d-s/2),i/o>l&&(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,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),o=this.positionDistance(this.animationState.current,e),n=this.animationState.current.cropWidth/t;r>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=Qb({},e),void(this.animationState.target=Qb({},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)),KD(this.animationState.current.scaleOffsetX)&&KD(this.animationState.target.scaleOffsetX)&&KD(this.animationState.current.scaleOffsetY)&&KD(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(Jb(e.sx-t.sx,2)+Jb(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,o,n){let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(this.isRecovering)return;let s=this.calculateTargetPosition(i,r,o,n,e,t);this.processFacePositionCrop(s,e,t),o*n/s.cropWidth/s.cropHeight>a&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,o,n){var a,s,l,c,d,u,h,p,m,f,_,g;let E={sx:i+o/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(s=null==(a=this.animationState.current)?void 0:a.scaleRatio)?s:1,scaleOffsetX:null!=(c=null==(l=this.animationState.current)?void 0:l.scaleOffsetX)?c: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+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}},eK=class extends NB{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 mw({code:hw.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(t.message||t)})),this.resolvePreditReady()}))}init(e){return nw(this,null,(function*(){var t,i,r;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!=(i=e.enableEffectOptimization)&&i,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:i,width:r,height:o}=e.waterMark;this.wasm.setWaterMark(t,i,r,o)}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),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:LO()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):null==(r=this._postProcessing)||r.init(n,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)}))}initVisionTasks(e){return nw(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 Zz(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch(CC){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(),DN(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:o}=i;if(DN(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,o]=[o,r]),0===r||0===o||!this.available)return!1;i.width=r,i.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===r&&this.height===o&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,o),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,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,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(hM){this._onAbort&&this._onAbort(hM)}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:o=1,scaleOffsetX:n=0,scaleOffsetY:a=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+n,a,0]),this._mat4.scale(r,r,[o,o,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){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+r)/a,0]),this._mat4.scale(s,s,[i/n,r/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()}},tK=class extends yB{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 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)}},iK=(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 rK=0,oK=class{constructor(e){rw(this,"id",rK++),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:i}=e;if(this.stateChangeOB=vV(),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=OV(t.availableState,zL.OFF),this.stopOB=vV(),"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),$U(this.stateChangeOB,IF(((e,i)=>(e!==i&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:e,state:i}),i)),"INITIALIZED"),eF(this.stopOB),tB()),this.start()}start(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=$U(this.pipe(this.track),eF(this.stopOB),aV());$U(t,tB((()=>{this.track.stat.framesDecoded++}),(t=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(t," retryCount: ").concat(e)),CP.addFailedEvent({key:iK(this.type,this.renderer),error:t}),e>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),CP.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")),CP.addSuccessEvent({key:iK(this.type,this.renderer)}),CP.addSuccessEvent({key:514704})}))),$U(t,ZV(1),tB((()=>{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&&!UP()&&(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 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==(i=this.decoder)?void 0:i.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=oN()}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=>nw(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:o,type:n}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(n){case"wasm":i=this.createDecoder(n,this.wasmOption);break;case"webCodecs":i=this.createDecoder(n);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"===n?4:8)})),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),"wasm"===n&&"webgl"===o){this.videoContext=new LB({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(LB.UNAVAILABLE,(i=>{e.log.error(i),t.error(7)}));let r=new tK(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"===o){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 xB({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(o){delete this.goodType,e.log.error(o),t.error(11)}}));let o=new SB(this.videoContext,{name:"remotePlayer",logger:e.log});r.connect(o),e.source=r,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(dM){e.log.error(dM),t.error("webCodecs"===n?2:6)}}))}},nK=Promise.resolve(),aK=class extends $z.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"),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",nK),rw(this,"_updateFlag",!1),this.log=eM.createLogger({parent:null==e?void 0:e.getLogger(),id:"vm",userId:null==e?void 0:e.userId,sdkAppId:null==e?void 0:e.sdkAppId}),this.smallVideoContext=new xB({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 DN(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new xB({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 LB({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(gO<=22),this._glVideoContext.on(LB.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(Sw){this.emit("error",Sw)}}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=QL.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(),QL.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vO||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?CP.addFailedEvent({key:t,error:e}):CP.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 LB({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 wB(this.smallVideoContext,e,this.log),this.smallVideoContext.on(LB.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:o}=i;vO&&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(r,e),i.setOutputMediaStreamTrack(n)}catch(cM){this.log.error("set main output failed",cM)}}update(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return nw(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(yB.RENDER,(e=>{var t;null==(t=this.cameraTrack)||t.emit("render",e)}))),16===RO?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof NB?(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 NB?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 bB(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(yB.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 eK(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 HB(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 FB(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,o,n;if(e instanceof zB)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof fB)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof eH){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 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 zB?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof fB?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 eH?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 nw(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 nw(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 mw({code:hw.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((i=>{let{image:o,x:n,y:a,width:s,height:l,fillVideo:c}=i,d=c&&e||s,u=c&&t||l,h=c?0:n,p=c?0:a;r.drawImage(o,h,p,d,u)})),TN(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&&t.fillVideo===e.fillVideo))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return nw(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return nw(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return nw(this,null,(function*(){let t;try{t=yield TN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(nM){throw new mw({code:hw.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:o=t.width,height:n=t.height,type:a="watermark",zIndex:s=2,fillVideo:l=!1}=e;this.watermarkImageList.some((e=>e.type===a))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==a)),this.pushWaterMarkImageList({x:i,y:r,width:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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:o,height:n,image:t,zIndex:s,type:a,imageUrl:e.imageUrl,fillVideo:l}),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 nw(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 nw(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 nw(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 TN(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 mw({code:hw.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 nw(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 oK(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}};iw([function(e){return OU(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return nw(this,null,(function*(){try{return yield t.apply(this,r)}catch(cM){e.call(this,cM)}}))}))}((function(e){this.log.error("update failed",e)})),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){this._updateFlag||(this._updateFlag=!0,yield nK,this.updated=new Promise(((t,r)=>{e.apply(this,i).then(t,r),setTimeout(r,5e3,new mw({code:hw.API_CALL_TIMEOUT,message:"update timeout"}))})),this._updateFlag=!1,yield this.updated)}))}))],aK.prototype,"update",1);var sK=0,lK=class extends zL{constructor(e){super("room"),rw(this,"seq",++sK),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"),rw(this,"_joinedTimestamp",0),rw(this,"_sdkType"),rw(this,"heartbeatReport"),rw(this,"heartbeatCount",0),rw(this,"quality"),rw(this,"enableSEI"),rw(this,"isDestroyed",!1),this._log=eM.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,qD(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),qD(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),qD(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new qz({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Jz({room:this}),this.badCaseDetector=new Qz({room:this}),this.audioManager=new JB(this),this.videoManager=new aK(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 nw(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return nw(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return nw(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(zD(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(FD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:o,unifiedProxy:n}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=n,n?(bj([n,n]),Nw("https://".concat(n))):(r&&Nw(r),o&&bj(o))}JO.once(QO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:Rj.main,sched_back_domain:Rj.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return nw(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return nw(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 nw(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 mw({code:hw.INVALID_OPERATION,message:fP({key:uP.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(hP.INVALID_DESTROY),new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.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,JO.emit(QO.ROOM_DESTROY,{room:this})}schedule(e,t){return nw(this,null,(function*(){var i,r,o,n;let a=oN();try{let{isCached:s,result:l,detailCost:c}=yield Sj({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Iw,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(gN(l,{keysToExclude:["username","credential"]}))),s&&JO.once(QO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=Qb(Qb({},this.scheduleResult),l),KD(null==(i=l.config)?void 0:i.retryCount)&&bC(l.config.retryCount),zD(null==(r=l.config)?void 0:r.loggerDomain)&&Nw(l.config.loggerDomain),this.videoDecodeFallbackType=(null==(o=l.config)?void 0:o.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(n=l.config)?void 0:n.smallMode)||this.smallMode,JO.emit(QO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),CP.addSuccessEvent({key:521700,cost:oN()-a})}catch(aM){throw CP.addFailedEvent({key:521700,error:aM}),aM}}))}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var cK={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},dK="__INLINE__WORKER__",uK="__INLINE__WASM__",{debug:hK}=console;cK.debug||(console.debug=()=>{});var pK,mK=!dK.startsWith("__"),fK=!uK.startsWith("__");function _K(){let e=bN("".concat(cK.assetsPath?"".concat(cK.assetsPath,"/"):"","worker.js"));return mK?URL.createObjectURL(new Blob([atob(dK)],{type:"application/javascript"})):e.startsWith("http")?fetch(e).then((e=>e.blob().then((e=>URL.createObjectURL(e))))):e}function gK(){return nw(this,null,(function*(){let e=cK.assetsPath?"".concat(cK.assetsPath,"/"):"";return pK||(pK=fK?(new TextEncoder).encode(atob(uK)).buffer:yield fetch(bN("".concat(e,"av_processing.wasm"))).then((e=>e.arrayBuffer())),pK)}))}var EK=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 nw(this,null,(function*(){let e=qx(),t=_K();try{yield e.audioWorklet.addModule("string"==typeof t?t:yield t),eM.info("global audio player worklet addModule success",t)}catch(CC){throw eM.error("global audio player worklet addModule failed:",CC),CC}return this.worklet=new AudioWorkletNode(e,"global-audio-player",{processorOptions:{wasm:yield gK(),flag:cK},numberOfInputs:2}),eM.info("global audio player worklet created",e.state),this.playPort=this.worklet.port,this.playPort}))}playAudio(e){return nw(this,null,(function*(){var t;yield this.init();let i=new MessageChannel;null==(t=this.playPort)||t.postMessage(null,[i.port1]),e(i.port2)}))}},vK="undefined"!=typeof self&&(!("top"in self)||self===top)&&"showOpenFilePicker"in self&&"showOpenFilePicker";vK?Promise.resolve().then((function(){return AK})):Promise.resolve().then((function(){return DK})),vK?Promise.resolve().then((function(){return wK})):Promise.resolve().then((function(){return NK}));var yK=vK?Promise.resolve().then((function(){return CK})):Promise.resolve().then((function(){return kK}));function TK(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){return(yield yK).default(...t)}))}var IK=e=>nw(void 0,null,(function*(){let t=yield e.getFile();return t.handle=e,t})),AK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{t[i]={description:e.description||"Files",accept:{}},e.mimeTypes?e.mimeTypes.map((r=>{t[i].accept[r]=e.extensions||[]})):t[i].accept["*/*"]=e.extensions||[]}));let i=yield window.showOpenFilePicker({id:e[0].id,startIn:e[0].startIn,types:t,multiple:e[0].multiple||!1,excludeAcceptAllOption:e[0].excludeAcceptAllOption||!1}),r=yield Promise.all(i.map(IK));return e[0].multiple?r:r[0]}()}))}};function SK(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 SK=function(e){this.s=e,this.n=e.next},SK.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?Promise.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Promise.reject(e):t(i.apply(this.s,arguments))}},new SK(e)}var RK,bK=function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),o=2;o<i;o++)r[o-2]=arguments[o];return nw(void 0,[e,t,...r],(function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.name,r=arguments.length>3?arguments[3]:void 0;return function*(){let o=[],n=[];var a,s=!1,l=!1;try{for(var c,d=function(e){var t,i,r,o=2;for("undefined"!=typeof Symbol&&(i=Symbol.asyncIterator,r=Symbol.iterator);o--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new SK(t.call(e));i="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}(e.values());s=!(c=yield d.next()).done;s=!1){let a=c.value,s="".concat(i,"/").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||r&&r(a)||o.push(bK(a,t,s,r))}}catch(u){l=!0,a=u}finally{try{s&&null!=d.return&&(yield d.return())}finally{if(l)throw a}}return[...(yield Promise.all(o)).flat(),...yield Promise.all(n)]}()}))},wK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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 bK(t,e.recursive,void 0,e.skipDirectory)}()}))}},CK={__proto__:null,default:function(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 nw(void 0,[e,...i],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[{}],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=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((i=>{n[t].accept[i]=e.extensions||[]}))):a?n[t].accept[a]=e.extensions||[]:n[t].accept["*/*"]=e.extensions||[]})),i)try{yield i.getFile()}catch(c){if(i=null,r)throw c}let s=i||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:n,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!i&&o&&o(s);let l=yield s.createWritable();return"stream"in e?(yield e.stream().pipeTo(l),s):"body"in e?(yield e.body.pipeTo(l),s):(yield l.write(yield e),yield l.close(),s)}()}))}},DK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{let r=document.createElement("input");r.type="file";let o=[...e.map((e=>e.mimeTypes||[])),...e.map((e=>e.extensions||[]))].join();r.multiple=e[0].multiple||!1,r.accept=o||"",r.style.display="none",document.body.append(r);let n=e=>{"function"==typeof a&&a(),t(e)},a=e[0].legacySetup&&e[0].legacySetup(n,(()=>a(i)),r),s=()=>{window.removeEventListener("focus",s),r.remove()};r.addEventListener("click",(()=>{window.addEventListener("focus",s)})),r.addEventListener("change",(()=>{window.removeEventListener("focus",s),r.remove(),n(r.multiple?Array.from(r.files):r.files[0])})),"showPicker"in HTMLInputElement.prototype?r.showPicker():r.click()}))}()}))}},NK={__proto__:null,default:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(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,i)=>{let r=document.createElement("input");r.type="file",r.webkitdirectory=!0;let o=e=>{"function"==typeof n&&n(),t(e)},n=e[0].legacySetup&&e[0].legacySetup(o,(()=>n(i)),r);r.addEventListener("change",(()=>{let t=Array.from(r.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?r.showPicker():r.click()}))}()}))}},kK={__proto__:null,default:function(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 nw(void 0,[e,...i],(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){Array.isArray(t)&&(t=t[0]);let i=document.createElement("a"),r=e;"body"in e&&(r=yield function(e,t){return nw(this,null,(function*(){let i=e.getReader(),r=new ReadableStream({start:e=>function t(){return nw(this,null,(function*(){return i.read().then((i=>{let{done:r,value:o}=i;if(!r)return e.enqueue(o),t();e.close()}))}))}()}),o=new Response(r),n=yield o.blob();return i.releaseLock(),new Blob([n],{type:t})}))}(e.body,e.headers.get("content-type"))),i.download=t.fileName||"Untitled",i.href=URL.createObjectURL(yield r);let o=()=>{"function"==typeof n&&n()},n=t.legacySetup&&t.legacySetup(o,(()=>n()),i);return i.addEventListener("click",(()=>{setTimeout((()=>URL.revokeObjectURL(i.href)),3e4),o()})),i.click(),null}()}))}},OK=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 i;null==(i=this.worker)||i.postMessage(e,t)}create(e){return nw(this,null,(function*(){if(this.ready)return this.ready;e||(e=this.name),console.time("createWorker_".concat(e));let t=_K(),i=new Worker("string"==typeof t?t:yield t,{name:e});return this.worker=i,this.ready=new Promise(((t,r)=>nw(this,null,(function*(){i.onmessage=i=>{let{data:{id:o,type:n,payload:a}}=i;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),r(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(_N(),a.group,a.name,e,"👉",t)}break;case"log":console.log(a);break;case"glog":window.dispatchEvent(new CustomEvent(n,{detail:a}))}},i.postMessage({wasm:yield gK(),flag:cK},this.ports)}))))}))}destroy(){var e;console.log("destroy worker",this.name),delete this.ready,null==(e=this.worker)||e.terminate()}},MK=class{constructor(e,t,i){this.worker=e,rw(this,"channel",new MessageChannel),rw(this,"ready"),this.ready=new Promise(((e,i)=>{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=i),e)))}postMessage(){this.channel.port1.postMessage(...arguments)}destroy(){0==--this.worker.sessionCount&&this.worker.destroy()}},PK=new class e extends OK{constructor(){super("main"),rw(this,"switchValue",new Map),rw(this,"extendChannel"),rw(this,"sessionCount",0)}setSwitchValue(e,t){var i;this.switchValue.set(e,t),null==(i=this.extendChannel)||i.port1.postMessage([e,t])}create(){return nw(this,null,(function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield ow(e.prototype,this,"create").call(this),this.switchValue.forEach(((e,t)=>{this.extendChannel.port1.postMessage([t,e])})),this)}))}},LK=-1;function xK(e){return console.log(e),RK.push(e.slice()),RK.length>1e3&&RK.shift(),e}function UK(e){return nw(this,null,(function*(){switch(LK){case 0:this.edpl.willDecodeAudio=xK;break;case 2:this.edpl.didEncodeAudio=xK}yield PK.create(),JO.emit(QO.JOIN_SEND_CMD,{room:this});let t=new MK(PK,e,(e=>{let i=e.data;if("string"==typeof i)this.onWorkerEvent(i);else if(null==i)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:e,payload:t}=i;this.onWorkerEvent(e,t)}})),{err:i,data:r}=yield t.ready;if("number"==typeof i){if(JO.emit(QO.JOIN_RECEIVED_CMD_RES,{room:this,code:i}),0===i)return Object.assign(this,r,{session:t});throw new mw({code:hw.JOIN_ROOM_FAILED,extraCode:Number(i),message:fP({key:uP.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i,errorMsg:""}})})}throw i}))}function VK(e){return nw(this,null,(function*(){PK.setSwitchValue("useAINS",e)}))}function FK(e){return nw(this,null,(function*(){PK.setSwitchValue("useV2",e)}))}function BK(e){let t=new MediaStreamTrackGenerator({kind:"audio"});e.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:e.tinyId,writable:t.writable}},[t.writable])}function HK(e){return nw(this,null,(function*(){var t;this._log.info("pull video",e);let i=Date.now(),r=0,o=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:e.mediaType,tinyId:e.tinyId}},[o.port1]),(t=e.stat).framesReceived||(t.framesReceived=0),$U(function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=Object.defineProperties(vV(),{postMessage:{value:e.postMessage.bind(e)},port:{get:()=>e,set(t){e.onmessage=WU,e.onmessageerror=WU,e=t,r()}}});function r(){e.onmessage=r=>{r.data?r.ports.length||t?i.next(r):i.next(r.data):(i.complete(),e.close())},e.onmessageerror=t=>{i.error(t),e.close()}}return r(),i}(o.port2),eF(OV(e,zL.INIT)),tB((t=>{let{data:o,packetsReceived:n}=t;e.stat.packetsReceived=n,e.stat.framesReceived++,r++;let a,s=31&o[4];if(r<=10){let e=Array.from(o.slice(0,10)).map((e=>e.toString(16).padStart(2,"0"))).join(" ");this._log.info("Frame ".concat(r," - Size: ").concat(o.length," bytes, Type: ").concat(s,", Timestamp: ").concat(Date.now()-i,"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()-i)}):console.warn("track is not available")}),(()=>{}),(()=>{o.port2.postMessage(null),o.port2.close()})))}))}Object.defineProperties(window,{useAINS:{set:VK},useWt:{set:function(e){return nw(this,null,(function*(){PK.setSwitchValue("useWt",e)}))}},enableDebug:{set(e){console.debug=e?hK:()=>{},PK.setSwitchValue("enableDebug",e)}},useV2:{set:FK},dump:{value(){if(LK=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,RK||(console.warn("dump audio will be activated at next time join room"),RK=[]),!RK.length)return void console.warn("no audio data to dump,try it later");let e=[];return RK.forEach((t=>{e.push(new Uint16Array([t.length])),e.push(t)})),TK(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,i=[],r=new Promise((r=>{let o=new MessageChannel;PK.extendChannel.port1.postMessage(["dump",e],[o.port1]),o.port2.onmessage=n=>{let{data:a}=n;console.log(a),i.push(a),i.length>t&&(o.port2.onmessage=null,PK.extendChannel.port1.postMessage(["dump",e]),o.port2.close(),r(new Blob(i)))}}));return TK(r,{fileName:e,extensions:[".pcm"]})}},hardDec:{set(e){switch(e){case!0:cK.useHardDecoder="prefer-hardware";break;case!1:cK.useHardDecoder="prefer-software";break;default:cK.useHardDecoder="no-preference"}}}});var WK=[];function GK(e){var t;let i=vV();if("joined"!==this.state)throw new Error("Room is not joined");if("publish"===e.state)return;for(let c=0;c<=WK.length;c++)if(!WK[c]){WK[c]=this,this.index=c;break}let r=e.profile;this._log.info("start push audio",this.index,r);let o=new MessageChannel,n=e.enableEncryptFrame?new MessageChannel:null;null==(t=this.session)||t.postMessage({cmd:"pushAudio",payload:Qb({index:this.index},r)},n?[o.port2,n.port2]:[o.port2]),o.port1.onmessage=t=>{null==t.data||("number"==typeof t.data?i.next(t.data):n&&n.port1.postMessage($b(Qb({},t.data),{data:new Uint8Array(e.encodeFrame({data:t.data.data.buffer,timestamp:t.data.timestamp}).data)})))};let a,s=new MediaStream,l=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=qx().createMediaStreamSource(s),a.connect(EK.worklet,0,this.index)};$U(OV(e,"output-media-track-changed"),eF(OV(e,"ready")),tB(l,console.error,(()=>{this._log.info("stop push audio",r),e.volume=0,a.disconnect(),WK[this.index]=null,n&&n.port1.postMessage(null),o.port1.postMessage(null)}))),$U(i,iB((t=>e.volume=t)),MF(IB(1e3)),tB((()=>{e.volume=0}))),l(e.outMediaTrack)}var jK=class{constructor(e,t,i,r){this.localTrack=e,this.type=t,this.config=i,this.port=r,rw(this,"track"),rw(this,"label"),rw(this,"insertKeyFrame",!0),rw(this,"session"),rw(this,"tsMap",new Map),rw(this,"startTime",0),rw(this,"startTimestamp",0),e._log.info("create Video Encoder",i)}trans(e,t,i){return nw(this,null,(function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});t.signal.addEventListener("abort",(()=>{r.encoder.close()}));let o=0;return e.pipeThrough(new TransformStream({transform:(e,t)=>{"configured"===r.encoder.state&&(this.tsMap.set(o,Date.now()),this.encode(e),o++,t.enqueue(e))}}),t)}))}encode(e){var t,i;null==(i=null==(t=this.session)?void 0:t.encoder)||i.encode(e,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(e,t,i){return nw(this,null,(function*(){let r=yield this.recreate(i,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=r;let o=0;e.pipeTo(new WritableStream({write:e=>{let t=Date.now();"configured"===r.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},r)),126===fO?this.tsMap.set(o,oN()):0===o&&(this.startTime=t,this.startTimestamp=e.timestamp),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),r.encoder.close()}))}))}recreate(e,t){return nw(this,null,(function*(){let i=0,r=new VideoEncoder({output:r=>{let o=126===fO?this.tsMap.get(i):(this.startTime+(r.timestamp-this.startTimestamp)/1e3&4294967295)>>>0;if(126===fO&&this.tsMap.delete(i),i<10&&(0===i&&0===t.recreateCount&&JO.emit(QO.SEND_FIRST_VIDEO_FRAME,{room:e}),this.localTrack.log.info("encoded ".concat(this.label," track frame:"),i,Date.now(),r.timestamp)),i++,t.frameEncoded=i,!1===this.track.enabled)return;let n=null;if(this.localTrack.enableEncodeFrame){n=new Uint8Array(r.byteLength),r.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:r.type,timestamp:r.timestamp,data:n,duration:r.duration},timestamp:o},[n.buffer])):(this.localTrack.stat.bytesSent+=r.byteLength,this.port.postMessage({chunk:r,timestamp:o}))},error:i=>{this.localTrack.log.warn(i,this.config),t.recreateCount++,setTimeout((()=>this.recreate(e,t)),100)}});return t.encoder=r,yield this.configure(null,t),t}))}configure(e,t){return nw(this,null,(function*(){var i;e&&Object.assign(this.config,e),null==(i=t.encoder)||i.configure(this.config)}))}close(){this.port.postMessage(null),this.port.close()}};function zK(e,t){return nw(this,null,(function*(){let i=2===e.mediaType,r=i?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:cK.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 jK(e,t.type,o,n.port2);return n.port2.onmessage=e=>{if(260===e.data)a.insertKeyFrame=!0;else if(!i){let{bitrate:t}=e.data;UD({configureBr:[e.data.bitrate,t]}),a.session&&a.configure({bitrate:t},a.session)}},this._log.info("start push",r,t),a}))}function KK(e){return nw(this,null,(function*(){var t;let i=2===e.mediaType,r=i?"screen":"video",o={type:i?7:2,profile:e.profile,trackType:i?"screen":"camera",crypto:!(null==(t=e.manager)||!t.encodePipeline[0])};!i&&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 l=yield zK.call(this,e,o);this._log.info("VideoEncoder created",o);let c,d=t=>nw(this,null,(function*(){if(null==c||c.abort("track changed"),!t)return;c=new AbortController;let{width:i,height:o,displaySurface:a}=t.getSettings();i&&(l.config.width=i),o&&(l.config.height=o);let s,d=QN.match(/Chrome\/(\d+)/);"114"===(null==d?void 0:d[1])&&"browser"===a&&delete l.config.hardwareAcceleration,this._log.info("push",r,"track:",t.readyState,t.getSettings()),s="undefined"==typeof MediaStreamTrackProcessor||t instanceof CanvasCaptureMediaStreamTrack?new ReadableStream({start(t){e.on("render",(i=>{if(0!==e.player.mode||document.hidden)try{t.enqueue(new VideoFrame(i,{timestamp:1e3*performance.now()}))}catch(r){console.warn(r)}}))},pull(t){return nw(this,null,(function*(){if(0===e.player.mode&&CL()&&e.player.element)return new Promise((i=>{e.player.element.requestVideoFrameCallback(((r,o)=>{try{let i=new VideoFrame(e.player.element);t.enqueue(i)}catch(gP){console.warn(gP)}i()}))}))}))}}):new MediaStreamTrackProcessor({track:t}).readable;let u="small"in e&&e.small;return u?(this.smallEncoder||(this.smallEncoder=yield zK.call(this,e,{profile:u,type:3,trackType:n})),this.smallEncoder.track=t,this.smallEncoder.label="small",s=yield this.smallEncoder.trans(s,c,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),l.track=t,l.label=r,l.start(s,c,this)}));return $U(OV(e,"output-media-track-changed"),eF(OV(e,"ready")),tB(d,console.error,(()=>{var e;this._log.info("stop push",r,o),c.abort("unpublish"),l.close(),null==(e=this.smallEncoder)||e.close()}))),d(e.outMediaTrack)}))}var qK=class e extends zL{constructor(t){var i,r;super(null!=(r=null==(i=t.roomid)?void 0:i.toString())?r:t.name,"volumeEvaluation"),this.room=t,rw(this,"enableInBackground",!1),rw(this,"interval",400),t.on("joined",(()=>{this.emit(e.INTERVALCHANGED,this.interval)})),$U(OV(this,e.INTERVALCHANGED),kF((e=>"joined"===this.room.state?this.room.fromWorker("getAudioEnergy",e):$U((e=>t=>{let i=0,r=performance.now();$U(TB,RF((t=>(t-r)/e|0)),QV((e=>e!=i&&(i=e,!0))))(t)})(e),RF((()=>[]))))),tB((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==zL.ON&&this.room.emit("audio-volume",e)})))}start(t,i){this.interval=t,this.enableInBackground=i,this.emit(e.INTERVALCHANGED,this.interval)}stop(){}};rw(qK,"INTERVALCHANGED","intervalChanged"),iw([WL([zL.INIT,zL.OFF],zL.ON)],qK.prototype,"start",1),iw([WL([],zL.OFF)],qK.prototype,"stop",1);var YK=qK,JK=class extends lK{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 YK(this)),rw(this,"enableAIVoice",VK),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:KO(),uint32_device_type:0,str_os_verion:qO(),uint32_link_type:1,str_client_version:Iw,uint32_net_type:qw[vw.getNetworkType()],ua:navigator.userAgent,version:""}}),rw(this,"joinAbortController",new AbortController),rw(this,"smallAbortCtrl"),rw(this,"smallEncoder"),e.tinyId&&(this.tinyId=e.tinyId,FK(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return nw(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(((i,r)=>{"joined"!=this.state&&r("join room first");let o=new MessageChannel;this.postMessage({cmd:e,payload:t},[o.port1]),o.port2.onmessageerror=r,o.port2.onmessage=e=>{o.port2.close(),i(e.data)}}))}fromWorker(e,t){if("joined"!=this.state)throw"join room first";return i=>{var r;let o=new MessageChannel;o.port2.onmessage=e=>{e.data?i.next(e.data):i.complete()},o.port2.onmessageerror=e=>i.error(e),i.defer((()=>{o.port2.postMessage(null),o.port2.close()})),null==(r=this.session)||r.postMessage({cmd:e,payload:t},[o.port1])}}switchRole(e){return nw(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,i){return nw(this,null,(function*(){var r;let o=vw.getEnv(),n=kP(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:i,params:e,proxy_wt:this.proxy_wt,proxy_ws:this.proxy_ws,proxy_cloud:null!=(r=this.scheduleResult.iceServers)&&r.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:o,osName:WO(),browserInfo:kP(),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:Iw,browserVersion:n.browserName+n.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 UK.call(this,a),console.log(this),EK.playAudio((e=>this.postMessage({cmd:"setAudioWorkletPort"},[e]))),this.checkDestroy()}))}leave(){return nw(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 nw(this,null,(function*(){let e=eF(OV(this,"left")),t=this.audioManager.decodePipeline.some((e=>e));$U((e=>nw(this,null,(function*(){let i=new MessageChannel;i.port2.onmessage=t=>{t.data?e.next({data:t.data,port:i.port2}):e.complete()},i.port2.onmessageerror=t=>e.error(t),e.defer((()=>{i.port2.postMessage(null),i.port2.close()})),this.postMessage({cmd:"decodeAudio",payload:t},[i.port1])}))),e,tB((e=>{let{data:t,port:i}=e;var r;let o={data:t.data.buffer};for(let[n,a]of this.audioManager.decodePipeline.entries())if(a&&(o=a({frame:o,track:null==(r=this.remotePublishedUserMap.get(t.userId))?void 0:r.remoteAudioTrack}),!o))return;i.postMessage($b(Qb({},t),{data:new Uint8Array(o.data)}),[o.data])})))}))}onWorkerEvent(e,t){switch("network-quality"!==e&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(t)),e){case QO.RECEIVED_PUBLISHED_USER_LIST:return void JO.emit(e,Qb({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 i=new Bz(this,t);return this.remotePublishedUserMap.set(t.userId,i),void this.emit("remote-published",i);case"5":{let e=t,i=this.remotePublishedUserMap.get(e);i&&(i.remoteVideoTrack.close(),i.remoteAuxiliaryTrack.close(),i.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(e),this.emit("remote-unpublished",i))}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:i,flag:r}=t,o=this.remotePublishedUserMap.get(i.userId);if(!o)return void this.emit("remote-publish-state-changed",t);o.flag=r}return JO.emit(QO.REMOTE_PUBLISH_STATE_CHANGED,Qb({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=Qb({},t);let{uplinkLoss:r,uplinkRTT:o,uplinkInfo:n,downlinkInfo:a,msg_down_stream_info:s}=t,l={str_sdk_version:Iw,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:qw[bD()]},msg_event_msg:oH(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:n,msg_down_stream_info:s};JO.emit(QO.HEARTBEAT_REPORT,{room:this,report:l}),this.emit("heartbeat-report",l),JO.emit(QO.NETWORK_QUALITY,{room:this,uplink:{rtt:o,loss:r},downlinks:a}),delete t.downlinkInfo;break;case"signal-connection-state-changed":return void JO.emit(QO.SIGNAL_CONNECTION_STATE_CHANGED,Qb({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(e){return nw(this,null,(function*(){if(1===(yield this.sendMessage("publish",e.mediaType).then((e=>0!==e.err?Promise.reject(e.err):e)),tx(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))yield EK.init(),GK.call(this,e);else yield KK.call(this,e);e.muted&&this.postMessage("mute",{mediaType:e.mediaType,srctinyid:this.tinyid,userId:this.openid,remove:!0})}))}unpublish(e){return nw(this,null,(function*(){ix(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){let e=t.reduce(((e,t)=>t.mediaType|e),0),{userId:i,tinyId:r,streamType:o}=t[0],n=this.remotePublishedUserMap.get(i),a=Qb({},n.subscribeState),s=Object.assign(new $M,a);s.mediaType|=e,JO.emit(QO.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:n,subscribeState:s});let l=yield this.sendMessage("subscribe",{mediaType:s.mediaType,userId:i,srctinyid:r,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",l),yield Promise.all(t.filter((e=>!e.isSubscribed)).map((e=>1===e.mediaType?BK.call(this,e):HK.call(this,e)))),JO.emit(QO.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:n})}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return nw(this,null,(function*(){let e=0;for(let i of t)e|=i.mediaType;if(t.length){let{userId:i,streamType:r,tinyId:o}=t[0];yield this.sendMessage("unSubscribe",{mediaType:e,srctinyid:o,userId:i});for(let e of t)e.unsubscribe();JO.emit(QO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:this.remotePublishedUserMap.get(i)})}}))}enableSmall(e){return nw(this,null,(function*(){var t;if(e){if(this.videoManager.smallTrack){let e=this.videoManager.cameraTrack;this.smallEncoder=yield zK.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 i=this.remotePublishedUserMap.get(t.userId);if(!i)return;let r=e?8:4;if(i.remoteVideoTrack.mediaType===r)return;let o={srctinyid:i.tinyId,mediaType:r,userId:t.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter((e=>r&e)).map((e=>({mediaType:e,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]})))}};i.remoteVideoTrack.mediaType=o.mediaType,this.postMessage("changetype",o)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};iw([kU(JK.prototype.afterJoin),WL(["left",zL.INIT],"joined"),OU((e=>{let t=new Hz;return function(i,r,o){return nw(this,null,(function*(){let n=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 mw({code:hw.INVALID_OPERATION,message:fP({key:uP.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new mw({code:hw.INVALID_OPERATION,message:fP({key:uP.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:n}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(n," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),JO.emit(QO.JOIN_START,{room:this,roomId:n,params:i});let a=vw.getEnv();a||(a=Gw.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(iC.OLD_CLOUD_LADDER)?a=Gw.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(iC.WEBRTC)&&(a=Gw.WEBRTC))),rx.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),rM.checkSystemRequirementsInternal(o).then((e=>{this.checkSystemResult=e,Wz.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vw.getEnv()&&(yield this.schedule(i,o));let t=yield e.call(this,i,r,o);return this.roomId=n,this._joinedTimestamp=vw.performanceNow(),JO.emit(QO.JOIN_SUCCESS,{room:this}),30===o&&!i.component&&rx.uploadEvent({log:"stat-conv-".concat(Number(NO),"-").concat(location.hostname),userId:this.userId}),t}catch(dM){throw t.delete({room:this,roomId:n}),JO.emit(QO.JOIN_FAILED,{room:this,error:dM}),dM}}))}}))],JK.prototype,"join",1),iw([WL("joined","left",{ignoreError:!0}),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){JO.emit(QO.LEAVE_START,{room:this}),yield e.call(this,...i),JO.emit(QO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))}))],JK.prototype,"leave",1),iw([FU((e=>e.mediaType)),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return nw(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"ready"===e.state)),!i.length))return;JO.emit("61",{room:this});let t=e.apply(this,i);return Promise.all(i.map((e=>e.publish(this,t))))}))}))],JK.prototype,"publish",1),iw([FU((e=>e.mediaType)),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach((e=>e.unpublish())),o}))],JK.prototype,"unpublish",1),iw([FU((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),OU((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(o))),o}))],JK.prototype,"subscribe",1);var XK=JK;return Fz.frameWorkType=37,Fz.create=function(e){let t=Fz._create.call(this,XK,e);return t._use(kG,null==e?void 0:e.assetsPath),null!=e&&e.assetsPath&&(cK.assetsPath=null==e?void 0:e.assetsPath),console.log("trtc wasm sdk:",Iw,"created",cK),t},Object.assign(Fz.prototype,{_setCurrentSpeaker(e){let t=qx();return null!=t&&t.setSinkId?t.setSinkId(e):Promise.reject("not support")},_enableVideoDecodeFallback(e,t){return nw(this,null,(function*(){return this.startPlugin(kG.Name,{type:"webCodecs",renderer:"videoFrame",track:e,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise(((t,i)=>{$U(OV(e,"decode-downgrade-state-changed"),QV((e=>"STARTED"===e.state)),ZV(1),rB(1e4),eF(OV(e,zL.INIT)),tB(t,i))}))}))}}),wL(37),Fz}));
|