trtc-sdk-v5 5.8.7-beta.8 → 5.8.7-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/cross-room.esm.js +1 -1
- package/plugins/cross-room/cross-room.iife.js +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +3 -3
- package/plugins/device-detector/device-detector.iife.js +4 -4
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-effect/basic-beauty/basic-beauty.esm.js +2 -2
- package/plugins/video-effect/basic-beauty/basic-beauty.iife.js +2 -2
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/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/video-effect/watermark/watermark.esm.js +1 -1
- package/plugins/video-effect/watermark/watermark.iife.js +1 -1
- package/trtc.esm.js +125 -36
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),n=r,o=Function.prototype,s=o.call,a=n&&o.bind.bind(s,s),c=n?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,v=TypeError,y=function(e){if(E(e))throw v("Can't call method on "+e);return e},S=g,I=y,A=function(e){return S(I(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},D=C,N=Object.defineProperty,w=function(e,t){try{N(D,e,{value:t,configurable:!0,writable:!0})}catch(i){D[e]=t}return t},O=w,P="__core-js_shared__",M=C[P]||O(P,{}),L=M;(k.exports=function(e,t){return L[e]||(L[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=y,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),W=Object.hasOwn||function(e,t){return j(H(e),t)},G=c,J=0,z=Math.random(),K=G(1..toString),q=function(e){return"Symbol("+(void 0===e?"":e)+")_"+K(++J+z,36)},Y="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=Y,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,re=ie,ne=i,oe=!!Object.getOwnPropertySymbols&&!ne((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&re&&re<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=W,le=q,de=oe,ue=se,he=C.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,_e=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},ve=Ee,ye=ge.all,Se=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:ve(e)||e===ye}:function(e){return"object"==typeof e?null!==e:ve(e)},Ie=Se,Ae=String,Re=TypeError,Ce=function(e){if(Ie(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),De=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ne={},we=Se,Oe=C.document,Pe=we(Oe)&&we(Oe.createElement),Me=function(e){return Pe?Oe.createElement(e):{}},Le=Me,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=r,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},We=c({}.isPrototypeOf),Ge=je,Je=Ee,ze=We,Ke=Object,qe=se?function(e){return"symbol"==typeof e}:function(e){var t=Ge("Symbol");return Je(t)&&ze(t.prototype,Ke(e))},Ye=String,Qe=function(e){try{return Ye(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,rt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},nt=Fe,ot=Ee,st=Se,at=TypeError,ct=Fe,lt=Se,dt=qe,ut=rt,ht=function(e,t){var i,r;if("string"===t&&ot(i=e.toString)&&!st(r=nt(i,e)))return r;if(ot(i=e.valueOf)&&!st(r=nt(i,e)))return r;if("string"!==t&&ot(i=e.toString)&&!st(r=nt(i,e)))return r;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,r=ut(e,mt);if(r){if(void 0===t&&(t="default"),i=ct(r,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=qe,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,vt=xe,yt=De,St=Ce,It=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Dt="writable";Ne.f=Et?yt?function(e,t,i){if(St(e),t=It(t),St(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Dt in i&&!i[Dt]){var r=Ct(e,t);r&&r[Dt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:r[kt],enumerable:bt in i?i[bt]:r[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(St(e),t=It(t),St(i),vt)try{return Rt(e,t,i)}catch(r){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Nt=Math.ceil,wt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?wt:Nt)(t)},Pt=Ot,Mt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Lt=Mt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Lt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Mt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Wt=function(e){return jt(e.length)},Gt=A,Jt=Ut,zt=Wt,Kt=function(e){return function(t,i,r){var n,o=Gt(t),s=zt(o),a=Jt(r,s);if(e&&i!=i){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},qt={includes:Kt(!0),indexOf:Kt(!1)},Yt={},Qt=W,Xt=A,$t=qt.indexOf,Zt=Yt,ei=c([].push),ti=function(e,t){var i,r=Xt(e),n=0,o=[];for(i in r)!Qt(Zt,i)&&Qt(r,i)&&ei(o,i);for(;t.length>n;)Qt(r,i=t[n++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ri=ti,ni=ii,oi=Object.keys||function(e){return ri(e,ni)},si=ke,ai=De,ci=Ne,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,r=di(t),n=ui(t),o=n.length,s=0;o>s;)ci.f(e,i=n[s++],r[i]);return e};var hi,pi=je("document","documentElement"),mi=q,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,vi=Yt,yi=pi,Si=Me,Ii="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Di=function(){try{hi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;Di="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=Si("iframe"),i="java"+Ai+":",t.style.display="none",yi.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var r=Ei.length;r--;)delete Di[Ii][Ei[r]];return Di()};vi[Ri]=!0;var Ni=Object.create||function(e,t){var i;return null!==e?(Ci[Ii]=gi(e),i=new Ci,Ci[Ii]=null,i[Ri]=e):i=Di(),void 0===t?i:Ti.f(i,t)},wi=_e,Oi=Ni,Pi=Ne.f,Mi=wi("unscopables"),Li=Array.prototype;null==Li[Mi]&&Pi(Li,Mi,{configurable:!0,value:Oi(null)});var xi,Vi,Ui,Fi=function(e){Li[Mi][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Wi=Hi(ji)&&/native code/.test(String(ji)),Gi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=Ne,zi=Gi,Ki=ke?function(e,t,i){return Ji.f(e,t,zi(1,i))}:function(e,t,i){return e[t]=i,e},qi=Wi,Yi=C,Qi=Se,Xi=Ki,$i=W,Zi=M,er=fi,tr=Yt,ir="Object already initialized",rr=Yi.TypeError,nr=Yi.WeakMap;if(qi||Zi.state){var or=Zi.state||(Zi.state=new nr);or.get=or.get,or.has=or.has,or.set=or.set,xi=function(e,t){if(or.has(e))throw rr(ir);return t.facade=e,or.set(e,t),t},Vi=function(e){return or.get(e)||{}},Ui=function(e){return or.has(e)}}else{var sr=er("state");tr[sr]=!0,xi=function(e,t){if($i(e,sr))throw rr(ir);return t.facade=e,Xi(e,sr,t),t},Vi=function(e){return $i(e,sr)?e[sr]:{}},Ui=function(e){return $i(e,sr)}}var ar={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rr("Incompatible receiver, "+e+" required");return i}}},cr={},lr={},dr={}.propertyIsEnumerable,ur=Object.getOwnPropertyDescriptor,hr=ur&&!dr.call({1:2},1);lr.f=hr?function(e){var t=ur(this,e);return!!t&&t.enumerable}:dr;var pr=ke,mr=Fe,_r=lr,fr=Gi,gr=A,Tr=Tt,Er=W,vr=xe,yr=Object.getOwnPropertyDescriptor;cr.f=pr?yr:function(e,t){if(e=gr(e),t=Tr(t),vr)try{return yr(e,t)}catch(i){}if(Er(e,t))return fr(!mr(_r.f,e,t),e[t])};var Sr={},Ir={get exports(){return Sr},set exports(e){Sr=e}},Ar=ke,Rr=W,Cr=Function.prototype,br=Ar&&Object.getOwnPropertyDescriptor,kr=Rr(Cr,"name"),Dr={EXISTS:kr,PROPER:kr&&"something"===function(){}.name,CONFIGURABLE:kr&&(!Ar||Ar&&br(Cr,"name").configurable)},Nr=Ee,wr=M,Or=c(Function.toString);Nr(wr.inspectSource)||(wr.inspectSource=function(e){return Or(e)});var Pr=wr.inspectSource,Mr=c,Lr=i,xr=Ee,Vr=W,Ur=ke,Fr=Dr.CONFIGURABLE,Br=Pr,Hr=ar.enforce,jr=ar.get,Wr=String,Gr=Object.defineProperty,Jr=Mr("".slice),zr=Mr("".replace),Kr=Mr([].join),qr=Ur&&!Lr((function(){return 8!==Gr((function(){}),"length",{value:8}).length})),Yr=String(String).split("String"),Qr=Ir.exports=function(e,t,i){"Symbol("===Jr(Wr(t),0,7)&&(t="["+zr(Wr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Vr(e,"name")||Fr&&e.name!==t)&&(Ur?Gr(e,"name",{value:t,configurable:!0}):e.name=t),qr&&i&&Vr(i,"arity")&&e.length!==i.arity&&Gr(e,"length",{value:i.arity});try{i&&Vr(i,"constructor")&&i.constructor?Ur&&Gr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Hr(e);return Vr(r,"source")||(r.source=Kr(Yr,"string"==typeof t?t:"")),e};Function.prototype.toString=Qr((function(){return xr(this)&&jr(this).source||Br(this)}),"toString");var Xr=Ee,$r=Ne,Zr=Sr,en=w,tn=function(e,t,i,r){r||(r={});var n=r.enumerable,o=void 0!==r.name?r.name:t;if(Xr(i)&&Zr(i,o,r),r.global)n?e[t]=i:en(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=i:$r.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},rn={},nn=ti,on=ii.concat("length","prototype");rn.f=Object.getOwnPropertyNames||function(e){return nn(e,on)};var sn={};sn.f=Object.getOwnPropertySymbols;var an,cn,ln,dn=je,un=rn,hn=sn,pn=Ce,mn=c([].concat),_n=dn("Reflect","ownKeys")||function(e){var t=un.f(pn(e)),i=hn.f;return i?mn(t,i(e)):t},fn=W,gn=_n,Tn=cr,En=Ne,vn=function(e,t,i){for(var r=gn(t),n=En.f,o=Tn.f,s=0;s<r.length;s++){var a=r[s];fn(e,a)||i&&fn(i,a)||n(e,a,o(t,a))}},yn=i,Sn=Ee,In=/#|\.prototype\./,An=function(e,t){var i=Cn[Rn(e)];return i==kn||i!=bn&&(Sn(t)?yn(t):!!t)},Rn=An.normalize=function(e){return String(e).replace(In,".").toLowerCase()},Cn=An.data={},bn=An.NATIVE="N",kn=An.POLYFILL="P",Dn=An,Nn=C,wn=cr.f,On=Ki,Pn=tn,Mn=w,Ln=vn,xn=Dn,Vn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Nn:l?Nn[a]||Mn(a,{}):(Nn[a]||{}).prototype)for(r in t){if(o=t[r],n=e.dontCallGetSet?(s=wn(i,r))&&s.value:i[r],!xn(c?r:a+(l?".":"#")+r,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;Ln(o,n)}(e.sham||n&&n.sham)&&On(o,"sham",!0),Pn(i,r,o,e)}},Un=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fn=W,Bn=Ee,Hn=B,jn=Un,Wn=fi("IE_PROTO"),Gn=Object,Jn=Gn.prototype,zn=jn?Gn.getPrototypeOf:function(e){var t=Hn(e);if(Fn(t,Wn))return t[Wn];var i=t.constructor;return Bn(i)&&t instanceof i?i.prototype:t instanceof Gn?Jn:null},Kn=i,qn=Ee,Yn=Se,Qn=zn,Xn=tn,$n=_e("iterator"),Zn=!1;[].keys&&("next"in(ln=[].keys())?(cn=Qn(Qn(ln)))!==Object.prototype&&(an=cn):Zn=!0);var eo=!Yn(an)||Kn((function(){var e={};return an[$n].call(e)!==e}));eo&&(an={}),qn(an[$n])||Xn(an,$n,(function(){return this}));var to={IteratorPrototype:an,BUGGY_SAFARI_ITERATORS:Zn},io=Ne.f,ro=W,no=_e("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!ro(e,no)&&io(e,no,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Ni,co=Gi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,r){var n=t+" Iterator";return e.prototype=ao(so,{next:co(+!r,i)}),lo(e,n,!1),uo[n]=ho,e},mo=c,_o=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return mo(_o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(r){}},vo=Ce,yo=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},So=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return vo(i),yo(r),t?e(i,r):i.__proto__=r,i}}():void 0),Io=Vn,Ao=Fe,Ro=Ee,Co=po,bo=zn,ko=So,Do=oo,No=Ki,wo=tn,Oo=Bi,Po=Dr.PROPER,Mo=Dr.CONFIGURABLE,Lo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=_e("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,r,n,o,s){Co(i,t,r);var a,c,l,d=function(e){if(e===n&&_)return _;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||n&&p[n],_=!xo&&m||d(n),f="Array"==t&&p.entries||m;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Lo&&(ko?ko(a,Lo):Ro(a[Vo])||wo(a,Vo,Ho)),Do(a,u,!0)),Po&&n==Fo&&m&&m.name!==Fo&&(Mo?No(p,"name",Fo):(h=!0,_=function(){return Ao(m,this)})),n)if(c={values:d(Fo),keys:o?_:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&wo(p,l,c[l]);else Io({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&wo(p,Vo,_,{name:n}),Oo[t]=_,c},Wo=function(e,t){return{value:e,done:t}},Go=A,Jo=Fi,zo=Bi,Ko=ar,qo=Ne.f,Yo=jo,Qo=Wo,Xo=ke,$o="Array Iterator",Zo=Ko.set,es=Ko.getterFor($o),ts=Yo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Go(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?r:"values"==i?t[r]:[r,t[r]],!1)}),"values"),is=zo.Arguments=zo.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{qo(is,"name",{value:"values"})}catch(VB){}var rs={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},ns=Me("span").classList,os=ns&&ns.constructor&&ns.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=rs,ls=ss,ds=ts,us=Ki,hs=_e,ps=hs("iterator"),ms=hs("toStringTag"),_s=ds.values,fs=function(e,t){if(e){if(e[ps]!==_s)try{us(e,ps,_s)}catch(VB){e[ps]=_s}if(e[ms]||us(e,ms,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i])}catch(VB){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=Sr,vs=Ne,ys=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),vs.f(e,t,i)},Ss=je,Is=ys,As=ke,Rs=_e("species"),Cs=function(e){var t=Ss(e);As&&t&&!t[Rs]&&Is(t,Rs,{configurable:!0,get:function(){return this}})},bs=We,ks=TypeError,Ds=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ns={};Ns[_e("toStringTag")]="z";var ws="[object z]"===String(Ns),Os=Ee,Ps=h,Ms=_e("toStringTag"),Ls=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=ws?Ps: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(VB){}}(t=Ls(e),Ms))?i:xs?Ps(t):"Object"==(r=Ps(t))&&Os(t.callee)?"Arguments":r},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Pr,Ws=function(){},Gs=[],Js=je("Reflect","construct"),zs=/^\s*(?:class|function)\b/,Ks=Us(zs.exec),qs=!zs.exec(Ws),Ys=function(e){if(!Bs(e))return!1;try{return Js(Ws,Gs,e),!0}catch(VB){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qs||!!Ks(zs,js(e))}catch(VB){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return Ys(Ys.call)||!Ys(Object)||!Ys((function(){e=!0}))||e}))?Qs:Ys,ia=ta,ra=Qe,na=TypeError,oa=function(e){if(ia(e))return e;throw na(ra(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=_e("species"),da=function(e,t){var i,r=sa(e).constructor;return void 0===r||ca(i=sa(r)[la])?t:aa(i)},ua=r,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,va=r,ya=Ta(Ta.bind),Sa=function(e,t){return Ea(e),void 0===t?e:va?ya(e,t):function(){return e.apply(t,arguments)}},Ia=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ba=C,ka=_a,Da=Sa,Na=Ee,wa=W,Oa=i,Pa=pi,Ma=Ia,La=Me,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Wa=ba.Function,Ga=ba.MessageChannel,Ja=ba.String,za=0,Ka={},qa="onreadystatechange";Oa((function(){Xs=ba.location}));var Ya=function(e){if(wa(Ka,e)){var t=Ka[e];delete Ka[e],t()}},Qa=function(e){return function(){Ya(e)}},Xa=function(e){Ya(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Na(e)?e:Wa(e),i=Ma(arguments,1);return Ka[++za]=function(){ka(t,void 0,i)},$s(za),za},Ba=function(e){delete Ka[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Ga&&!Va?(ea=(Zs=new Ga).port2,Zs.port1.onmessage=Xa,$s=Da(ea.postMessage,ea)):ba.addEventListener&&Na(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!Oa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=qa in La("script")?function(e){Pa.appendChild(La("script"))[qa]=function(){Pa.removeChild(this),Ya(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,rc,nc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(Y)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(Y),lc=C,dc=Sa,uc=cr.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,vc=lc.process,yc=lc.Promise,Sc=uc(lc,"queueMicrotask"),Ic=Sc&&Sc.value;if(!Ic){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=vc.domain)&&e.exit();t=Ac.get();)try{t()}catch(VB){throw Ac.head&&tc(),VB}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&yc&&yc.resolve?((nc=yc.resolve(void 0)).constructor=yc,oc=dc(nc.then,nc),tc=function(){oc(Rc)}):gc?tc=function(){vc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,rc=Ec.createTextNode(""),new Tc(Rc).observe(rc,{characterData:!0}),tc=function(){rc.data=ic=!ic}),Ic=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=Ic,bc=function(e){try{return{error:!1,value:e()}}catch(VB){return{error:!0,value:VB}}},kc=C.Promise,Dc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Nc=!Dc&&!Ts&&"object"==typeof window&&"object"==typeof document,wc=C,Oc=kc,Pc=Ee,Mc=Dn,Lc=Pr,xc=_e,Vc=Nc,Uc=Dc,Fc=ie;Oc&&Oc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(wc.PromiseRejectionEvent),Wc=Mc("Promise",(function(){var e=Lc(Oc),t=e!==String(Oc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new Oc((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=r,!(Hc=i.then((function(){}))instanceof r))return!0}return!t&&(Vc||Uc)&&!jc})),Gc={CONSTRUCTOR:Wc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},zc=et,Kc=TypeError,qc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw Kc("Bad Promise constructor");t=e,i=r})),this.resolve=zc(t),this.reject=zc(i)};Jc.f=function(e){return new qc(e)};var Yc,Qc,Xc,$c=Vn,Zc=Ts,el=C,tl=Fe,il=tn,rl=So,nl=oo,ol=Cs,sl=et,al=Ee,cl=Se,ll=Ds,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(VB){}},ml=bc,_l=sc,fl=ar,gl=kc,Tl=Jc,El="Promise",vl=Gc.CONSTRUCTOR,yl=Gc.REJECTION_EVENT,Sl=Gc.SUBCLASSING,Il=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Dl=el.document,Nl=el.process,wl=Tl.f,Ol=wl,Pl=!!(Dl&&Dl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,r,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),n=!0)),i===e.promise?l(kl("Promise-chain cycle")):(r=Ll(i))?tl(r,i,c,l):c(i)):l(o)}catch(VB){d&&!n&&d.exit(),l(VB)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,r=e.reactions;i=r.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var r,n;Pl?((r=Dl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),el.dispatchEvent(r)):r={promise:t,reason:i},!yl&&(n=el["on"+e])?n(r):e===Ml&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,r=e.value;if(Bl(e)&&(t=ml((function(){Zc?Nl.emit("unhandledRejection",r,i):Ul(Ml,i,r)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Nl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(r){e(t,r,i)}},Wl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Gl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var r=Ll(t);r?hl((function(){var i={done:!1};try{tl(r,t,jl(Gl,i,e),jl(Wl,i,e))}catch(VB){Wl(i,VB,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(VB){Wl({done:!1},VB,e)}}};if(vl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(Yc,this);var t=Il(this);try{e(jl(Gl,t),jl(Wl,t))}catch(VB){Wl(t,VB)}}).prototype,(Yc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=Il(this),r=wl(dl(this,Cl));return i.parent=!0,r.ok=!al(e)||e,r.fail=al(t)&&t,r.domain=Zc?Nl.domain:void 0,0==i.state?i.reactions.add(r):hl((function(){xl(r,i)})),r.promise})),Qc=function(){var e=new Yc,t=Il(e);this.promise=e,this.resolve=jl(Gl,t),this.reject=jl(Wl,t)},Tl.f=wl=function(e){return e===Cl||undefined===e?new Qc(e):Ol(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,Sl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(VB){}rl&&rl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:vl},{Promise:Cl}),nl(Cl,El,!1),ol(El);var Jl=Bi,zl=_e("iterator"),Kl=Array.prototype,ql=function(e){return void 0!==e&&(Jl.Array===e||Kl[zl]===e)},Yl=Vs,Ql=rt,Xl=T,$l=Bi,Zl=_e("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[Yl(e)]},td=Fe,id=et,rd=Ce,nd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return rd(td(i,e));throw sd(nd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=rt,ud=function(e,t,i){var r,n;ld(e);try{if(!(r=dd(e,"return"))){if("throw"===t)throw i;return i}r=cd(r,e)}catch(VB){n=!0,r=VB}if("throw"===t)throw i;if(n)throw r;return ld(r),i},hd=Sa,pd=Fe,md=Ce,_d=Qe,fd=ql,gd=Wt,Td=We,Ed=ad,vd=ed,yd=ud,Sd=TypeError,Id=function(e,t){this.stopped=e,this.result=t},Ad=Id.prototype,Rd=function(e,t,i){var r,n,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return r&&yd(r,"normal",e),new Id(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=vd(e)))throw Sd(_d(e)+" is not iterable");if(fd(n)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new Id(!1)}r=Ed(e,n)}for(c=h?e.next:r.next;!(l=pd(c,r)).done;){try{a=g(l.value)}catch(VB){yd(r,"throw",VB)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new Id(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Dd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Dd[Cd]=function(){return this},Array.from(Dd,(function(){throw 2}))}catch(VB){}var Nd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var r={};r[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(VB){}return i},wd=kc,Od=Gc.CONSTRUCTOR||!Nd((function(e){wd.all(e).then(void 0,(function(){}))})),Pd=Fe,Md=et,Ld=Jc,xd=bc,Vd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{all:function(e){var t=this,i=Ld.f(t),r=i.resolve,n=i.reject,o=xd((function(){var i=Md(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var Ud=Vn,Fd=Gc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Wd=tn,Gd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Gd.catch!==Jd&&Wd(Gd,"catch",Jd,{unsafe:!0})}var zd=Fe,Kd=et,qd=Jc,Yd=bc,Qd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{race:function(e){var t=this,i=qd.f(t),r=i.reject,n=Yd((function(){var n=Kd(t.resolve);Qd(e,(function(e){zd(n,t,e).then(i.resolve,r)}))}));return n.error&&r(n.value),i.promise}});var Xd=Fe,$d=Jc;Vn({target:"Promise",stat:!0,forced:Gc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=Se,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},ru=Vn,nu=Gc.CONSTRUCTOR,ou=iu;je("Promise"),ru({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return ou(this,e)}});var su=Ee,au=Se,cu=So,lu=function(e,t,i){var r,n;return cu&&su(r=t.constructor)&&r!==i&&au(n=r.prototype)&&n!==i.prototype&&cu(e,n),e},du=Se,uu=h,hu=_e("match"),pu=Vs,mu=String,_u=function(e){if("Symbol"===pu(e))throw TypeError("Cannot convert a Symbol value to a string");return mu(e)},fu=Ce,gu=function(){var e=fu(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},Tu=Fe,Eu=W,vu=We,yu=gu,Su=RegExp.prototype,Iu=i,Au=C.RegExp,Ru=Iu((function(){var e=Au("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),Cu=Ru||Iu((function(){return!Au("a","y").sticky})),bu=Ru||Iu((function(){var e=Au("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),ku={BROKEN_CARET:bu,MISSED_STICKY:Cu,UNSUPPORTED_Y:Ru},Du=Ne.f,Nu=i,wu=C.RegExp,Ou=Nu((function(){var e=wu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Pu=i,Mu=C.RegExp,Lu=Pu((function(){var e=Mu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),xu=ke,Vu=C,Uu=c,Fu=Dn,Bu=lu,Hu=Ki,ju=rn.f,Wu=We,Gu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},Ju=_u,zu=function(e){var t=e.flags;return void 0!==t||"flags"in Su||Eu(e,"flags")||!vu(Su,e)?t:Tu(yu,e)},Ku=ku,qu=function(e,t,i){i in e||Du(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Yu=tn,Qu=i,Xu=W,$u=ar.enforce,Zu=Cs,eh=Ou,th=Lu,ih=_e("match"),rh=Vu.RegExp,nh=rh.prototype,oh=Vu.SyntaxError,sh=Uu(nh.exec),ah=Uu("".charAt),ch=Uu("".replace),lh=Uu("".indexOf),dh=Uu("".slice),uh=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,hh=/a/g,ph=/a/g,mh=new rh(hh)!==hh,_h=Ku.MISSED_STICKY,fh=Ku.UNSUPPORTED_Y,gh=xu&&(!mh||_h||eh||th||Qu((function(){return ph[ih]=!1,rh(hh)!=hh||rh(ph)==ph||"/a/i"!=rh(hh,"i")})));if(Fu("RegExp",gh)){for(var Th=function(e,t){var i,r,n,o,s,a,c=Wu(nh,this),l=Gu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Th)return e;if((l||Wu(nh,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?"":Ju(e),t=void 0===t?"":Ju(t),h=e,eh&&"dotAll"in hh&&(r=!!t&&lh(t,"s")>-1)&&(t=ch(t,/s/g,"")),i=t,_h&&"sticky"in hh&&(n=!!t&&lh(t,"y")>-1)&&fh&&(t=ch(t,/y/g,"")),th&&(o=function(e){for(var t,i=e.length,r=0,n="",o=[],s={},a=!1,c=!1,l=0,d="";r<=i;r++){if("\\"===(t=ah(e,r)))t+=ah(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:sh(uh,dh(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Xu(s,d))throw new oh("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Bu(rh(e,t),c?this:nh,Th),(r||n||u.length)&&(a=$u(s),r&&(a.dotAll=!0,a.raw=Th(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=ah(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+ah(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Hu(s,"source",""===h?"(?:)":h)}catch(VB){}return s},Eh=ju(rh),vh=0;Eh.length>vh;)qu(Th,rh,Eh[vh++]);nh.constructor=Th,Th.prototype=nh,Yu(Vu,"RegExp",Th,{constructor:!0})}Zu("RegExp");var yh=Fe,Sh=c,Ih=_u,Ah=gu,Rh=ku,Ch=Ni,bh=ar.get,kh=Ou,Dh=Lu,Nh=b("native-string-replace",String.prototype.replace),wh=RegExp.prototype.exec,Oh=wh,Ph=Sh("".charAt),Mh=Sh("".indexOf),Lh=Sh("".replace),xh=Sh("".slice),Vh=function(){var e=/a/,t=/b*/g;return yh(wh,e,"a"),yh(wh,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Uh=Rh.BROKEN_CARET,Fh=void 0!==/()??/.exec("")[1];(Vh||Fh||Uh||kh||Dh)&&(Oh=function(e){var t,i,r,n,o,s,a,c=this,l=bh(c),d=Ih(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Oh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Uh&&c.sticky,m=yh(Ah,c),_=c.source,f=0,g=d;if(p&&(m=Lh(m,"y",""),-1===Mh(m,"g")&&(m+="g"),g=xh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Ph(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Fh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Vh&&(r=c.lastIndex),n=yh(wh,p?i:c,g),p?n?(n.input=xh(n.input,f),n[0]=xh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Vh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Fh&&n&&n.length>1&&yh(Nh,n[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=Ch(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Bh=Oh;Vn({target:"RegExp",proto:!0,forced:/./.exec!==Bh},{exec:Bh});var Hh=h,jh=Array.isArray||function(e){return"Array"==Hh(e)},Wh=jh,Gh=ta,Jh=Se,zh=_e("species"),Kh=Array,qh=function(e){var t;return Wh(e)&&(t=e.constructor,(Gh(t)&&(t===Kh||Wh(t.prototype))||Jh(t)&&null===(t=t[zh]))&&(t=void 0)),void 0===t?Kh:t},Yh=Sa,Qh=g,Xh=B,$h=Wt,Zh=function(e,t){return new(qh(e))(0===t?0:t)},ep=c([].push),tp=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Xh(c),_=Qh(m),f=Yh(l,d),g=$h(_),T=0,E=u||Zh,v=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)v[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ep(v,h)}else switch(e){case 4:return!1;case 7:ep(v,h)}return o?-1:r||n?n:v}},ip={forEach:tp(0),map:tp(1),filter:tp(2),some:tp(3),every:tp(4),find:tp(5),findIndex:tp(6),filterReject:tp(7)},rp=i,np=function(e,t){var i=[][e];return!!i&&rp((function(){i.call(null,t||function(){return 1},1)}))},op=ip.forEach,sp=np("forEach")?[].forEach:function(e){return op(this,e,arguments.length>1?arguments[1]:void 0)},ap=C,cp=rs,lp=ss,dp=sp,up=Ki,hp=function(e){if(e&&e.forEach!==dp)try{up(e,"forEach",dp)}catch(VB){e.forEach=dp}};for(var pp in cp)cp[pp]&&hp(ap[pp]&&ap[pp].prototype);hp(lp);var mp=et,_p=B,fp=g,gp=Wt,Tp=TypeError,Ep=function(e){return function(t,i,r,n){mp(i);var o=_p(t),s=fp(o),a=gp(o),c=e?a-1:0,l=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Tp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(n=i(n,s[c],c,o));return n}},vp={left:Ep(!1),right:Ep(!0)}.left;Vn({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!np("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Sp=tn,Ip=Bh,Ap=i,Rp=_e,Cp=Ki,bp=Rp("species"),kp=RegExp.prototype,Dp=c,Np=Mt,wp=_u,Op=y,Pp=Dp("".charAt),Mp=Dp("".charCodeAt),Lp=Dp("".slice),xp=function(e){return function(t,i){var r,n,o=wp(Op(t)),s=Np(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=Mp(o,s))<55296||r>56319||s+1===a||(n=Mp(o,s+1))<56320||n>57343?e?Pp(o,s):r:e?Lp(o,s,s+2):n-56320+(r-55296<<10)+65536}},Vp={codeAt:xp(!1),charAt:xp(!0)},Up=Vp.charAt,Fp=c,Bp=B,Hp=Math.floor,jp=Fp("".charAt),Wp=Fp("".replace),Gp=Fp("".slice),Jp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,Kp=Fe,qp=Ce,Yp=Ee,Qp=h,Xp=Bh,$p=TypeError,Zp=_a,em=Fe,tm=c,im=function(e,t,i,r){var n=Rp(e),o=!Ap((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Ap((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[bp]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=yp(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var s=yp(e),c=t.exec;return c===Ip||c===kp.exec?o&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:s(i,t,r)}:{done:!1}}));Sp(String.prototype,e,c[0]),Sp(kp,n,c[1])}r&&Cp(kp[n],"sham",!0)},rm=i,nm=Ce,om=Ee,sm=T,am=Mt,cm=Ht,lm=_u,dm=y,um=function(e,t,i){return t+(i?Up(e,t).length:1)},hm=rt,pm=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=zp;return void 0!==n&&(n=Bp(n),c=Jp),Wp(o,c,(function(o,c){var l;switch(jp(c,0)){case"$":return"$";case"&":return e;case"`":return Gp(t,0,i);case"'":return Gp(t,s);case"<":l=n[Gp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Hp(d/10);return 0===u?o:u<=a?void 0===r[u-1]?jp(c,1):r[u-1]+jp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},mm=function(e,t){var i=e.exec;if(Yp(i)){var r=Kp(i,e,t);return null!==r&&qp(r),r}if("RegExp"===Qp(e))return Kp(Xp,e,t);throw $p("RegExp#exec called on incompatible receiver")},_m=_e("replace"),fm=Math.max,gm=Math.min,Tm=tm([].concat),Em=tm([].push),vm=tm("".indexOf),ym=tm("".slice),Sm=function(e){return void 0===e?e:String(e)},Im="$0"==="a".replace(/./,"$0"),Am=!!/./[_m]&&""===/./[_m]("a","$0"),Rm=!rm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));im("replace",(function(e,t,i){var r=Am?"$":"$0";return[function(e,i){var r=dm(this),n=sm(e)?void 0:hm(e,_m);return n?em(n,e,r,i):em(t,lm(r),e,i)},function(e,n){var o=nm(this),s=lm(e);if("string"==typeof n&&-1===vm(n,r)&&-1===vm(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=om(n);c||(n=lm(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=mm(o,s);if(null===h)break;if(Em(u,h),!l)break;""===lm(h[0])&&(o.lastIndex=um(s,cm(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=lm((h=u[_])[0]),g=fm(gm(am(h.index),s.length),0),T=[],E=1;E<h.length;E++)Em(T,Sm(h[E]));var v=h.groups;if(c){var y=Tm([f],T,g,s);void 0!==v&&Em(y,v);var S=lm(Zp(n,void 0,y))}else S=pm(f,s,g,T,v,n);g>=m&&(p+=ym(s,m,g)+S,m=g+f.length)}return p+ym(s,m)}]}),!Rm||!Im||Am);var Cm=qt.includes,bm=Fi;Vn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Cm(this,e,arguments.length>1?arguments[1]:void 0)}}),bm("includes");var km=Mt,Dm=_u,Nm=y,wm=RangeError,Om=c,Pm=Ht,Mm=_u,Lm=function(e){var t=Dm(Nm(this)),i="",r=km(e);if(r<0||Infinity==r)throw wm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},xm=y,Vm=Om(Lm),Um=Om("".slice),Fm=Math.ceil,Bm=function(e){return function(t,i,r){var n,o,s=Mm(xm(t)),a=Pm(i),c=s.length,l=void 0===r?" ":Mm(r);return a<=c||""==l?s:((o=Vm(l,Fm((n=a-c)/l.length))).length>n&&(o=Um(o,0,n)),e?s+o:o+s)}},Hm={start:Bm(!1),end:Bm(!0)},jm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),Wm=Hm.start;Vn({target:"String",proto:!0,forced:jm},{padStart:function(e){return Wm(this,e,arguments.length>1?arguments[1]:void 0)}});var Gm=i,Jm=ke,zm=_e("iterator"),Km=!Gm((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!Jm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[zm]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),qm=tn,Ym=function(e,t,i){for(var r in t)qm(e,r,t[r],i);return e},Qm=Tt,Xm=Ne,$m=Gi,Zm=function(e,t,i){var r=Qm(t);r in e?Xm.f(e,r,$m(0,i)):e[r]=i},e_=Ut,t_=Wt,i_=Zm,r_=Array,n_=Math.max,o_=function(e,t,i){for(var r=t_(e),n=e_(t,r),o=e_(void 0===i?r:i,r),s=r_(n_(o-n,0)),a=0;n<o;n++,a++)i_(s,a,e[n]);return s.length=a,s},s_=o_,a_=Math.floor,c_=function(e,t){var i=e.length,r=a_(i/2);return i<8?l_(e,t):d_(e,c_(s_(e,0,r),t),c_(s_(e,r),t),t)},l_=function(e,t){for(var i,r,n=e.length,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}return e},d_=function(e,t,i,r){for(var n=t.length,o=i.length,s=0,a=0;s<n||a<o;)e[s+a]=s<n&&a<o?r(t[s],i[a])<=0?t[s++]:i[a++]:s<n?t[s++]:i[a++];return e},u_=c_,h_=Vn,p_=C,m_=Fe,__=c,f_=ke,g_=Km,T_=tn,E_=ys,v_=Ym,y_=oo,S_=po,I_=ar,A_=Ds,R_=Ee,C_=W,b_=Sa,k_=Vs,D_=Ce,N_=Se,w_=_u,O_=Ni,P_=Gi,M_=ad,L_=ed,x_=Ra,V_=u_,U_=_e("iterator"),F_="URLSearchParams",B_=F_+"Iterator",H_=I_.set,j_=I_.getterFor(F_),W_=I_.getterFor(B_),G_=Object.getOwnPropertyDescriptor,J_=function(e){if(!f_)return p_[e];var t=G_(p_,e);return t&&t.value},z_=J_("fetch"),K_=J_("Request"),q_=J_("Headers"),Y_=K_&&K_.prototype,Q_=q_&&q_.prototype,X_=p_.RegExp,$_=p_.TypeError,Z_=p_.decodeURIComponent,ef=p_.encodeURIComponent,tf=__("".charAt),rf=__([].join),nf=__([].push),of=__("".replace),sf=__([].shift),af=__([].splice),cf=__("".split),lf=__("".slice),df=/\+/g,uf=Array(4),hf=function(e){return uf[e-1]||(uf[e-1]=X_("((?:%[\\da-f]{2}){"+e+"})","gi"))},pf=function(e){try{return Z_(e)}catch(VB){return e}},mf=function(e){var t=of(e,df," "),i=4;try{return Z_(t)}catch(VB){for(;i;)t=of(t,hf(i--),pf);return t}},_f=/[!'()~]|%20/g,ff={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},gf=function(e){return ff[e]},Tf=function(e){return of(ef(e),_f,gf)},Ef=S_((function(e,t){H_(this,{type:B_,iterator:M_(j_(e).entries),kind:t})}),"Iterator",(function(){var e=W_(this),t=e.kind,i=e.iterator.next(),r=i.value;return i.done||(i.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),i}),!0),vf=function(e){this.entries=[],this.url=null,void 0!==e&&(N_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===tf(e,0)?lf(e,1):e:w_(e)))};vf.prototype={type:F_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=L_(e);if(c)for(i=(t=M_(e,c)).next;!(r=m_(i,t)).done;){if(o=(n=M_(D_(r.value))).next,(s=m_(o,n)).done||(a=m_(o,n)).done||!m_(o,n).done)throw $_("Expected sequence with length 2");nf(this.entries,{key:w_(s.value),value:w_(a.value)})}else for(var l in e)C_(e,l)&&nf(this.entries,{key:l,value:w_(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=cf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=cf(t,"="),nf(this.entries,{key:mf(sf(i)),value:mf(rf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],nf(i,Tf(e.key)+"="+Tf(e.value));return rf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yf=function(){A_(this,Sf);var e=H_(this,new vf(arguments.length>0?arguments[0]:void 0));f_||(this.length=e.entries.length)},Sf=yf.prototype;if(v_(Sf,{append:function(e,t){x_(arguments.length,2);var i=j_(this);nf(i.entries,{key:w_(e),value:w_(t)}),f_||this.length++,i.updateURL()},delete:function(e){x_(arguments.length,1);for(var t=j_(this),i=t.entries,r=w_(e),n=0;n<i.length;)i[n].key===r?af(i,n,1):n++;f_||(this.length=i.length),t.updateURL()},get:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&nf(r,t[n].value);return r},has:function(e){x_(arguments.length,1);for(var t=j_(this).entries,i=w_(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){x_(arguments.length,1);for(var i,r=j_(this),n=r.entries,o=!1,s=w_(e),a=w_(t),c=0;c<n.length;c++)(i=n[c]).key===s&&(o?af(n,c--,1):(o=!0,i.value=a));o||nf(n,{key:s,value:a}),f_||(this.length=n.length),r.updateURL()},sort:function(){var e=j_(this);V_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=j_(this).entries,r=b_(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new Ef(this,"keys")},values:function(){return new Ef(this,"values")},entries:function(){return new Ef(this,"entries")}},{enumerable:!0}),T_(Sf,U_,Sf.entries,{name:"entries"}),T_(Sf,"toString",(function(){return j_(this).serialize()}),{enumerable:!0}),f_&&E_(Sf,"size",{get:function(){return j_(this).entries.length},configurable:!0,enumerable:!0}),y_(yf,F_),h_({global:!0,constructor:!0,forced:!g_},{URLSearchParams:yf}),!g_&&R_(q_)){var If=__(Q_.has),Af=__(Q_.set),Rf=function(e){if(N_(e)){var t,i=e.body;if(k_(i)===F_)return t=e.headers?new q_(e.headers):new q_,If(t,"content-type")||Af(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),O_(e,{body:P_(0,w_(i)),headers:P_(0,t)})}return e};if(R_(z_)&&h_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return z_(e,arguments.length>1?Rf(arguments[1]):{})}}),R_(K_)){var Cf=function(e){return A_(this,Y_),new K_(e,arguments.length>1?Rf(arguments[1]):{})};Y_.constructor=Cf,Cf.prototype=Y_,h_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Cf})}}var bf={URLSearchParams:yf,getState:j_},kf=Vn,Df=kc,Nf=i,wf=je,Of=Ee,Pf=da,Mf=iu,Lf=tn,xf=Df&&Df.prototype;if(kf({target:"Promise",proto:!0,real:!0,forced:!!Df&&Nf((function(){xf.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Pf(this,wf("Promise")),i=Of(e);return this.then(i?function(i){return Mf(t,e()).then((function(){return i}))}:e,i?function(i){return Mf(t,e()).then((function(){throw i}))}:e)}}),Of(Df)){var Vf=wf("Promise").prototype.finally;xf.finally!==Vf&&Lf(xf,"finally",Vf,{unsafe:!0})}var Uf="\t\n\v\f\r \u2028\u2029\ufeff",Ff=y,Bf=_u,Hf=Uf,jf=c("".replace),Wf=RegExp("^["+Hf+"]+"),Gf=RegExp("(^|[^"+Hf+"])["+Hf+"]+$"),Jf=function(e){return function(t){var i=Bf(Ff(t));return 1&e&&(i=jf(i,Wf,"")),2&e&&(i=jf(i,Gf,"$1")),i}},zf={start:Jf(1),end:Jf(2),trim:Jf(3)},Kf=Dr.PROPER,qf=i,Yf=Uf,Qf=zf.trim;Vn({target:"String",proto:!0,forced:function(e){return qf((function(){return!!Yf[e]()||"
"!=="
"[e]()||Kf&&Yf[e].name!==e}))}("trim")},{trim:function(){return Qf(this)}});var Xf="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,$f=Mt,Zf=Ht,eg=RangeError,tg=function(e){if(void 0===e)return 0;var t=$f(e),i=Zf(t);if(t!==i)throw eg("Wrong length or index");return i},ig=Array,rg=Math.abs,ng=Math.pow,og=Math.floor,sg=Math.log,ag=Math.LN2,cg={pack:function(e,t,i){var r,n,o,s=ig(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?ng(2,-24)-ng(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=rg(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=og(sg(e)/ag),e*(o=ng(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*ng(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*ng(2,t),r+=l):(n=e*ng(2,l-1)*ng(2,t),r=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(r=r<<t|n,a+=t;a>0;)s[h++]=255&r,r/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=r-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=ng(2,t),d-=s}return(l?-1:1)*i*ng(2,d-t)}},lg=B,dg=Ut,ug=Wt,hg=function(e){for(var t=lg(this),i=ug(t),r=arguments.length,n=dg(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:dg(o,i);s>n;)t[n++]=e;return t},pg=C,mg=c,_g=ke,fg=Xf,gg=Dr,Tg=Ki,Eg=ys,vg=Ym,yg=i,Sg=Ds,Ig=Mt,Ag=Ht,Rg=tg,Cg=cg,bg=zn,kg=So,Dg=rn.f,Ng=hg,wg=o_,Og=oo,Pg=ar,Mg=gg.PROPER,Lg=gg.CONFIGURABLE,xg="ArrayBuffer",Vg="DataView",Ug="prototype",Fg="Wrong index",Bg=Pg.getterFor(xg),Hg=Pg.getterFor(Vg),jg=Pg.set,Wg=pg[xg],Gg=Wg,Jg=Gg&&Gg[Ug],zg=pg[Vg],Kg=zg&&zg[Ug],qg=Object.prototype,Yg=pg.Array,Qg=pg.RangeError,Xg=mg(Ng),$g=mg([].reverse),Zg=Cg.pack,eT=Cg.unpack,tT=function(e){return[255&e]},iT=function(e){return[255&e,e>>8&255]},rT=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},nT=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},oT=function(e){return Zg(e,23,4)},sT=function(e){return Zg(e,52,8)},aT=function(e,t,i){Eg(e[Ug],t,{configurable:!0,get:function(){return i(this)[t]}})},cT=function(e,t,i,r){var n=Rg(i),o=Hg(e);if(n+t>o.byteLength)throw Qg(Fg);var s=o.bytes,a=n+o.byteOffset,c=wg(s,a,a+t);return r?c:$g(c)},lT=function(e,t,i,r,n,o){var s=Rg(i),a=Hg(e);if(s+t>a.byteLength)throw Qg(Fg);for(var c=a.bytes,l=s+a.byteOffset,d=r(+n),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(fg){var dT=Mg&&Wg.name!==xg;if(yg((function(){Wg(1)}))&&yg((function(){new Wg(-1)}))&&!yg((function(){return new Wg,new Wg(1.5),new Wg(NaN),1!=Wg.length||dT&&!Lg})))dT&&Lg&&Tg(Wg,"name",xg);else{(Gg=function(e){return Sg(this,Jg),new Wg(Rg(e))})[Ug]=Jg;for(var uT,hT=Dg(Wg),pT=0;hT.length>pT;)(uT=hT[pT++])in Gg||Tg(Gg,uT,Wg[uT]);Jg.constructor=Gg}kg&&bg(Kg)!==qg&&kg(Kg,qg);var mT=new zg(new Gg(2)),_T=mg(Kg.setInt8);mT.setInt8(0,2147483648),mT.setInt8(1,2147483649),!mT.getInt8(0)&&mT.getInt8(1)||vg(Kg,{setInt8:function(e,t){_T(this,e,t<<24>>24)},setUint8:function(e,t){_T(this,e,t<<24>>24)}},{unsafe:!0})}else Jg=(Gg=function(e){Sg(this,Jg);var t=Rg(e);jg(this,{type:xg,bytes:Xg(Yg(t),0),byteLength:t}),_g||(this.byteLength=t,this.detached=!1)})[Ug],Kg=(zg=function(e,t,i){Sg(this,Kg),Sg(e,Jg);var r=Bg(e),n=r.byteLength,o=Ig(t);if(o<0||o>n)throw Qg("Wrong offset");if(o+(i=void 0===i?n-o:Ag(i))>n)throw Qg("Wrong length");jg(this,{type:Vg,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),_g||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[Ug],_g&&(aT(Gg,"byteLength",Bg),aT(zg,"buffer",Hg),aT(zg,"byteLength",Hg),aT(zg,"byteOffset",Hg)),vg(Kg,{getInt8:function(e){return cT(this,1,e)[0]<<24>>24},getUint8:function(e){return cT(this,1,e)[0]},getInt16:function(e){var t=cT(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=cT(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return nT(cT(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return nT(cT(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return eT(cT(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return eT(cT(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){lT(this,1,e,tT,t)},setUint8:function(e,t){lT(this,1,e,tT,t)},setInt16:function(e,t){lT(this,2,e,iT,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){lT(this,2,e,iT,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){lT(this,4,e,rT,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){lT(this,4,e,rT,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){lT(this,4,e,oT,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){lT(this,8,e,sT,t,arguments.length>2?arguments[2]:void 0)}});Og(Gg,xg),Og(zg,Vg);var fT={ArrayBuffer:Gg,DataView:zg},gT=Vn,TT=Ta,ET=i,vT=Ce,yT=Ut,ST=Ht,IT=da,AT=fT.ArrayBuffer,RT=fT.DataView,CT=RT.prototype,bT=TT(AT.prototype.slice),kT=TT(CT.getUint8),DT=TT(CT.setUint8);gT({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:ET((function(){return!new AT(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(bT&&void 0===t)return bT(vT(this),e);for(var i=vT(this).byteLength,r=yT(e,i),n=yT(void 0===t?i:t,i),o=new(IT(this,AT))(ST(n-r)),s=new RT(this),a=new RT(o),c=0;r<n;)DT(a,c++,kT(s,r++));return o}});var NT,wT,OT,PT={},MT={get exports(){return PT},set exports(e){PT=e}},LT=Xf,xT=ke,VT=C,UT=Ee,FT=Se,BT=W,HT=Vs,jT=Qe,WT=Ki,GT=tn,JT=ys,zT=We,KT=zn,qT=So,YT=_e,QT=q,XT=ar.enforce,$T=ar.get,ZT=VT.Int8Array,eE=ZT&&ZT.prototype,tE=VT.Uint8ClampedArray,iE=tE&&tE.prototype,rE=ZT&&KT(ZT),nE=eE&&KT(eE),oE=Object.prototype,sE=VT.TypeError,aE=YT("toStringTag"),cE=QT("TYPED_ARRAY_TAG"),lE="TypedArrayConstructor",dE=LT&&!!qT&&"Opera"!==HT(VT.opera),uE=!1,hE={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},pE={BigInt64Array:8,BigUint64Array:8},mE=function(e){var t=KT(e);if(FT(t)){var i=$T(t);return i&&BT(i,lE)?i[lE]:mE(t)}},_E=function(e){if(!FT(e))return!1;var t=HT(e);return BT(hE,t)||BT(pE,t)};for(NT in hE)(OT=(wT=VT[NT])&&wT.prototype)?XT(OT)[lE]=wT:dE=!1;for(NT in pE)(OT=(wT=VT[NT])&&wT.prototype)&&(XT(OT)[lE]=wT);if((!dE||!UT(rE)||rE===Function.prototype)&&(rE=function(){throw sE("Incorrect invocation")},dE))for(NT in hE)VT[NT]&&qT(VT[NT],rE);if((!dE||!nE||nE===oE)&&(nE=rE.prototype,dE))for(NT in hE)VT[NT]&&qT(VT[NT].prototype,nE);if(dE&&KT(iE)!==nE&&qT(iE,nE),xT&&!BT(nE,aE))for(NT in uE=!0,JT(nE,aE,{configurable:!0,get:function(){return FT(this)?this[cE]:void 0}}),hE)VT[NT]&&WT(VT[NT],cE,NT);var fE={NATIVE_ARRAY_BUFFER_VIEWS:dE,TYPED_ARRAY_TAG:uE&&cE,aTypedArray:function(e){if(_E(e))return e;throw sE("Target is not a typed array")},aTypedArrayConstructor:function(e){if(UT(e)&&(!qT||zT(rE,e)))return e;throw sE(jT(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(xT){if(i)for(var n in hE){var o=VT[n];if(o&&BT(o.prototype,e))try{delete o.prototype[e]}catch(VB){try{o.prototype[e]=t}catch(s){}}}nE[e]&&!i||GT(nE,e,i?t:dE&&eE[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(xT){if(qT){if(i)for(r in hE)if((n=VT[r])&&BT(n,e))try{delete n[e]}catch(VB){}if(rE[e]&&!i)return;try{return GT(rE,e,i?t:dE&&rE[e]||t)}catch(VB){}}for(r in hE)!(n=VT[r])||n[e]&&!i||GT(n,e,t)}},getTypedArrayConstructor:mE,isView:function(e){if(!FT(e))return!1;var t=HT(e);return"DataView"===t||BT(hE,t)||BT(pE,t)},isTypedArray:_E,TypedArray:rE,TypedArrayPrototype:nE},gE=C,TE=i,EE=Nd,vE=fE.NATIVE_ARRAY_BUFFER_VIEWS,yE=gE.ArrayBuffer,SE=gE.Int8Array,IE=!vE||!TE((function(){SE(1)}))||!TE((function(){new SE(-1)}))||!EE((function(e){new SE,new SE(null),new SE(1.5),new SE(e)}),!0)||TE((function(){return 1!==new SE(new yE(2),1,void 0).length})),AE=Se,RE=Math.floor,CE=Number.isInteger||function(e){return!AE(e)&&isFinite(e)&&RE(e)===e},bE=Mt,kE=RangeError,DE=function(e){var t=bE(e);if(t<0)throw kE("The argument can't be less than 0");return t},NE=RangeError,wE=function(e,t){var i=DE(e);if(i%t)throw NE("Wrong offset");return i},OE=Vs,PE=_t,ME=TypeError,LE=function(e){var t=PE(e,"number");if("number"==typeof t)throw ME("Can't convert number to bigint");return BigInt(t)},xE=Sa,VE=Fe,UE=oa,FE=B,BE=Wt,HE=ad,jE=ed,WE=ql,GE=function(e){var t=OE(e);return"BigInt64Array"==t||"BigUint64Array"==t},JE=fE.aTypedArrayConstructor,zE=LE,KE=function(e){var t,i,r,n,o,s,a,c,l=UE(this),d=FE(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=jE(d);if(m&&!WE(m))for(c=(a=HE(d,m)).next,d=[];!(s=VE(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=xE(h,arguments[2])),i=BE(d),r=new(JE(l))(i),n=GE(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?zE(o):+o;return r},qE=Vn,YE=C,QE=Fe,XE=ke,$E=IE,ZE=fE,ev=fT,tv=Ds,iv=Gi,rv=Ki,nv=CE,ov=Ht,sv=tg,av=wE,cv=Tt,lv=W,dv=Vs,uv=Se,hv=qe,pv=Ni,mv=We,_v=So,fv=rn.f,gv=KE,Tv=ip.forEach,Ev=Cs,vv=ys,yv=Ne,Sv=cr,Iv=lu,Av=ar.get,Rv=ar.set,Cv=ar.enforce,bv=yv.f,kv=Sv.f,Dv=Math.round,Nv=YE.RangeError,wv=ev.ArrayBuffer,Ov=wv.prototype,Pv=ev.DataView,Mv=ZE.NATIVE_ARRAY_BUFFER_VIEWS,Lv=ZE.TYPED_ARRAY_TAG,xv=ZE.TypedArray,Vv=ZE.TypedArrayPrototype,Uv=ZE.aTypedArrayConstructor,Fv=ZE.isTypedArray,Bv="BYTES_PER_ELEMENT",Hv="Wrong length",jv=function(e,t){Uv(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},Wv=function(e,t){vv(e,t,{configurable:!0,get:function(){return Av(this)[t]}})},Gv=function(e){var t;return mv(Ov,e)||"ArrayBuffer"==(t=dv(e))||"SharedArrayBuffer"==t},Jv=function(e,t){return Fv(e)&&!hv(t)&&t in e&&nv(+t)&&t>=0},zv=function(e,t){return t=cv(t),Jv(e,t)?iv(2,e[t]):kv(e,t)},Kv=function(e,t,i){return t=cv(t),!(Jv(e,t)&&uv(i)&&lv(i,"value"))||lv(i,"get")||lv(i,"set")||i.configurable||lv(i,"writable")&&!i.writable||lv(i,"enumerable")&&!i.enumerable?bv(e,t,i):(e[t]=i.value,e)};XE?(Mv||(Sv.f=zv,yv.f=Kv,Wv(Vv,"buffer"),Wv(Vv,"byteOffset"),Wv(Vv,"byteLength"),Wv(Vv,"length")),qE({target:"Object",stat:!0,forced:!Mv},{getOwnPropertyDescriptor:zv,defineProperty:Kv}),MT.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=YE[n],c=a,l=c&&c.prototype,d={},u=function(e,t){bv(e,t,{get:function(){return function(e,t){var i=Av(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=Av(e);i&&(n=(n=Dv(n))<0?0:n>255?255:255&n),o.view[s](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};Mv?$E&&(c=t((function(e,t,i,n){return tv(e,l),Iv(uv(t)?Gv(t)?void 0!==n?new a(t,av(i,r),n):void 0!==i?new a(t,av(i,r)):new a(t):Fv(t)?jv(c,t):QE(gv,c,t):new a(sv(t)),e,c)})),_v&&_v(c,xv),Tv(fv(a),(function(e){e in c||rv(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){tv(e,l);var o,s,a,d=0,h=0;if(uv(t)){if(!Gv(t))return Fv(t)?jv(c,t):QE(gv,c,t);o=t,h=av(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw Nv(Hv);if((s=p-h)<0)throw Nv(Hv)}else if((s=ov(n)*r)+h>p)throw Nv(Hv);a=s/r}else a=sv(t),o=new wv(s=a*r);for(Rv(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Pv(o)});d<a;)u(e,d++)})),_v&&_v(c,xv),l=c.prototype=pv(Vv)),l.constructor!==c&&rv(l,"constructor",c),Cv(l).TypedArrayConstructor=c,Lv&&rv(l,Lv,n);var h=c!=a;d[n]=c,qE({global:!0,constructor:!0,forced:h,sham:!Mv},d),Bv in c||rv(c,Bv,r),Bv in l||rv(l,Bv,r),Ev(n)}):MT.exports=function(){},PT("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var qv=hg,Yv=LE,Qv=Vs,Xv=Fe,$v=i,Zv=fE.aTypedArray,ey=fE.exportTypedArrayMethod,ty=c("".slice);ey("fill",(function(e){var t=arguments.length;Zv(this);var i="Big"===ty(Qv(this),0,3)?Yv(e):+e;return Xv(qv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),$v((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var iy=C,ry=Fe,ny=fE,oy=Wt,sy=wE,ay=B,cy=i,ly=iy.RangeError,dy=iy.Int8Array,uy=dy&&dy.prototype,hy=uy&&uy.set,py=ny.aTypedArray,my=ny.exportTypedArrayMethod,_y=!cy((function(){var e=new Uint8ClampedArray(2);return ry(hy,e,{length:1,0:3},1),3!==e[1]})),fy=_y&&ny.NATIVE_ARRAY_BUFFER_VIEWS&&cy((function(){var e=new dy(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));my("set",(function(e){py(this);var t=sy(arguments.length>1?arguments[1]:void 0,1),i=ay(e);if(_y)return ry(hy,this,i,t);var r=this.length,n=oy(i),o=0;if(n+t>r)throw ly("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!_y||fy);var gy=Y.match(/firefox\/(\d+)/i),Ty=!!gy&&+gy[1],Ey=/MSIE|Trident/.test(Y),vy=Y.match(/AppleWebKit\/(\d+)\./),yy=!!vy&&+vy[1],Sy=Ta,Iy=i,Ay=et,Ry=u_,Cy=Ty,by=Ey,ky=ie,Dy=yy,Ny=fE.aTypedArray,wy=fE.exportTypedArrayMethod,Oy=C.Uint16Array,Py=Oy&&Sy(Oy.prototype.sort),My=!(!Py||Iy((function(){Py(new Oy(2),null)}))&&Iy((function(){Py(new Oy(2),{})}))),Ly=!!Py&&!Iy((function(){if(ky)return ky<74;if(Cy)return Cy<67;if(by)return!0;if(Dy)return Dy<602;var e,t,i=new Oy(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(Py(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));wy("sort",(function(e){return void 0!==e&&Ay(e),Ly?Py(this,e):Ry(Ny(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))}),!Ly||My);var xy=Vn,Vy=ke,Uy=c,Fy=W,By=Ee,Hy=We,jy=_u,Wy=ys,Gy=vn,Jy=C.Symbol,zy=Jy&&Jy.prototype;if(Vy&&By(Jy)&&(!("description"in zy)||void 0!==Jy().description)){var Ky={},qy=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:jy(arguments[0]),t=Hy(zy,this)?new Jy(e):void 0===e?Jy():Jy(e);return""===e&&(Ky[t]=!0),t};Gy(qy,Jy),qy.prototype=zy,zy.constructor=qy;var Yy="Symbol(test)"==String(Jy("test")),Qy=Uy(zy.valueOf),Xy=Uy(zy.toString),$y=/^Symbol\((.*)\)[^)]+$/,Zy=Uy("".replace),eS=Uy("".slice);Wy(zy,"description",{configurable:!0,get:function(){var e=Qy(this);if(Fy(Ky,e))return"";var t=Xy(e),i=Yy?eS(t,7,-1):Zy(t,$y,"$1");return""===i?void 0:i}}),xy({global:!0,constructor:!0,forced:!0},{Symbol:qy})}var tS=Vp.charAt,iS=_u,rS=ar,nS=jo,oS=Wo,sS="String Iterator",aS=rS.set,cS=rS.getterFor(sS);nS(String,"String",(function(e){aS(this,{type:sS,string:iS(e),index:0})}),(function(){var e,t=cS(this),i=t.string,r=t.index;return r>=i.length?oS(void 0,!0):(e=tS(i,r),t.index+=e.length,oS(e,!1))}));var lS,dS=ke,uS=c,hS=Fe,pS=i,mS=oi,_S=sn,fS=lr,gS=B,TS=g,ES=Object.assign,vS=Object.defineProperty,yS=uS([].concat),SS=!ES||pS((function(){if(dS&&1!==ES({b:1},ES(vS({},"a",{enumerable:!0,get:function(){vS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach((function(e){t[e]=e})),7!=ES({},e)[i]||mS(ES({},t)).join("")!=r}))?function(e,t){for(var i=gS(e),r=arguments.length,n=1,o=_S.f,s=fS.f;r>n;)for(var a,c=TS(arguments[n++]),l=o?yS(mS(c),o(c)):mS(c),d=l.length,u=0;d>u;)a=l[u++],dS&&!hS(s,c,a)||(i[a]=c[a]);return i}:ES,IS=Ce,AS=ud,RS=Sa,CS=Fe,bS=B,kS=function(e,t,i,r){try{return r?t(IS(i)[0],i[1]):t(i)}catch(VB){AS(e,"throw",VB)}},DS=ql,NS=ta,wS=Wt,OS=Zm,PS=ad,MS=ed,LS=Array,xS=c,VS=2147483647,US=/[^\0-\u007E]/,FS=/[.\u3002\uFF0E\uFF61]/g,BS="Overflow: input needs wider integers to process",HS=RangeError,jS=xS(FS.exec),WS=Math.floor,GS=String.fromCharCode,JS=xS("".charCodeAt),zS=xS([].join),KS=xS([].push),qS=xS("".replace),YS=xS("".split),QS=xS("".toLowerCase),XS=function(e){return e+22+75*(e<26)},$S=function(e,t,i){var r=0;for(e=i?WS(e/700):e>>1,e+=WS(e/t);e>455;)e=WS(e/35),r+=36;return WS(r+36*e/(e+38))},ZS=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=JS(e,i++);if(n>=55296&&n<=56319&&i<r){var o=JS(e,i++);56320==(64512&o)?KS(t,((1023&n)<<10)+(1023&o)+65536):(KS(t,n),i--)}else KS(t,n)}return t}(e);var i,r,n=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(r=e[i])<128&&KS(t,GS(r));var c=t.length,l=c;for(c&&KS(t,"-");l<n;){var d=VS;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>WS((VS-s)/u))throw HS(BS);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>VS)throw HS(BS);if(r==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;KS(t,GS(XS(m+_%f))),h=WS(_/f),p+=36}KS(t,GS(XS(h))),a=$S(s,u,l==c),s=0,l++}}s++,o++}return zS(t,"")},eI=Vn,tI=ke,iI=Km,rI=C,nI=Sa,oI=c,sI=tn,aI=ys,cI=Ds,lI=W,dI=SS,uI=function(e){var t=bS(e),i=NS(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=RS(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=MS(t),p=0;if(!h||this===LS&&DS(h))for(s=wS(t),a=i?new this(s):LS(s);s>p;p++)u=o?n(t[p],p):t[p],OS(a,p,u);else for(d=(l=PS(t,h)).next,a=i?new this:[];!(c=CS(d,l)).done;p++)u=o?kS(l,n,[c.value,p],!0):c.value,OS(a,p,u);return a.length=p,a},hI=o_,pI=Vp.codeAt,mI=function(e){var t,i,r=[],n=YS(qS(QS(e),FS,"."),".");for(t=0;t<n.length;t++)i=n[t],KS(r,jS(US,i)?"xn--"+ZS(i):i);return zS(r,".")},_I=_u,fI=oo,gI=Ra,TI=bf,EI=ar,vI=EI.set,yI=EI.getterFor("URL"),SI=TI.URLSearchParams,II=TI.getState,AI=rI.URL,RI=rI.TypeError,CI=rI.parseInt,bI=Math.floor,kI=Math.pow,DI=oI("".charAt),NI=oI(/./.exec),wI=oI([].join),OI=oI(1..toString),PI=oI([].pop),MI=oI([].push),LI=oI("".replace),xI=oI([].shift),VI=oI("".split),UI=oI("".slice),FI=oI("".toLowerCase),BI=oI([].unshift),HI="Invalid scheme",jI="Invalid host",WI="Invalid port",GI=/[a-z]/i,JI=/[\d+-.a-z]/i,zI=/\d/,KI=/^0x/i,qI=/^[0-7]+$/,YI=/^\d+$/,QI=/^[\da-f]+$/i,XI=/[\0\t\n\r #%/:<>?@[\\\]^|]/,$I=/[\0\t\n\r #/:<>?@[\\\]^|]/,ZI=/^[\u0000-\u0020]+/,eA=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,tA=/[\t\n\r]/g,iA=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)BI(t,e%256),e=bI(e/256);return wI(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i&&(t=r,i=n),t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=OI(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},rA={},nA=dI({},rA,{" ":1,'"':1,"<":1,">":1,"`":1}),oA=dI({},nA,{"#":1,"?":1,"{":1,"}":1}),sA=dI({},oA,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),aA=function(e,t){var i=pI(e,0);return i>32&&i<127&&!lI(t,e)?e:encodeURIComponent(e)},cA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},lA=function(e,t){var i;return 2==e.length&&NI(GI,DI(e,0))&&(":"==(i=DI(e,1))||!t&&"|"==i)},dA=function(e){var t;return e.length>1&&lA(UI(e,0,2))&&(2==e.length||"/"===(t=DI(e,2))||"\\"===t||"?"===t||"#"===t)},uA=function(e){return"."===e||"%2e"===FI(e)},hA={},pA={},mA={},_A={},fA={},gA={},TA={},EA={},vA={},yA={},SA={},IA={},AA={},RA={},CA={},bA={},kA={},DA={},NA={},wA={},OA={},PA=function(e,t,i){var r,n,o,s=_I(e);if(t){if(n=this.parse(s))throw RI(n);this.searchParams=null}else{if(void 0!==i&&(r=new PA(i,!0)),n=this.parse(s,null,r))throw RI(n);(o=II(new SI)).bindURL(this),this.searchParams=o}};PA.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||hA,d=0,u="",h=!1,p=!1,m=!1;for(e=_I(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=LI(e,ZI,""),e=LI(e,eA,"$1")),e=LI(e,tA,""),r=uI(e);d<=r.length;){switch(n=r[d],l){case hA:if(!n||!NI(GI,n)){if(t)return HI;l=mA;continue}u+=FI(n),l=pA;break;case pA:if(n&&(NI(JI,n)||"+"==n||"-"==n||"."==n))u+=FI(n);else{if(":"!=n){if(t)return HI;u="",l=mA,d=0;continue}if(t&&(c.isSpecial()!=lI(cA,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&cA[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=RA:c.isSpecial()&&i&&i.scheme==c.scheme?l=_A:c.isSpecial()?l=EA:"/"==r[d+1]?(l=fA,d++):(c.cannotBeABaseURL=!0,MI(c.path,""),l=NA)}break;case mA:if(!i||i.cannotBeABaseURL&&"#"!=n)return HI;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=hI(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=OA;break}l="file"==i.scheme?RA:gA;continue;case _A:if("/"!=n||"/"!=r[d+1]){l=gA;continue}l=vA,d++;break;case fA:if("/"==n){l=yA;break}l=DA;continue;case gA:if(c.scheme=i.scheme,n==lS)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=TA;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query="",l=wA;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.path.length--,l=DA;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=hI(i.path),c.query=i.query,c.fragment="",l=OA}break;case TA:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=DA;continue}l=yA}else l=vA;break;case EA:if(l=vA,"/"!=n||"/"!=DI(u,d+1))continue;d++;break;case vA:if("/"!=n&&"\\"!=n){l=yA;continue}break;case yA:if("@"==n){h&&(u="%40"+u),h=!0,o=uI(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=aA(f,sA);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==lS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=uI(u).length+1,u="",l=SA}else u+=n;break;case SA:case IA:if(t&&"file"==c.scheme){l=bA;continue}if(":"!=n||p){if(n==lS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return jI;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=kA,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return jI;if(s=c.parseHost(u))return s;if(u="",l=AA,t==IA)return}break;case AA:if(!NI(zI,n)){if(n==lS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=CI(u,10);if(T>65535)return WI;c.port=c.isSpecial()&&T===cA[c.scheme]?null:T,u=""}if(t)return;l=kA;continue}return WI}u+=n;break;case RA:if(c.scheme="file","/"==n||"\\"==n)l=CA;else{if(!i||"file"!=i.scheme){l=DA;continue}if(n==lS)c.host=i.host,c.path=hI(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=hI(i.path),c.query="",l=wA;else{if("#"!=n){dA(wI(hI(r,d),""))||(c.host=i.host,c.path=hI(i.path),c.shortenPath()),l=DA;continue}c.host=i.host,c.path=hI(i.path),c.query=i.query,c.fragment="",l=OA}}break;case CA:if("/"==n||"\\"==n){l=bA;break}i&&"file"==i.scheme&&!dA(wI(hI(r,d),""))&&(lA(i.path[0],!0)?MI(c.path,i.path[0]):c.host=i.host),l=DA;continue;case bA:if(n==lS||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&lA(u))l=DA;else if(""==u){if(c.host="",t)return;l=kA}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=kA}continue}u+=n;break;case kA:if(c.isSpecial()){if(l=DA,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=lS&&(l=DA,"/"!=n))continue}else c.fragment="",l=OA;else c.query="",l=wA;break;case DA:if(n==lS||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=FI(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||MI(c.path,"")):uA(u)?"/"==n||"\\"==n&&c.isSpecial()||MI(c.path,""):("file"==c.scheme&&!c.path.length&&lA(u)&&(c.host&&(c.host=""),u=DI(u,0)+":"),MI(c.path,u)),u="","file"==c.scheme&&(n==lS||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)xI(c.path);"?"==n?(c.query="",l=wA):"#"==n&&(c.fragment="",l=OA)}else u+=aA(n,oA);break;case NA:"?"==n?(c.query="",l=wA):"#"==n?(c.fragment="",l=OA):n!=lS&&(c.path[0]+=aA(n,rA));break;case wA:t||"#"!=n?n!=lS&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":aA(n,rA)):(c.fragment="",l=OA);break;case OA:n!=lS&&(c.fragment+=aA(n,nA))}d++}},parseHost:function(e){var t,i,r;if("["==DI(e,0)){if("]"!=DI(e,e.length-1))return jI;if(t=function(e){var t,i,r,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return DI(e,u)};if(":"==h()){if(":"!=DI(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&NI(QI,h());)t=16*t+CI(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(r=0;h();){if(n=null,r>0){if(!("."==h()&&r<4))return;u++}if(!NI(zI,h()))return;for(;NI(zI,h());){if(o=CI(h(),10),null===n)n=o;else{if(0==n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++r&&4!=r||l++}if(4!=r)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(UI(e,1,-1)),!t)return jI;this.host=t}else if(this.isSpecial()){if(e=mI(e),NI(XI,e))return jI;if(t=function(e){var t,i,r,n,o,s,a,c=VI(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""==(n=c[r]))return e;if(o=10,n.length>1&&"0"==DI(n,0)&&(o=NI(KI,n)?16:8,n=UI(n,8==o?1:2)),""===n)s=0;else{if(!NI(10==o?YI:8==o?qI:QI,n))return e;s=CI(n,o)}MI(i,s)}for(r=0;r<t;r++)if(s=i[r],r==t-1){if(s>=kI(256,5-t))return null}else if(s>255)return null;for(a=PI(i),r=0;r<i.length;r++)a+=i[r]*kI(256,3-r);return a}(e),null===t)return jI;this.host=t}else{if(NI($I,e))return jI;for(t="",i=uI(e),r=0;r<i.length;r++)t+=aA(i[r],rA);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return lI(cA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&lA(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=i+(r?":"+r:"")+"@"),l+=iA(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+wI(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw RI(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new MA(e.path[0]).origin}catch(VB){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+iA(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(_I(e)+":",hA)},getUsername:function(){return this.username},setUsername:function(e){var t=uI(_I(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=aA(t[i],sA)}},getPassword:function(){return this.password},setPassword:function(e){var t=uI(_I(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=aA(t[i],sA)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?iA(e):iA(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,SA)},getHostname:function(){var e=this.host;return null===e?"":iA(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,IA)},getPort:function(){var e=this.port;return null===e?"":_I(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=_I(e))?this.port=null:this.parse(e,AA))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+wI(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,kA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=_I(e))?this.query=null:("?"==DI(e,0)&&(e=UI(e,1)),this.query="",this.parse(e,wA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=_I(e))?("#"==DI(e,0)&&(e=UI(e,1)),this.fragment="",this.parse(e,OA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var MA=function(e){var t=cI(this,LA),i=gI(arguments.length,1)>1?arguments[1]:void 0,r=vI(t,new PA(e,!1,i));tI||(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())},LA=MA.prototype,xA=function(e,t){return{get:function(){return yI(this)[e]()},set:t&&function(e){return yI(this)[t](e)},configurable:!0,enumerable:!0}};if(tI&&(aI(LA,"href",xA("serialize","setHref")),aI(LA,"origin",xA("getOrigin")),aI(LA,"protocol",xA("getProtocol","setProtocol")),aI(LA,"username",xA("getUsername","setUsername")),aI(LA,"password",xA("getPassword","setPassword")),aI(LA,"host",xA("getHost","setHost")),aI(LA,"hostname",xA("getHostname","setHostname")),aI(LA,"port",xA("getPort","setPort")),aI(LA,"pathname",xA("getPathname","setPathname")),aI(LA,"search",xA("getSearch","setSearch")),aI(LA,"searchParams",xA("getSearchParams")),aI(LA,"hash",xA("getHash","setHash"))),sI(LA,"toJSON",(function(){return yI(this).serialize()}),{enumerable:!0}),sI(LA,"toString",(function(){return yI(this).serialize()}),{enumerable:!0}),AI){var VA=AI.createObjectURL,UA=AI.revokeObjectURL;VA&&sI(MA,"createObjectURL",nI(VA,AI)),UA&&sI(MA,"revokeObjectURL",nI(UA,AI))}fI(MA,"URL"),eI({global:!0,constructor:!0,forced:!iI,sham:!tI},{URL:MA}),PT("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var FA=Cs,BA="ArrayBuffer",HA=fT[BA];Vn({global:!0,constructor:!0,forced:C[BA]!==HA},{ArrayBuffer:HA}),FA(BA);var jA=Vn,WA=jh,GA=c([].reverse),JA=[1,2];jA({target:"Array",proto:!0,forced:String(JA)===String(JA.reverse())},{reverse:function(){return WA(this)&&(this.length=this.length),GA(this)}});var zA=Qe,KA=TypeError,qA=Vn,YA=c,QA=et,XA=B,$A=Wt,ZA=function(e,t){if(!delete e[t])throw KA("Cannot delete property "+zA(t)+" of "+zA(e))},eR=_u,tR=i,iR=u_,rR=np,nR=Ty,oR=Ey,sR=ie,aR=yy,cR=[],lR=YA(cR.sort),dR=YA(cR.push),uR=tR((function(){cR.sort(void 0)})),hR=tR((function(){cR.sort(null)})),pR=rR("sort"),mR=!tR((function(){if(sR)return sR<70;if(!(nR&&nR>3)){if(oR)return!0;if(aR)return aR<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)cR.push({k:t+r,v:i})}for(cR.sort((function(e,t){return t.v-e.v})),r=0;r<cR.length;r++)t=cR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));qA({target:"Array",proto:!0,forced:uR||!hR||!pR||!mR},{sort:function(e){void 0!==e&&QA(e);var t=XA(this);if(mR)return void 0===e?lR(t):lR(t,e);var i,r,n=[],o=$A(t);for(r=0;r<o;r++)r in t&&dR(n,t[r]);for(iR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:eR(t)>eR(i)?1:-1}}(e)),i=$A(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)ZA(t,r++);return t}}),(0,fE.exportTypedArrayStaticMethod)("from",KE,IE);let _R=!0,fR=!0;function gR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function TR(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};const o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ER(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_R=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function vR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(fR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function yR(){if("object"==typeof window){if(_R)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function SR(e,t){fR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function IR(e){return"[object Object]"===Object.prototype.toString.call(e)}function AR(e){return IR(e)?Object.keys(e).reduce((function(t,i){const r=IR(e[i]),n=r?AR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function RR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?RR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{RR(e,e.get(t),i)}))})))}function CR(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===r&&i.trackId===t.id&&RR(e,i,n)}))})),n}const bR=yR;function kR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),e={},e[n("max",i)]=r.ideal,t.optional.push(e)):(e[n("",i)]=r.ideal,t.optional.push(e))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach((e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let s=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),bR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return bR("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,r){n(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{r&&r(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function DR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function NR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else TR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function wR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function OR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const r=function(e){i(o(n(e)))};return t.apply(this,[r,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])})).then(i,r)}}function PR(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>CR(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),TR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>CR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,r;return this.getSenders().forEach((i=>{i.track===e&&(t?r=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?r=!0:i=t),t.track===e))),r||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function MR(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const r=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(r)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function LR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return MR(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[i.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=r[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function xR(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function VR(e,t){TR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var UR=Object.freeze({__proto__:null,shimMediaStream:DR,shimOnTrack:NR,shimGetSendersWithDtmf:wR,shimGetStats:OR,shimSenderReceiverGetStats:PR,shimAddTrackRemoveTrackWithNative:MR,shimAddTrackRemoveTrack:LR,shimPeerConnection:xR,fixNegotiationNeeded:VR,shimGetUserMedia:kR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function FR(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){SR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){const t=r.prototype.getSettings;r.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){const t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function BR(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function HR(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return r.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(ub){if("TypeError"!==ub.name)throw ub;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function jR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function WR(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),TR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function GR(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){SR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function JR(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function zR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const r=t.apply(this,arguments);if(i){const{sender:t}=r,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return r})}function KR(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function qR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function YR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var QR=Object.freeze({__proto__:null,shimOnTrack:BR,shimPeerConnection:HR,shimSenderGetStats:jR,shimReceiverGetStats:WR,shimRemoveStream:GR,shimRTCDataChannel:JR,shimAddTransceiver:zR,shimGetParameters:KR,shimCreateOffer:qR,shimCreateAnswer:YR,shimGetUserMedia:FR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function XR(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function $R(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function ZR(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,i){const r=n.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r};t.setLocalDescription=a,a=function(e,t,i){const r=o.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.setRemoteDescription=a,a=function(e,t,i){const r=s.apply(this,[e]);return i?(r.then(t,i),Promise.resolve()):r},t.addIceCandidate=a}function eC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(tC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function tC(e){return e&&void 0!==e.video?Object.assign({},e,{video:AR(e.video)}):e}function iC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];void 0===r.urls&&r.url?(SR("RTCIceServer.url","RTCIceServer.urls"),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function rC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function nC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function oC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var sC=Object.freeze({__proto__:null,shimLocalStreamsAPI:XR,shimRemoteStreamsAPI:$R,shimCallbacksAPI:ZR,shimGetUserMedia:eC,shimConstraints:tC,shimRTCIceServerUrls:iC,shimTrackEventTransceiver:rC,shimCreateOfferLegacy:nC,shimAudioContext:oC}),aC={},cC={get exports(){return aC},set exports(e){aC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:void 0===i[t[r]]&&(i[t[r]]=t[r+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const r=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<r.length;n++)i=r[n].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const r=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const r=t.matchPrefix(e+i,"a=ice-ufrag:")[0],n=t.matchPrefix(e+i,"a=ice-pwd:")[0];return r&&n?{usernameFragment:r.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const n=r[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const r=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(r.parameters=o.length?t.parseFmtp(o[0]):{},r.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),i.codecs.push(r),r.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let r="";r+="m="+e+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));let n=0;return i.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(r+="a=maxptime:"+n+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){const i=[],r=t.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),r.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=n.length>0,i.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const r=t.matchPrefix(e,"a=msid:");if(1===r.length)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(i=n[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");let n;r.length>0&&(n=parseInt(r[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,r){let n;const o=void 0!==i?i:2;n=e||t.generateSessionId();return"v=0\r\no="+(r||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const r=t.splitLines(e);for(let t=0;t<r.length;t++)switch(r[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(cC);var lC=aC,dC=e({__proto__:null,default:lC},[aC]);function uC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),r=lC.parseCandidate(e.candidate);for(const e in r)e in i||Object.defineProperty(i,e,{value:r[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,TR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function hC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||TR(e,"icecandidate",(e=>{if(e.candidate){const t=lC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function pC(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=lC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=lC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),r=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);const n=lC.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(r=2147483637),r}(arguments[0],e);let n;n=0===i&&0===r?Number.POSITIVE_INFINITY:0===i||0===r?Math.max(i,r):Math.min(i,r);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return i.apply(this,arguments)}}function mC(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},TR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function _C(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function fC(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function gC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function TC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var EC=Object.freeze({__proto__:null,shimRTCIceCandidate:uC,shimRTCIceCandidateRelayProtocol:hC,shimMaxMessageSize:pC,shimSendThrowTypeError:mC,shimConnectionState:_C,removeExtmapAllowMixed:fC,shimAddIceCandidateNullOrEmpty:gC,shimParameterlessSetLocalDescription:TC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=yR,r=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=gR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=gR(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=gR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:EC,extractVersion:gR,disableLog:ER,disableWarnings:vR,sdp:dC};switch(r.browser){case"chrome":if(!UR||!xR||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(null===r.version)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=UR,gC(e,r),TC(e),kR(e,r),DR(e),xR(e,r),NR(e),LR(e,r),wR(e),OR(e),PR(e),VR(e,r),uC(e),hC(e),_C(e),pC(e,r),mC(e),fC(e,r);break;case"firefox":if(!QR||!HR||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=QR,gC(e,r),TC(e),FR(e,r),HR(e,r),BR(e),GR(e),jR(e),WR(e),JR(e),zR(e),KR(e),qR(e),YR(e),uC(e),_C(e),pC(e,r),mC(e);break;case"safari":if(!sC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=sC,gC(e,r),TC(e),iC(e),nC(e),ZR(e),XR(e),$R(e),rC(e),eC(e),oC(e),uC(e),hC(e),pC(e,r),mC(e),fC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var vC,yC=Object.create,SC=Object.defineProperty,IC=Object.defineProperties,AC=Object.getOwnPropertyDescriptor,RC=Object.getOwnPropertyDescriptors,CC=Object.getOwnPropertyNames,bC=Object.getOwnPropertySymbols,kC=Object.getPrototypeOf,DC=Object.prototype.hasOwnProperty,NC=Object.prototype.propertyIsEnumerable,wC=Reflect.get,OC=Math.pow,PC=(e,t,i)=>t in e?SC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,MC=(e,t)=>{for(var i in t||(t={}))DC.call(t,i)&&PC(e,i,t[i]);if(bC)for(var i of bC(t))NC.call(t,i)&&PC(e,i,t[i]);return e},LC=(e,t)=>IC(e,RC(t)),xC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),VC=(e,t)=>{for(var i in t)SC(e,i,{get:t[i],enumerable:!0})},UC=(e,t,i)=>(i=null!=e?yC(kC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of CC(t))!DC.call(e,n)&&n!==i&&SC(e,n,{get:()=>t[n],enumerable:!(r=AC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:SC(i,"default",{value:e,enumerable:!0}),e)),FC=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?AC(t,i):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(r?n(t,i,o):n(o))||o);return r&&o&&SC(t,i,o),o},BC=(e,t,i)=>(PC(e,"symbol"!=typeof t?t+"":t,i),i),HC=(e,t,i)=>wC(kC(e),i,t),jC=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(hO){n(hO)}},s=e=>{try{a(i.throw(e))}catch(hO){n(hO)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),WC=xC(((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,n||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)i.call(e,t)&&n.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n<o;n++)s[n]=i[n].fn;return s},c.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,n,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,n),!0;case 5:return d.fn.call(d.context,t,i,n,o),!0;case 6:return d.fn.call(d.context,t,i,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,n){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),GC=xC(((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")}))}))})),JC=xC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=GC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),zC=xC(((e,t)=>{var i=GC(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),KC=xC((e=>{var t=JC(),i=zC();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})),qC=xC(((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")}))}))})),YC=xC((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var n=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:n&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:n?i[e.name]:i;(function(e,i,r,n){if(n&&!r)i[n]=t(e[1]);else for(var o=0;o<r.length;o+=1)null!=e[o+1]&&(i[r[o]]=t(e[o+1]))})(r.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},r=qC(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(r[t]||[]).length;a+=1){var c=r[t][a];if(c.reg.test(n))return i(c,s,n)}})),t.media=o,t};var o=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),n=0;n<r.length;n+=3)i.push({component:r[n],ip:r[n+1],port:r[n+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}})),QC=xC(((e,t)=>{var i=qC(),r=/%[sdv%]/g,n=function(e){var t=1,i=arguments,n=i.length;return e.replace(r,(function(e){if(t>=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},o=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?r.push(i[t.name][s]):r.push(i[t.names[o]])}else r.push(i[t.name]);return n.apply(null,r)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||s,n=t.innerOrder||a,c=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),XC=xC((e=>{var t=YC(),i=QC();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})),$C=UC(WC()),ZC=((vC=ZC||{})[vC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",vC[vC.INVALID_OPERATION=4097]="INVALID_OPERATION",vC[vC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",vC[vC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",vC[vC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",vC[vC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",vC[vC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",vC[vC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",vC[vC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",vC[vC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",vC[vC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",vC[vC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",vC[vC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",vC[vC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",vC[vC.CLIENT_BANNED=16448]="CLIENT_BANNED",vC[vC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",vC[vC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",vC[vC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",vC[vC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",vC[vC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",vC[vC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",vC[vC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",vC[vC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",vC[vC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",vC[vC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",vC[vC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",vC[vC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",vC[vC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",vC[vC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",vC[vC.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",vC[vC.UNKNOWN=65535]="UNKNOWN",vC),eb=ZC,tb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=eb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in eb)if(eb[t]===e)return t;return"UNKNOWN"}(r)," 0x").concat(r.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),BC(this,"code"),BC(this,"extraCode"),BC(this,"message"),BC(this,"originMessage"),BC(this,"name"),BC(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ib=tb,rb=((new Date).getTime(),0),nb=function(){return(new Date).getTime()+rb},ob=function(){let e=new Date;return e.setTime(nb()),e.toLocaleString()},sb={};VC(sb,{bytes2ms:()=>pw,convertObjectNumberToInt:()=>iO,copyProperties:()=>hw,deepClone:()=>zw,deepMerge:()=>Jw,delay:()=>rO,fibonacci:()=>vw,formatedTime:()=>Yw,getAbilityConfigUrl:()=>ew,getConstructorName:()=>Mw,getContainerFromElement:()=>qw,getEnv:()=>nw,getInternalVersion:()=>Fw,getLoggerUrl:()=>sw,getMuteStateFromFlag:()=>jw,getNetworkType:()=>cw,getNumNetworkType:()=>uw,getReconnectionTimeout:()=>yw,getStringByteLength:()=>$w,getTurnServer:()=>Ww,getUint32Version:()=>tO,getValueType:()=>Sw,getViewListFromView:()=>Kw,glog:()=>gw,ipv4ToUint32:()=>Gw,isArray:()=>Dw,isAudioWorkletSupported:()=>Lw,isBoolean:()=>bw,isConstructor:()=>Pw,isEmpty:()=>Hw,isFunction:()=>Iw,isLangChinese:()=>Tw,isMediaStreamTrack:()=>Nw,isNumber:()=>Cw,isObject:()=>kw,isOverseaSdkAppId:()=>ow,isPlainObject:()=>Ew,isPortrait:()=>Zw,isPromise:()=>Ow,isRemoteTrack:()=>ww,isString:()=>Rw,isUndefined:()=>Aw,loadImage:()=>eO,ms2bytes:()=>_w,ms2samples:()=>fw,performanceNow:()=>Vw,promiseAny:()=>xw,samples2ms:()=>mw,setNetworkType:()=>dw,stringify:()=>Qw,stringifyIncludeValue:()=>Xw,throttlePromise:()=>nO});var ab={};VC(ab,{AUDIO_MUTE_BIT:()=>Kb,AUDIO_STAT_BIT:()=>zb,AUX_STAT_BIT:()=>Jb,AUX_STREAM_MSID:()=>$b,BACKEND_ENV:()=>Hb,BASE_DOC_URL:()=>Ib,BASE_HOST:()=>Eb,CAPABILITIES_KEYS:()=>Wk,CLASS_NAME:()=>Nk,CLOUD_CONSOLE_URL:()=>Sb,CROSS_ROOM_BIT:()=>Qb,DATA_FREEZE_TIMING:()=>Ik,DOC_URL:()=>Ab,DTLS_STATE_UNKNOWN:()=>ck,ENV_NAME:()=>Db,EXCHANGE_SDP_TIMEOUT:()=>Tk,INTERVAL:()=>Hk,IS_WORKER:()=>mb,IS_WORKLET:()=>_b,KIBANA_EVENT:()=>_k,LOCAL_STREAM_PUBLISH_STATE:()=>Sk,LOGGER_CMD_TYPE:()=>kb,LOGGER_DOMAIN:()=>Rb,LOGGER_DOMAIN_OVERSEA:()=>Cb,LOG_LEVEL:()=>Nb,LOG_LEVEL_NAME:()=>Lk,MAIN_STREAM_MSID:()=>Xb,MAX_RTT:()=>Gk,MICROPHONE_COMMUNICATIONS:()=>Mk,MICROPHONE_DEFAULT:()=>Ok,MUTE_ALL_BIT:()=>Yb,NAME:()=>Fb,NETWORK_TYPE:()=>Pb,NOT_SUPPORTED_H264:()=>yk,PAUSED_RETRY_COUNT:()=>wk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>bk,PEER_CONNECTION_STATE:()=>lk,PEER_LEAVE_REASON:()=>xk,RAF:()=>Bk,RECOVER_CAPTURE_INTERVAL:()=>Uk,REMOTE_STREAM_TYPE_AUX:()=>ek,REMOTE_STREAM_TYPE_MAIN:()=>Zb,RENDER_FREEZE_TIMING:()=>Ak,RIC:()=>Fk,SCHEDULE_DOMAIN:()=>kk,SCHEDULE_TIMEOUT:()=>Dk,SDP_SEMANTICS_PLAN_B:()=>vk,SDP_SEMANTICS_UNIFIED_PLAN:()=>Ek,SECOND_HOST:()=>vb,SIGNAL_PING_PONG_INTERVAL:()=>Ob,SIGNAL_PING_TIMEOUT:()=>wb,SIGNAL_RECONNECTION_COUNT:()=>mk,SMALL_STAT_BIT:()=>Gb,SPEAKER_DEFAULT:()=>Pk,STORAGE_EXPIRES_TIME:()=>Mb,STREAM_TYPE_BIG:()=>Rk,STREAM_TYPE_SMALL:()=>Ck,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Vk,SYNC_USER_LIST_INTERVAL:()=>fk,Scene:()=>jb,Switch:()=>Lb,THIRD_HOST:()=>yb,TIMEOUT:()=>jk,TRANSPORT_DIRECTION:()=>Bb,TRTC_ERROR_ASSISTANCE:()=>bb,TRTC_QUALITY_BAD:()=>ok,TRTC_QUALITY_DISCONNECTED:()=>ak,TRTC_QUALITY_EXCELLENT:()=>ik,TRTC_QUALITY_GOOD:()=>rk,TRTC_QUALITY_POOR:()=>nk,TRTC_QUALITY_UNKNOWN:()=>tk,TRTC_QUALITY_VERY_BAD:()=>sk,UPDATE_OFFER_TIMEOUT:()=>gk,VIDEO_MUTE_BIT:()=>qb,VIDEO_STAT_BIT:()=>Wb,audioProfileMap:()=>xb,getRetryCount:()=>hk,getScriptDir:()=>fb,innerVersion:()=>cb,loggerProxy:()=>gb,screenProfileMap:()=>Ub,setLoggerProxy:()=>Tb,setRetryCount:()=>uk,setVersion:()=>db,version:()=>lb,videoProfileMap:()=>Vb});var cb="4.15.00.1600",lb="5.0.0";function db(e){lb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));cb="".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 ub,hb,pb,mb="undefined"!=typeof importScripts,_b="undefined"!=typeof registerProcessor,fb=()=>{let e=mb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},gb="",Tb=e=>gb=e,Eb="web.sdk.qcloud.com",vb="web.sdk.tencent.cn",yb="web.sdk.cloud.tencent.cn",Sb="https://console.cloud.tencent.com/trtc",Ib="https://".concat(Eb,"/trtc/webrtc/v5/doc"),Ab="".concat(Ib,"/zh-cn/"),Rb="https://yun.tim.qq.com",Cb="https://apisgp.my-imcloud.com",bb="trtc_error_assistance",kb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Db={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Nb=((pb=Nb||{})[pb.TRACE=0]="TRACE",pb[pb.DEBUG=1]="DEBUG",pb[pb.INFO=2]="INFO",pb[pb.WARN=3]="WARN",pb[pb.ERROR=4]="ERROR",pb[pb.NONE=5]="NONE",pb),wb=18e3,Ob=2e3,Pb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Mb=6048e5,Lb=((hb=Lb||{}).USEAINS="useAINS",hb.ENABLEDEBUG="enableDebug",hb.USEV2="useV2",hb.USEWT="useWt",hb),xb={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}},Vb={"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}},Ub={"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}},Fb={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},Bb={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Hb={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},jb=((ub=jb||{}).LIVE="live",ub.RTC="rtc",ub),Wb=1,Gb=2,Jb=4,zb=8,Kb=64,qb=16,Yb=112,Qb=128,Xb="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",$b="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zb=Fb.MAIN,ek=Fb.AUXILIARY,tk=0,ik=1,rk=2,nk=3,ok=4,sk=5,ak=6,ck="unknown",lk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},dk=1/0;function uk(e){dk=e}function hk(){return dk}var pk,mk=30,_k={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"},fk=1e4,gk=1e4,Tk=1e4,Ek="unified-plan",vk="plan-b",yk=1028,Sk=((pk=Sk||{})[pk.UNPUBLISH=-1]="UNPUBLISH",pk[pk.PUBLISHING=0]="PUBLISHING",pk[pk.PUBLISHED=1]="PUBLISHED",pk),Ik=500,Ak=1e3,Rk=Fb.BIG,Ck=Fb.SMALL,bk=1e4,kk={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"},Dk=2e3,Nk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},wk=5,Ok="default",Pk=Ok,Mk="communications",Lk=Object.keys(Nb),xk=["normal leave","timeout leave","kick","role change"],Vk=10,Uk=2e3,Fk="ric",Bk="raf",Hk="interval",jk="timeout",Wk=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Gk=1e4;function Jk(e){let{url:t,body:i,method:r,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(r||"POST",t,!0),o.send(i)}))}function zk(e){return jC(this,null,(function*(){let t=Vw(),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 cO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Vw()-t,"ms")),r}catch(pk){return i}}))}var Kk=1e8,qk={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"},Yk={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(Sw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(Sw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType: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 ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},Qk={};VC(Qk,{ANDROID_VERSION:()=>lD,CHROME_MAJOR_VERSION:()=>uN,CHROME_VERSION:()=>hN,EDGE_VERSION:()=>fD,EDG_MAJOR_VERSION:()=>ED,EDG_VERSION:()=>TD,FIREFOX_MAJOR_VERSION:()=>mD,FIREFOX_VERSION:()=>pD,HUAWEI_VERSION:()=>eN,IE_VERSION:()=>ND,IOS_MAIN_VERSION:()=>TN,IOS_VERSION:()=>gN,IPADQQB_VERSION:()=>HD,IS_ANDROID:()=>cD,IS_ANDROID_WEBVIEW:()=>fN,IS_ANY_SAFARI:()=>mN,IS_CHROME:()=>lN,IS_CHROME_OS:()=>JD,IS_CHROMIUM_BASE:()=>cN,IS_EDG:()=>gD,IS_EDGE:()=>_D,IS_ELECTRON:()=>qD,IS_FIREFOX:()=>hD,IS_HEADLESS_CHROME:()=>dN,IS_HONOR:()=>ZD,IS_HUAWEI:()=>$D,IS_HUAWEIBROWSER:()=>XD,IS_IE:()=>DD,IS_IE8:()=>kD,IS_IOS:()=>aD,IS_IOS_13_OR_14:()=>yN,IS_IOS_15_1:()=>vN,IS_IPAD:()=>rD,IS_IPADQQB:()=>BD,IS_IPAD_PRO:()=>nD,IS_IPHONE:()=>oD,IS_IPOD:()=>sD,IS_LINUX:()=>GD,IS_LOCAL:()=>SN,IS_MAC:()=>WD,IS_MACQQB:()=>UD,IS_MIBROWSER:()=>YD,IS_MQQB:()=>MD,IS_NATIVE_ANDROID:()=>uD,IS_OLD_ANDROID:()=>dD,IS_OPPOBROWSER:()=>rN,IS_SAFARI:()=>pN,IS_SAFARI_15_1:()=>EN,IS_SAMSUNGBROWSER:()=>tN,IS_SOGOU:()=>SD,IS_SOGOUM:()=>vD,IS_TBS:()=>AD,IS_UCBROWSER:()=>KD,IS_VIVOBROWSER:()=>oN,IS_WECHAT:()=>wD,IS_WIN:()=>jD,IS_WQQB:()=>xD,IS_WX:()=>zD,IS_X5MQQB:()=>PD,IS_XWEB:()=>CD,MACQQB_VERSION:()=>FD,MI_VERSION:()=>QD,MQQB_VERSION:()=>LD,OPPO_VERSION:()=>nN,SAFARI_VERSION:()=>_N,SAMSUNG_VERSION:()=>iN,SOGOUM_VERSION:()=>yD,SOGOU_VERSION:()=>ID,TBS_VERSION:()=>RD,UA_DATA_STRING:()=>bN,USER_AGENT:()=>Xk,VIVO_VERSION:()=>sN,WECHAT_VERSION:()=>OD,WQQB_VERSION:()=>VD,XWEB_VERSION:()=>bD,browserInfo:()=>AN,getBrowserInfo:()=>RN,getChromeMajorVersion:()=>aN,getDeviceModel:()=>DN,getOSName:()=>wN,getOSNumber:()=>ON,getOSString:()=>PN,getOSType:()=>LN,getTerminalType:()=>MN,getUserAgentData:()=>kN,isLocalStorageEnabled:()=>IN});var Xk="undefined"==typeof navigator?"":navigator.userAgent,$k=e=>new RegExp(e,"i").test(Xk),Zk=e=>{if($k(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=Xk.match(t);if(i&&i[1])return i[1]}return""},eD=e=>{if($k(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=Xk.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},tD=/AppleWebKit\/([\d.]+)/i.exec(Xk),iD=tD?parseFloat(tD[1]):NaN,rD=$k("iPad"),nD="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$k("Macintosh"),oD=$k("iPhone")&&!rD,sD=$k("iPod"),aD=oD||rD||sD||nD,cD=$k("Android"),lD=function(){if(cD){let e=Xk.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}(),dD=cD&&$k("webkit")&&lD<2.3,uD=cD&&lD<5&&iD<537,hD=$k("Firefox"),pD=Zk("Firefox"),mD=eD("Firefox"),_D=$k("Edge"),fD=Zk("Edge"),gD=$k("Edg"),TD=Zk("Edg"),ED=eD("Edg"),vD=$k("SogouMobileBrowser"),yD=Zk("SogouMobileBrowser"),SD=$k("MetaSr\\s"),ID=Zk("MetaSr\\s"),AD=$k("TBS"),RD=Zk("TBS"),CD=$k("XWEB"),bD=Zk("XWEB"),kD=$k("MSIE\\s8\\.0"),DD=$k("MSIE\\/\\d+"),ND=function(){if(DD){let e=/MSIE\s(\d+)\.\d/.exec(Xk),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(Xk)&&/rv:11.0/.test(Xk)&&(t=11),t}return NaN}(),wD=$k("(micromessenger|webbrowser)"),OD=Zk("MicroMessenger"),PD=!AD&&$k("MQQBrowser")&&$k("COVC"),MD=!AD&&$k("MQQBrowser")&&!$k("COVC"),LD=MD||PD?Zk("MQQBrowser"):"",xD=!AD&&$k(" QQBrowser"),VD=Zk(" QQBrowser"),UD=!AD&&$k("QQBrowserLite"),FD=Zk("QQBrowserLite"),BD=!AD&&$k("MQBHD"),HD=Zk("MQBHD"),jD=$k("Windows"),WD=!aD&&$k("MAC OS X"),GD=!cD&&$k("Linux"),JD=$k("CrOS"),zD=$k("MicroMessenger"),KD=$k("UCBrowser"),qD=$k("Electron"),YD=$k("MiuiBrowser"),QD=Zk("MiuiBrowser"),XD=$k("HuaweiBrowser"),$D=$k("Huawei")||$k("HUAWEI"),ZD=$k("Honor")||$k("HONOR"),eN=Zk("HuaweiBrowser"),tN=$k("SamsungBrowser"),iN=Zk("SamsungBrowser"),rN=$k("HeyTapBrowser"),nN=Zk("HeyTapBrowser"),oN=$k("VivoBrowser"),sN=Zk("VivoBrowser"),aN=()=>eD("Chrome"),cN=$k("Chrome"),lN=!_D&&!SD&&!vD&&!AD&&!CD&&!gD&&!xD&&!YD&&!XD&&!tN&&!rN&&!oN&&cN,dN=$k("HeadlessChrome"),uN=aN(),hN=Zk("Chrome"),pN=!cN&&!MD&&!PD&&!UD&&!BD&&$k("Safari"),mN=pN||aD,_N=Zk("Version"),fN=/Android.*(wv|.0.0.0)/.test(Xk),gN=(()=>{if(nD)return _N;if(aD){let e=Xk.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),TN=Number(gN.split(".")[0]),EN="15.1"===_N,vN="15.1"===gN,yN=(()=>{let e=Number(gN.split(".")[0]);return 14===e||13===e})(),SN="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),IN=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(mO){e=!1}return e}})(),AN=RN();function RN(){let e=new Map([[hD,["Firefox",pD]],[gD,["Edg",TD]],[lN,["Chrome",hN]],[pN,["Safari",_N]],[AD,["TBS",RD]],[CD,["XWEB",bD]],[wD&&oD,["WeChat",OD]],[xD,["QQ(Win)",VD]],[MD,["QQ(Mobile)",LD]],[PD,["QQ(Mobile X5)",LD]],[UD,["QQ(Mac)",FD]],[BD,["QQ(iPad)",HD]],[YD,["MI",QD]],[XD,["HW",eN]],[tN,["Samsung",iN]],[rN,["OPPO",nN]],[oN,["VIVO",sN]],[_D,["EDGE",fD]],[vD,["SogouMobile",yD]],[SD,["Sogou",ID]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var CN=null,bN="";function kN(){return jC(this,null,(function*(){if(CN)return CN;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(CN=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!bN&&(bN="UAData: ".concat(CN.platform,"/").concat(CN.platformVersion),CN.architecture&&CN.bitness&&(bN+=" ".concat(CN.architecture,"/").concat(CN.bitness)),CN.mobile&&(bN+=" mobile"),CN.model&&(bN+=" model: ".concat(CN.model)),CN.fullVersionList&&(bN+=" ".concat(CN.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),CN}catch(ux){return null}}))}function DN(){return(null==CN?void 0:CN.model)||""}var NN=new Map([[cD,"Android"],[aD,"iOS"],[jD,"Windows"],[WD,"MacOS"],[GD,"Linux"],[JD,"ChromeOS"]]),wN=function(){return NN.get(!0)?NN.get(!0):CN?CN.platform:"unknown"};function ON(){return jD?1:cD?2:WD?3:aD?4:GD?5:JD?6:0}var PN=()=>{let e=wN();return e+="/".concat(AN.name,"/").concat(pN?AN.version:AN.version.split(".")[0]),null!=CN&&CN.platformVersion&&(e+="/".concat(CN.platformVersion)),null!=CN&&CN.architecture&&(e+="/".concat(CN.architecture)),e};function MN(){return cD?4:oD?2:rD?3:WD?12:jD?5:GD?13:1}function LN(){return cD?"Android":oD?"iPhone":rD?"iPad":WD?"Mac":jD?"Windows":GD?"Linux":"unknown"}var xN=(e,t)=>t?"".concat(Ib,"/").concat(e,"/").concat(t):"".concat(Ib,"/").concat(e,"/index.html"),VN=()=>{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(bb);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 UN(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";Iw(Yk[t])?o=Yk[t](i):Rw(Yk[t])&&(o=Yk[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=VN();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(Iw(l[t])?a=l[t](i):Rw(l[t])&&(a=l[t]));let d=o;return Tw()&&(c&&c[t]&&(Iw(c[t])?s=c[t](i):Rw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(xN("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(xN("en",a),"\n")),d}var FN=Object.prototype.hasOwnProperty,BN=e=>"function"==typeof e,HN=e=>void 0===e;function jN(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(FN.call(e,t))return!1;return!0}return!1}var WN=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>jC(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,m=2,i(f)},s=()=>{2!==m&&h<(BN(d)?d():d)?(h++,m=1,BN(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),BN(u)?u(h):u)):(t(),BN(o)&&o.call(this,f))};BN(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},GN=new(UC(WC(),1).default),JN=(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.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e))(JN||{}),zN=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:lb,env:Db.QCLOUD,browserVersion:AN.name+AN.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){SN||!cO.isAbleToUpload||this._configs.env===Db.QCLOUD&&this.uploadEventToKibana(LC(MC({},e),{result:"success"}))}logFailedEvent(e){if(SN||!cO.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||eb.UNKNOWN};this._configs.env===Db.QCLOUD&&this.uploadEventToKibana(LC(MC({},o),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:ob(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:lb,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+="\n".concat(r.stack))),this.sendRequest(sw(this._configs.sdkAppId,kb.LOG),n)}sendRequest(e,t){cO.isAbleToUpload?Jk({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},KN=null,qN=!0;function YN(e){bw(e)&&e!==qN&&(qN=e,cO.info("setIsNeedToSchedule ".concat(e)))}function QN(e){return jC(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!qN&&KN)return{isCached:!0,result:KN};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(i)),d.append("isStrGroupId",String(r)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=Vw(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;xw([rw((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=1&&(a[0]=ZN(i,Fb.MAIN,!0)),n())}))(ZN(i,Fb.MAIN),e,{get timeout(){return 1e3*vw(2+t.count[0])}}),rw((e=>t.count[1]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=r.message,o||(s>=2&&(a[0]=ZN(i,Fb.BACKUP,!0)),n())}))(ZN(i,Fb.BACKUP),e,{get timeout(){return 1e3*vw(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Tb(h.config.loggerDomain),bw(h.config.scheduleCache)&&YN(!h.config.scheduleCache)),e.delta=Vw()-u;let p=function(e,t,i){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=ZN(e,Fb.MAIN),s=ZN(e,Fb.BACKUP);for(let e of n)if(e.startTime>=i&&(e.name===o||e.name===s)&&e.transferSize>0){let i=e.name===o?Fb.MAIN:Fb.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];zN.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(i),userId:t}),r=LC(MC({},r),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){cO.error("getScheduleDetailCost error",o)}return r}(Number(i),t,u);return KN=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=Dw(d)?d[0]:d,t=Cw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new ib({code:eb.SCHEDULE_FAILED,extraCode:t,message:UN({key:qk.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw cO.error(i,t),r}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(kk).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),GN.on("28",(()=>YN(!0))),GN.on("63",(()=>YN(!0))),GN.on("84",(()=>YN(!0))),GN.on("201",(e=>{"RECONNECTING"===e.state&&YN(!0)})),GN.on("202",(e=>{"RECONNECTING"===e.state&&YN(!0)}));var XN={main:"",backup:""};function $N(e){Dw(e)?(XN.main=e[0],XN.backup=e[1]):XN.main=e}function ZN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(XN[t]||tw(e,t,i),"/api/v1/config")}function ew(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN;return"https://".concat(XN[t]||tw(e,t),"/api/v1/trtcAutoConf")}function tw(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=ow(e)?r?i===Fb.MAIN?kk.MAIN_OVERSEA_BACKUP:kk.BACKUP_OVERSEA:i===Fb.MAIN?kk.MAIN_OVERSEA:kk.BACKUP_OVERSEA:i===Fb.MAIN?kk.MAIN:kk.BACKUP,t}function iw(e,t,i){return new Promise(((r,n)=>{Jk({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?r(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var rw=(e,t)=>WN({retryFunction:iw,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var nw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ow=e=>Number(e)<14e8,sw=function(e,t){let i;i=gb||(ow(e)?Cb:Rb);let r=Math.floor(Math.random()*OC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},aw="unknown";function cw(){if("unknown"!==aw)return aw;let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===n&&(n="2g"),r&&(aw=lw(r,n)),aw}function lw(e,t){if(Pb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function dw(e){aw=lw(e)}function uw(){return Pb[cw()]}function hw(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 pw(e){return mw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function mw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function _w(e){return 4*fw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function fw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var gw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},Tw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},Ew=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 vw(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:vw(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function yw(e){return e>8?3e4:1e3*vw(e)}function Sw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Iw=e=>"function"==typeof e,Aw=e=>void 0===e,Rw=e=>"string"==typeof e,Cw=e=>"number"==typeof e,bw=e=>"boolean"==typeof e,kw=e=>"object"===Sw(e),Dw=e=>"array"===Sw(e),Nw=e=>Sw(e)==="MediaStreamTrack".toLowerCase(),ww=e=>e.isRemote,Ow=e=>"promise"===Sw(e),Pw=e=>Iw(e)&&e.prototype.constructor===e,Mw=e=>Pw(e)?e.prototype.constructor.name:"",Lw="undefined"!=typeof AudioWorkletNode;function xw(e){return new Promise(((t,i)=>{let r=[];e.forEach((n=>{n.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function Vw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Uw=e=>+e<10?"0".concat(e):e,Fw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Uw(i[1])+Uw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},Bw=Object.prototype.hasOwnProperty;function Hw(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(Ew(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(Bw.call(e,t))return!1;return!0}return!1}function jw(e,t){return{userId:t,hasAudio:!!(e&zb),hasVideo:!!(e&Wb),hasAuxiliary:!!(e&Jb),hasSmall:!!(e&Gb),audioMuted:!!(e&Kb),videoMuted:!!(e&qb),audioAvailable:!(!(e&zb)||e&Kb),videoAvailable:!(!(e&Wb)||e&qb)}}function Ww(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!Aw(e.username)&&!Aw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",Aw(e.credentialType)||(t.credentialType=e.credentialType)),t}function Gw(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Rw(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 Jw=function(e,t,i,r){if(!kw(e)||!kw(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(Aw(t[n])||i&&i.includes(n)))if(kw(e[n])&&kw(t[n]))o+=Jw(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=zw(t[n]),o+=1)}return o};function zw(e){if(Dw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=zw(e)})),t}if(kw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=zw(e[i])})),t}return e}var Kw=e=>{let t=[];if(Dw(e))t=[...e];else if(Rw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},qw=e=>Rw(e)?document.getElementById(e):e,Yw=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function Qw(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Dw(e))return"[".concat(e.map((e=>Qw(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!Ew(e)||!Dw(i)&&!Dw(r))return JSON.stringify(e);let t={},n=new Set(i),o=new Set(r);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=Ew(e[s])||Dw(e[s])?JSON.parse(Qw(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(pk){return"{}"}}function Xw(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)})),Qw(e,{keysToInclude:i})}function $w(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Zw=()=>{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},eO=e=>jC(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(Rw(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 ib({code:eb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),tO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},iO=e=>(Object.keys(e).forEach((t=>{Cw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Ew(e[t])||Dw(e[t]))&&iO(e[t])})),e);function rO(e,t){return new Promise((i=>{let r=setTimeout(i,e);t&&t(r)}))}var nO=(e,t)=>{let i=null;return function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return i||(i=e.apply(t||this,n),i.finally((()=>i=null)),i)}},oO=class{constructor(e){BC(this,"userId"),BC(this,"remoteUserId"),BC(this,"id"),BC(this,"sdkAppId"),BC(this,"type"),BC(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof e.isLocal||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let i=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(i?"|".concat(i):"","]")),cO.log(e,t,HN(this.userId)||jN(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)}},sO=JN,aO=!(aD||cD||dN),cO=new class{constructor(){BC(this,"_isEnableUploadLog",!0),BC(this,"_localJoinedUser",new Map),BC(this,"_queue",[]),BC(this,"_timeoutId",-1),BC(this,"_logLevel",1),BC(this,"_logLevelToUpload",2),!mb&&!_b&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){GN.on(sO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&Nb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),GN.on(sO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),GN.once(sO.JOIN_FAILED,(()=>{this.startUpload()})),GN.on(sO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:r,sdkAppId:n}=t;e.map.has(r)?e.map.get(r).logs.push(i):e.map.set(r,{userId:r,sdkAppId:n,logs:[i]})}));else if(Rw(i.userId)&&Cw(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 jC(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:r,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ob(),sdkAppId:String(r),userId:i,version:lb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(hb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return WN({retryFunction:()=>Jk({url:sw(t,kb.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(nb());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(Nb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Aw(Nb[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(Rw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(ub){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;t.unshift(this.getPrefix(e));let s={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i};if(GN.emit(sO.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=Nb[e])?void 0:o.toLowerCase())||"info";aO?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new oO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Nb[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},lO=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)}))},dO=new class{constructor(){BC(this,"_prefix","TRTC"),BC(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){IN()&&(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(hb){return!1}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(IN())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(mO){cO.warn(mO)}}getItem(e){if(!IN())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(ub){cO.warn(ub)}}setItem(e,t){if(IN())try{let i={expiresIn:Date.now()+Mb,value:t};this._queue.set(this.getRealKey(e),i)}catch(pk){cO.warn(pk)}}deleteItem(e){if(!IN())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(ub){return cO.warn(ub),!1}}clear(){if(IN())try{localStorage.clear()}catch(mO){cO.warn(mO)}}},uO={};VC(uO,{HTTPS_API:()=>HO,IS_GET_CAPABILITIES_SUPPORTED:()=>sP,IS_GET_SETTINGS_SUPPORTED:()=>oP,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>nP,IS_INSERTABLE_STREAM_SUPPORTED:()=>aP,IS_RTC_RTP_SENDER_SUPPORTED:()=>tP,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>cP,IS_SEI_SUPPORTED:()=>lP,IS_SPC_SUPPORTED:()=>ZO,basis:()=>_P,checkSystemRequirementsInternal:()=>VO,decodeSupportStatus:()=>xO,encodeSupportStatus:()=>LO,getBrowserInfo:()=>kO,getDisplayResolution:()=>WO,isAddTransceiverSupported:()=>$O,isBrowserSupported:()=>DO,isGetReceiversSupported:()=>YO,isGetSendersSupported:()=>QO,isGetTransceiversSupported:()=>XO,isGetUserMediaSupported:()=>GO,isMediaDevicesSupported:()=>wO,isMediaSessionSupported:()=>hP,isMediaStreamTrackProcessorSupported:()=>MO,isReplaceTrackSupported:()=>iP,isRequestVideoFrameCallbackSupported:()=>gP,isSIMDSupported:()=>mP,isScreenCaptureApiAvailable:()=>FO,isSelectedCandidatePair:()=>jO,isSetParametersSupported:()=>rP,isSmallStreamAPISupported:()=>zO,isSmallStreamSupported:()=>KO,isStopTransceiverSupported:()=>eP,isTRTCSupported:()=>UO,isUnifiedPlanDefault:()=>qO,isUsedInHttpProtocol:()=>PO,isWebAudioSupported:()=>JO,isWebCodecSupported:()=>uP,isWebCodecsSupported:()=>NO,isWebRTCSupported:()=>dP,isWebTransportSupported:()=>pP});var hO,pO,mO,_O=UC(KC(),1),fO=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=cO.createLogger({id:"kv"}),e&&(GN.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===Fb.AUDIO?yO.START_MICROPHONE:SO.START_CAMERA,cost:i})})),GN.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===Fb.AUDIO?yO.START_MICROPHONE:SO.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:tO(this.version||lb),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,uint32_count:i}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,i]=e;return{uint32_key:t,distribution_items:[...i.entries()].map((e=>{let[t,i]=e;return{uint32_item_key:t,uint32_item_value:i}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(i,(o.get(i)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(Cw(r))a=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=eb.UNKNOWN;i&&(Cw(i)?r=i:(!Aw(i.extraCode)||!Aw(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},gO=((pO=gO||{})[pO.enterRoom=500700]="enterRoom",pO[pO.exitRoom=500701]="exitRoom",pO[pO.switchRole=500702]="switchRole",pO[pO.destroy=500703]="destroy",pO[pO.startLocalAudio=500704]="startLocalAudio",pO[pO.updateLocalAudio=500705]="updateLocalAudio",pO[pO.stopLocalAudio=500706]="stopLocalAudio",pO[pO.startLocalVideo=500707]="startLocalVideo",pO[pO.updateLocalVideo=500708]="updateLocalVideo",pO[pO.stopLocalVideo=500709]="stopLocalVideo",pO[pO.startScreenShare=500710]="startScreenShare",pO[pO.updateScreenShare=500711]="updateScreenShare",pO[pO.stopScreenShare=500712]="stopScreenShare",pO[pO.startRemoteVideo=500713]="startRemoteVideo",pO[pO.updateRemoteVideo=500714]="updateRemoteVideo",pO[pO.stopRemoteVideo=500715]="stopRemoteVideo",pO[pO.muteRemoteAudio=500716]="muteRemoteAudio",pO[pO.setRemoteAudioVolume=500717]="setRemoteAudioVolume",pO[pO.use=500718]="use",pO[pO.sendSEIMessage=5e5]="sendSEIMessage",pO[pO.sendCustomMessage=500001]="sendCustomMessage",pO),TO=((hO=TO||{})[hO.AudioMixer=550700]="AudioMixer",hO[hO.AIDenoiser=551700]="AIDenoiser",hO[hO.VirtualBackground=570700]="VirtualBackground",hO[hO.Beauty=571700]="Beauty",hO[hO.Watermark=572700]="Watermark",hO[hO.BasicBeauty=574700]="BasicBeauty",hO[hO.CDNStreaming=590700]="CDNStreaming",hO[hO.DeviceDetector=591700]="DeviceDetector",hO[hO.Debug=592700]="Debug",hO),EO=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e))(EO||{}),vO=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e))(vO||{}),yO=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(yO||{}),SO=((mO=SO||{})[mO.START_CAMERA=511700]="START_CAMERA",mO),IO=new fO(!0),AO=new fO(!1),RO=IO,CO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},bO=new Map([[hD,["Firefox",pD]],[gD,["Edg",TD]],[lN,["Chrome",hN]],[pN,["Safari",_N]],[AD,["TBS",RD]],[CD,["XWEB",bD]],[wD&&oD,["WeChat",OD]],[xD,["QQ(Win)",VD]],[MD,["QQ(Mobile)",LD]],[PD,["QQ(Mobile X5)",LD]],[UD,["QQ(Mac)",FD]],[BD,["QQ(iPad)",HD]],[YD,["MI",QD]],[XD,["HW",eN]],[tN,["Samsung",iN]],[rN,["OPPO",nN]],[oN,["VIVO",sN]],[_D,["EDGE",fD]],[vD,["SogouMobile",yD]],[SD,["Sogou",ID]]]);function kO(){let e=bO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var DO=function(){return!(KD||_D||gD&&ED<80||hD&&mD<56)},NO=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},wO=function(){if(!navigator.mediaDevices)return PO()||cO.error(Yk.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},OO=!1;function PO(){return"http:"===location.protocol&&!SN&&(OO||cO.error(UN({key:qk.NOT_SUPPORTED_HTTP})),OO=!0,!0)}var MO=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},LO=function(){return jC(this,null,(function*(){if(CO.detail.isH264EncodeSupported&&CO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:CO.detail.isH264EncodeSupported,isVp8EncodeSupported:CO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(Fb.CANVAS);n.getContext("2d");let o=n.captureStream(0);return r.addTrack(o.getVideoTracks()[0],o),e=yield r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),CO.detail.isH264EncodeSupported=t,CO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:CO.detail.isH264EncodeSupported,isVp8EncodeSupported:CO.detail.isVp8EncodeSupported}}catch(pk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},xO=function(){return jC(this,null,(function*(){if(CO.detail.isH264DecodeSupported&&CO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:CO.detail.isH264DecodeSupported,isVp8DecodeSupported:CO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection;return e=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(pk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},VO=nO((()=>jC(void 0,null,(function*(){if(CO.result&&CO.detail.isH264EncodeSupported&&CO.detail.isVp8EncodeSupported&&CO.detail.isH264DecodeSupported&&CO.detail.isVp8DecodeSupported)return CO;let e=Date.now(),t=DO(),i=dP(),r=NO(),n=wO(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield LO(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield xO();if(!o||!s){let e=yield LO();cO.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&(rN||oN||fN)&&!AD&&aN()<79){let{encode:e,decode:t}=yield function(){return jC(this,null,(function*(){return BO||(BO=new Promise((e=>jC(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{cO.warn("detectH264Supported start");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=320,r.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),2e3);let c=r.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=_O.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=_O.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>jC(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getSenders()[0].getStats(),n=yield d.getReceivers()[0].getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===Fb.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===Fb.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(r){i(),cO.warn(r),e(t)}})))).then((e=>((!e.encode||!e.decode)&&cO.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(bN)),e))),BO)}))}();o=e,a=t}return CO.result=t&&i&&n&&(o||s)&&(a||c),CO.detail.isBrowserSupported=t,CO.detail.isWebRTCSupported=i,CO.detail.isWebCodecsSupported=r,CO.detail.isMediaDevicesSupported=n,CO.detail.isScreenShareSupported=FO(),CO.detail.isSmallStreamSupported=KO(),CO.detail.isH264EncodeSupported=o,CO.detail.isVp8EncodeSupported=s,CO.detail.isH264DecodeSupported=a,CO.detail.isVp8DecodeSupported=c,CO.result||cO.error("".concat(navigator.userAgent," ").concat(Xw(CO.detail,!1))),dO.setItem(fP,{ua:navigator.userAgent,checkResult:CO}),RO.addNumber({key:523800,value:Date.now()-e}),CO})))),UO=function(){return CO.result},FO=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},BO=null;var HO=(e,t,i)=>{"http:"===location.protocol&&!SN&&(e[t]=()=>{throw new ib({code:eb.INVALID_OPERATION,message:Yk.NOT_SUPPORTED_HTTP})})},jO=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(bw(e.selected)&&!e.selected)};function WO(){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 GO(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function JO(){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 zO(){return"captureStream"in HTMLCanvasElement.prototype}function KO(){return!(wD||aD||uN&&uN<63)&&!(!DO()||!zO())}var qO=function(){if(Aw(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Ek}),e.addTransceiver(Fb.AUDIO),t=!0}catch(ub){}return null==e||e.close(),t};function YO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function QO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function XO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function $O(){return 11!==TN&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var ZO=!(!$O()||cN&&uN<86);function eP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var tP="RTCRtpSender"in window;function iP(){return tP&&"replaceTrack"in window.RTCRtpSender.prototype}function rP(){return tP&&"setParameters"in window.RTCRtpSender.prototype&&QO()}var nP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,oP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,sP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,aP=tP&&"createEncodedStreams"in window.RTCRtpSender.prototype&&aN()>=86,cP="RTCRtpScriptTransform"in window,lP=tP&&(aP||cP),dP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function uP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Aw(window.AudioDecoder)||(e.AudioDecoder=!0),Aw(window.AudioEncoder)||(e.AudioEncoder=!0),Aw(window.VideoDecoder)||(e.VideoDecoder=!0),Aw(window.VideoEncoder)||(e.VideoEncoder=!0),Aw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function hP(){return"mediaSession"in navigator&&!Aw(navigator.mediaSession.setActionHandler)}function pP(){return!Aw(window.WebTransport)}function mP(){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 _P(){let e={browser:"".concat(AN.name,"/").concat(AN.version),os:wN(),displayResolution:WO(),isScreenShareSupported:FO(),isWebRTCSupported:dP(),isGetUserMediaSupported:GO(),isWebAudioSupported:JO(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:uP(),isMediaSessionSupported:hP(),isWebTransportSupported:pP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var fP="checkResult";function gP(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}!function(){PO();let e=dO.getItem(fP);e&&e.ua===navigator.userAgent&&(CO=e.checkResult),VO()}();var TP=UC(WC(),1),EP=Symbol("instance"),vP=Symbol("cacheResult"),yP=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,CP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},SP=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var IP=new Map;function AP(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=IP.get(r)||[];IP.has(r)||IP.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=bP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[vP]:Promise.resolve(r[vP]);r.state instanceof yP&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof yP&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new SP(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e.join("|")))):e!==r.state&&(l=new SP(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=r.state,h=new yP(u,t,s);CP.call(r,h);let p=e=>{var n;return r[vP]=e,h.aborted||(CP.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[vP])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return CP.call(r,u,e),d(new SP(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var RP="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 CP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(bP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var bP=class extends TP.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=bP.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[EP];r?this.name=r.name+"-"+r.count++:i[EP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=IP.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);IP.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=bP.instances.get(e),t||bP.instances.set(e,t=new bP(e,void 0,Object.create(bP.prototype)))):(t=bP.instances2.get(e),t||bP.instances2.set(e,t=new bP(e.constructor.name,void 0,Object.create(bP.prototype)))),t}static getState(e){var t;return null===(t=bP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};RP(bP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){CP.call(this,e)}};bP.STATECHANGED="stateChanged",bP.UPDATEAFSM="updateAFSM",bP.INIT="[*]",bP.ON="on",bP.OFF="off",bP.instances=new Map,bP.instances2=new WeakMap;var kP=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},DP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},NP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),wP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:jk,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=MC(e===Hk?{delay:2e3,count:0,backgroundTask:!0}:e===Fk?{delay:1e4,count:0}:e===Bk?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),kw(t)&&(i=MC(MC({},i),t)),Iw(e)&&(t=e,e=jk);let r=MC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")],{type:"application/javascript"})));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=Vw(),r=()=>{if(t=Vw()-i,t>=e.delay&&(i=Vw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=kP(r,{timeout:e.delay})};return e.ricID=kP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=Vw(),r=()=>document.hidden&&e.backgroundTask?(t=Vw()-i,i=Vw(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=Vw()-i,t>=e.delay&&(i=Vw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(r));if(e.rafID=requestAnimationFrame(r),e.backgroundTask){let t=()=>{if(document.hidden){let t=Vw()-i;t>=e.delay?r():e.timeoutID=setTimeout(r,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:r,ricID:n,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),r&&NP(r),n&&DP(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};wP.taskMap=new Map,wP.currentTaskID=1;var OP=wP;Fb.SEI_MESSAGE;var PP={LOADED_DATA:Fb.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},MP={};VC(MP,{create:()=>xP,remove:()=>VP});var LP=new WeakMap;function xP(e,t){LP.has(e)||LP.set(e,[]);let i=LP.get(e),r={add:(e,n)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,n)),t.addEventListener(e,n)):(i.push(t.off.bind(t,e,n)),t.on(e,n)),r)};return r}function VP(e){let t=LP.get(e);t&&(t.forEach((e=>e())),LP.delete(e))}var UP=new WeakMap;function FP(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=WN({retryFunction:s.value,settings:t,onError(t){let{error:r,retry:n,reject:s,retryFuncArgs:a}=t;var c;i?i.call(this,r,(()=>{var t;null!=(t=UP.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=UP.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;BN(r)&&r.call(this,t,i),null!=(n=UP.get(e))&&n.has(o)&&(UP.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=UP.get(e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return t?t.set(o,{args:r}):UP.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=UP.get(e))?void 0:t.delete(o)}))},s}}function BP(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=UP.get(e))&&n.has(t)){let{stopRetry:n,args:s}=UP.get(e).get(t),a=!0;if(r)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),n&&n(),null==(o=UP.get(e))||o.delete(t))}return s.apply(this,c)},o}}var HP=class extends bP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,BC(this,"id"),BC(this,"element",null),BC(this,"track"),BC(this,"url"),BC(this,"attr"),BC(this,"muted"),BC(this,"_log"),BC(this,"_pausedRetryCount"),BC(this,"_isElementPlayingFired",!1),BC(this,"_interval"),BC(this,"_delayDestroyTimeoutId",0),BC(this,"_isReplayByRecreateMediaStreamCalled",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=wk,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 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 jC(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(ub){let t=UN({key:qk.PLAY_FAILED,data:{media:this.kind,error:ub}});if(this.track&&!this.track.muted&&this._log.warn(ub),t.includes("NotAllowedError"))throw new ib({code:eb.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(Fb.ENDED),this._interval>0&&OP.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():vN?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 xP(this.element,this.element).add(Fb.PLAYING,e).add(Fb.ENDED,e).add(Fb.PAUSE,e).add(Fb.ERROR,e).add(Fb.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==MP||MP.create(this.track,this.track).add(Fb.ENDED,e).add(Fb.MUTE,e).add(Fb.UNMUTE,e),this.track.readyState===Fb.ENDED&&this.handleTrackEvent({type:Fb.ENDED}),this.track.muted&&this.handleTrackEvent({type:Fb.MUTE})}}bindAutoPlayEvent(){GN.on(sO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&VP(this.track)}unbindEvents(){this.element&&VP(this.element),this.unbindTrackEvents(),GN.off(sO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case Fb.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(Fb.PLAYING),this._interval&&(OP.clearTask(this._interval),this._interval=-1);break;case Fb.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(Fb.ENDED);break;case Fb.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(Fb.PAUSE),aD&&(this._interval=OP.run(jk,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case Fb.ERROR:if(this.element&&this.element.error){this.handlePaused(Fb.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)),zN.uploadEvent({log:"stat-".concat(this.kind,"-").concat(_k.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),ZD||$D?this.emit(PP.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case Fb.LOADEDDATA:this.kind===Fb.VIDEO&&this.emit(PP.LOADED_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),zN.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),RO.addSuccessEvent({key:this.kind===Fb.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),zN.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),RO.addFailedEvent({key:this.kind===Fb.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(PP.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,i)=>{rO(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)}),rO(5e3).then((()=>{var e,r;(!this.isPlaying||(null==(e=this.element)?void 0:e.error))&&i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case Fb.ENDED:this.handleStopped(Fb.ENDED);break;case Fb.MUTE:this.handlePaused(Fb.MUTE);break;case Fb.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(Fb.UNMUTE)}}handlePlaying(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(PP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};FC([FP({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],HP.prototype,"doReplayByRecreateMediaStream",1),FC([AP([],"PLAYING",{sync:!0})],HP.prototype,"handlePlaying",1),FC([AP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],HP.prototype,"handlePaused",1),FC([AP([],"STOPPED",{sync:!0})],HP.prototype,"handleStopped",1);var jP,WP="trtc_autoplay",GP="".concat(WP,"_mask"),JP="".concat(WP,"_wrapper"),zP="".concat(WP,"_header"),KP="".concat(WP,"_content"),qP="".concat(WP,"_action_wrapper"),YP="".concat(WP,"_question"),QP="".concat(WP,"_collapse"),XP="".concat(WP,"_action_confirm"),$P="".concat(WP,"_detail"),ZP="#2473E8",eM="dialog",tM="".concat(eM,"-show"),iM="".concat(eM,"-1"),rM="".concat(eM,"-2"),nM=!1,oM=()=>!!document.querySelector(".".concat(JP)),sM="".concat(Ib,"/").concat(Tw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),aM="<br><a href='".concat(sM,"' target='_blank'>").concat(Tw()?"其他方案?":"Any other solution?","</a>"),cM="".concat(Tw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(aM):"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(aM)),lM=class{constructor(){if(BC(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),BC(this,"_dialogNode",null),BC(this,"_bodyPosition",""),BC(this,"_showDetail",!1),BC(this,"_isCollapseClicked",!1),BC(this,"_isQuestionClicked",!1),Tw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!nM){let e=document.createElement("style");e.innerHTML=".".concat(GP,"{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(GP," div:not(.").concat(qP,"){display:block !important;}.").concat(JP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(JP," a{color:").concat(ZP,";}.").concat(zP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(KP,"{margin:8px 0;}.").concat(qP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(QP,"{margin-right:auto;cursor:pointer}.").concat(YP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(XP,"{margin-left:8px;color:#fff;background:").concat(ZP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(XP,":hover{opacity:0.9;}.").concat(QP,",.").concat(XP,",.").concat(KP,",.").concat(YP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(JP,"{width:80vw;}}"),document.head.appendChild(e),nM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(GP,"\"><div class='").concat(JP,"'><div class='").concat(zP,"'>").concat(location.host,"</div><div class='").concat(KP,"'>").concat(this.content,"</div><div class='").concat($P,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(cM,"</div><div class='").concat(qP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=XP,t.innerText=Tw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=YP,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=QP,r.innerText="".concat(Tw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(qP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){oM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(JP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",cO.info("show autoplay dialog"),zN.uploadEvent({log:tM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){cO.warn("confirm clicked, try resume stream"),GN.emit(sO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat($P));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||zN.uploadEvent({log:iM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(sM,"_blank"),this._isQuestionClicked||zN.uploadEvent({log:rM}),this._isQuestionClicked=!0}},dM=class extends HP{constructor(e){super(e,Fb.VIDEO),BC(this,"stat",{}),BC(this,"_calculateTimeout",-1),BC(this,"viewMirror",!1),BC(this,"objectFit"),BC(this,"container"),BC(this,"canvas"),this.container=e.container,this.canvas=e.canvas,Aw(e.viewMirror)||(this.viewMirror=e.viewMirror),Aw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(Fb.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(Fb.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(Fb.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){super.handleTrackEvent(e),e.type===Fb.MUTE&&this.stat.fps&&(this.stat.fps=0)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===Fb.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this._pausedRetryCount>0&&!oM()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;i===Fb.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===Fb.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&(null==(i=this.container)||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(PP.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(gP()&&this.element&&this._calculateTimeout<0){let e=0,t=null,i=(r,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(i)}),2e3))};this.element.requestVideoFrameCallback(i)}}catch(ub){this._log.warn("init stat failed",ub)}}};function uM(e,t){return jC(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),cO.info("worklet addModule success")}catch(ub){throw cO.info("worklet addModule catch error. ".concat(ub.message)),ub}}))}"undefined"!=typeof AudioContext?jP=AudioContext:"undefined"!=typeof webkitAudioContext?jP=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(jP=mozAudioContext);var hM,pM=-1;!function e(){try{if(hM)return;(hM=new jP({sampleRate:48e3})).onstatechange=()=>{cO.info("context state: ".concat(hM.state)),mM()},clearTimeout(pM)}catch(ux){cO.error("initAudioContext failed: ".concat(ux," typeof AudioContextClass: ").concat(typeof jP)),pM=setTimeout(e,1e3)}}();var mM=()=>{"suspended"===hM.state?(hM.resume(),document.addEventListener("click",mM)):"interrupted"===hM.state?hM.resume().catch((e=>{cO.warn("resume failed: ".concat(e)),document.addEventListener("visibilitychange",mM)})):(document.removeEventListener("visibilitychange",mM),document.removeEventListener("click",mM))};document.addEventListener("click",mM);var _M=e=>hM,fM=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set,this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.node&&(this.node.channelCount=e),this.next.forEach((t=>t.channelCount=e))}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),RO.addSuccessEvent({key:502701})}catch(pk){cO.error(pk),RO.addFailedEvent({key:502701,error:pk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),RO.addSuccessEvent({key:502702})}catch(ub){cO.error(ub),RO.addFailedEvent({key:502702,error:ub})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},gM=class extends fM{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},TM=class{constructor(){this.source=new fM,this.gain=new fM,this.destination=new fM}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(SM(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},EM=class extends TM{constructor(e){super(),this.context=e,this.denoiser=new fM,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}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()}},vM=class{constructor(){this.audioContext=_M(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0}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]}},yM=new WeakMap;function SM(e){let t=yM.get(e);if(t)return t;let i=_M();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return yM.set(e,t),t}var IM=class{constructor(e){this._volume=0,this._scriptProcessorNode=null,this._audioWorkletNode=null,this._interval=200,this.ready=this.preload();let{log:t}=e;this._log=t,GN.on(sO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-IM.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!IM.workletReady){let e='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,e){t=t[0],e=e[0];if(t||e){if(this.isStop)return!1;var s=e?e[0].length:0,i=this.cache.length,h=(s<i?(e[0].set(this.cache.slice(0,s)),this.cache=this.cache.slice(s)):this.unmute&&e[0].set(t[0]),(s<i?e:t)[0]);if(h){let e=0;for(let t=0;t<h.length;++t)e=Math.max(Math.abs(h[t]),e);this.volume=e,this.tick-=h.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:i,outputLen:s}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';IM.workletReady=uM(IM.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return IM.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(IM.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{IM.lastMessageTime=Date.now(),this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(mO){this._log.error("volumeMeter init audio worklet error: ".concat(mO)),zN.logFailedEvent({userId:this._log.userId,eventType:_k.LOAD_WORKLET,error:mO}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=_M("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{IM.lastMessageTime=Date.now();let t=e.inputBuffer.getChannelData(0),i=0;for(let r=0;r<t.length;++r)i+=t[r]*t[r];this._volume=Math.sqrt(i/t.length)||0}}catch(mO){this._log.error("volumeMeter init script processor error: ".concat(mO))}}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,GN.off(sO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}},AM=IM;AM.lastMessageTime=0,AM.audioContext=_M();var RM=class extends fM{constructor(e){super(),this._volumeMeter=new AM(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return jC(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}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()}}},CM=AM,bM=UC(WC(),1),kM=e=>t=>t.deviceId===e,DM=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";BC(this,"kind"),BC(this,"type"),BC(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&&OM(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(kM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");cO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(kM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");cO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},NM=class extends bM.EventEmitter{constructor(){super(),BC(this,"audioInputs",new DM(Fb.AUDIO)),BC(this,"videoInputs",new DM(Fb.VIDEO)),BC(this,"audioOutputs",new DM(Fb.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||OP.run(Hk,(()=>{this.update()}),{delay:1e4}))}init(){PM().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield PM(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},wM=_b||mb?null:new NM;function OM(e){return e.deviceId===e.groupId&&""===e.groupId}function PM(){return jC(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(PO()||!wO())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{OM(e)&&(e.kind===Fb.AUDIO_INPUT?i.audio=!0:e.kind===Fb.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(i)}catch(hb){cO.debug("capture before getDevices failed: ",hb)}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&&UM.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function MM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return wM.update(e?1:0).then((e=>e.audioInputs.devices))}function LM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return wM.update(e?2:0).then((e=>e.videoInputs.devices))}var xM=!1;function VM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return jC(this,null,(function*(){return wM.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var UM=new Set;function FM(e,t){return jC(this,null,(function*(){let i=(yield MM()).find((e=>e.deviceId===Ok));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}))}var BM,HM=class extends TM{constructor(e){super(),this.log=e,BC(this,"volumeMeter"),BC(this,"volumeDestination"),BC(this,"analyser",new gM),this.volumeMeter=new RM({log:this.log}),this.volumeDestination=new fM,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},jM=class extends HP{constructor(e){super(e,Fb.AUDIO),BC(this,"_outputDeviceId"),BC(this,"_volume",1),BC(this,"_destination",_M().createMediaStreamDestination()),BC(this,"pipeline"),BC(this,"volumeMeterMode","worklet"),this.pipeline=new HM(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===gN||"15.3"===gN||"15.4"===gN)&&this.muted)return void this._log.info("audioElement is muted.");let t=BM||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,Cw(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===BM&&(BM=void 0),this.bindElementEvents()}play(e){return jC(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==e?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(_M().createAnalyser()),function(){jC(this,null,(function*(){try{xM||(xM=!0,cO.info("speakers:".concat((yield VM()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(ux){}}))}(),HC(jM.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return jC(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()}},WM=class extends jM{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(PP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.source.channelCount=(null==(t=e.getSettings())?void 0:t.channelCount)||1,this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},GM=class extends jM{constructor(e){super(e),BC(this,"_sourceElement"),BC(this,"_output",new fM),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(_M().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(PP.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){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),VP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&mN&&(BM=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},JM=class extends bP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?GM:dM)}=e;var s;super(),BC(this,"id",lO()),BC(this,"userId",""),BC(this,"isRemote"),BC(this,"mediaType"),BC(this,"room"),BC(this,"user"),BC(this,"_log"),BC(this,"_inputTrack"),BC(this,"_outputTrack"),BC(this,"isPlayCalled"),BC(this,"container",null),BC(this,"player"),BC(this,"subVideoPlayerMap"),BC(this,"muted",!1),BC(this,"abortCtrl"),BC(this,"objectFit","cover"),BC(this,"mirror"),BC(this,"isScreen",!1),BC(this,"manager"),BC(this,"trackSettings"),this.userId=t||"",this.mediaType=r,this._log=cO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof hL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof hL}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(PP.PLAYER_STATE_CHANGED,(e=>{GN.emit(sO.PLAYER_STATE_CHANGED,MC({track:this},e)),this.emit("player-state-changed",e)})),this.kind===Fb.VIDEO&&(this.player.on(PP.LOADED_DATA,(()=>{GN.emit(sO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(PP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(PP.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||cO}get kind(){return 1===this.mediaType?Fb.AUDIO:Fb.VIDEO}get strMediaType(){return 4===this.mediaType?Fb.VIDEO:2===this.mediaType?Fb.SCREEN:Fb.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 jC(this,null,(function*(){let i=Dw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!Aw(t.muted)&&this.setPlayerMute(t.muted),t&&!Aw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof dM&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Dw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!Aw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===Fb.VIDEO)&&this.setPlayerMute(!0),t&&!Aw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof dM&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof dM&&this.player.setContainer(i)),GN.emit(sO.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),Dw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(),this.emit("error",r),r}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==Fb.VIDEO||Aw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(bw(this.mirror))return i.setViewMirror(this.mirror),void(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 jC(this,null,(function*(){if(!this._outputTrack||this.kind===Fb.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(let[r,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(Aw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new dM({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ww(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return jC(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),GN.emit(e?sO.TRACK_MUTED:sO.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){xP(e,e).add(Fb.MUTE,this.onTrackMuted).add(Fb.UNMUTE,this.onTrackUnmuted).add(Fb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Fb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){VP(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(ww(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(){if(this.room&&this.room.enableAutoPlayDialog)new lM;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof dM?this.player.getVideoFrame():""}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"))}};FC([AP([],bP.INIT,{sync:!0})],JM.prototype,"close",1);var zM=Object.prototype.hasOwnProperty;var KM=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(Ew(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(zM.call(e,t))return!1;return!0}return!1},qM=WN({retryFunction:function(e){return jC(this,null,(function*(){let t=function(e){return{audio:QM(e),video:XM(e)}}(e);cO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield MM(),cO.info("microphones: ".concat(Qw(i,{keysToInclude:n})))),t.video&&(r=yield LM(),cO.info("cameras: ".concat(Qw(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return sP&&e.getTracks().forEach((e=>{cO.info("".concat(e.kind," capabilities: ").concat(Qw(e.getCapabilities(),{keysToInclude:Wk})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&r&&0===r.length&&(t=UN({key:qk.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(t=UN({key:qk.MICROPHONE_NOT_FOUND}))),new ib({code:eb.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!pN||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&YM(n[0].microphoneId,!1),n[0].cameraId&&YM(n[0].cameraId,!0)},onRetrying:e=>{cO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{zN.logFailedEvent({eventType:_k.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{zN.logSuccessEvent({eventType:_k.GET_USER_MEDIA_RETRY}),zN.uploadEvent({log:"stat-".concat(_k.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function YM(e,t){return jC(this,null,(function*(){let i=(t?yield LM():yield MM()).find((t=>t.deviceId===e));i&&Iw(i.getCapabilities)&&cO.warn(Qw(i.getCapabilities(),{keysToInclude:Wk}))}))}function QM(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!KM(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(Cw(e.channelCount)&&(t.channelCount=e.channelCount),bw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),bw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),bw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!KM(t)||t)}function XM(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&&!KM(i)?i:(e.width&&(i.width={ideal:e.width},t&&!hD&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!hD&&(i.height.max=e.height)),hD&&WD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!KM(i)||i)}var $M=qM;function ZM(e){return tL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function eL(e){return tL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function tL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var iL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&cO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{cO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),rL=0,nL=class{constructor(){this.log=cO.createLogger({id:"fq".concat(++rL)}),this.isRunning=!1,this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i,r;let n=MC({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:i,resolve:r,reject:n}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},oL=new WeakMap,sL=new WeakMap;function aL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let t=oL.get(this)||new nL;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return oL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function cL(e){return function(t,i,r){let n=r.value;return r.value=function(){var t,i,r;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(i=null==(t=oL.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=sL.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new ib({code:eb.API_CALL_ABORTED,message:e}))})),oL.delete(this),sL.delete(this),n.apply(this,a)},r}}function lL(e){return function(t,i,r){let n=r.value,o=t=>e(...t);return r.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=sL.get(this)||new Map,s=r.get(o(t))||new nL;return r.set(o(t),s),sL.set(this,r),s.push({fn:n,args:t,context:this})},r}}function dL(e,t){return tL(((i,r)=>function(){let r=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=i.apply(this,o),a=Vw();return Ow(e)?e.then((e=>(t?RO.addSuccessEvent({key:r,cost:Vw()-a}):RO.addSuccessEvent({key:r}),e))).catch((e=>{throw RO.addFailedEvent({key:r,error:e}),e})):(RO.addSuccessEvent({key:r}),e)}catch(pb){throw RO.addFailedEvent({key:r,error:pb}),pb}}))}var uL=class extends JM{constructor(e,t){super({mediaType:e,PlayerClass:t}),BC(this,"isRemote",!1),BC(this,"deviceId"),BC(this,"groupId",""),BC(this,"label",""),BC(this,"_isRecapturing",!1),BC(this,"_lastRecaptureTime",0),BC(this,"_onMuteTimeoutId",-1),BC(this,"_encodeCheckTimeoutId",-1),BC(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){xP(e,e).add(Fb.MUTE,this.onTrackMuted).add(Fb.UNMUTE,this.onTrackUnmuted).add(Fb.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===Fb.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){VP(e)}setStateToCapture(){}capture(e){return jC(this,null,(function*(){var t;try{let i,r=Vw();GN.emit(sO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield $M(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),GN.emit(sO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Vw()-r}),i}catch(hb){throw GN.emit(sO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:hb}),this.log.error("getUserMedia error observed ".concat(hb)),hb}}))}setInputMediaStreamTrack(e){return this.state===bP.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),GN.emit(sO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return jC(this,null,(function*(){if(this.mediaTrack&&oP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return jC(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==Fb.AUDIO||t!==Ok||(yield FM(r,n)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),PM().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===Fb.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(Fb.AUDIO_INPUT);return!!UM.has(i)}(this.mediaTrack)||this.kind===Fb.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(Fb.VIDEO_INPUT);return!!UM.has(i)}(this.mediaTrack)||this._isRecapturing||e&&WD&&pN)}onTrackMuted(){if(super.onTrackMuted(),iL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Uk)return void setTimeout((()=>this.onTrackMuted()),Uk);this._onMuteTimeoutId=setTimeout((()=>jC(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((aD||cD)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return jC(this,null,(function*(){if(HC(uL.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Uk)return void setTimeout((()=>this.onTrackEnded()),Uk);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return jC(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield MM():yield LM()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),GN.emit(sO.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),GN.emit(sO.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return jC(this,null,(function*(){let e=this instanceof gL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(pL.get(t)||0)+1;if(pL.set(t,i),i>=3){let r=e?(yield LM()).find((e=>!pL.has(e.deviceId))):(yield MM()).find((e=>!pL.has(e.deviceId)));r&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(r.deviceId)),t=r.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}},hL=uL;FC([AP(bP.INIT,"capture",{ignoreError:!0,sync:!0})],hL.prototype,"setStateToCapture",1),FC([aL()],hL.prototype,"capture",1),FC([AP("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),GN.emit(sO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===Fb.AUDIO,t=this.stat.bytesSent>0;RO[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(RO.addEnum({key:e?503701:513703,value:ON()}),zN.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(DN()||PN()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===eb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}}),dL(521714,!1)],hL.prototype,"publish",1),FC([tL((e=>function(){return jC(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)}))})),AP([],"capture",{sync:!0})],hL.prototype,"unpublish",1);var pL=new Map;GN.on(sO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&pL.delete(e.track.deviceId)}));var mL=class extends hL{constructor(e){super(1,WM),BC(this,"mediaType",1),BC(this,"volume",0),BC(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),BC(this,"playerMuted",!0),BC(this,"pipeline"),BC(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new EM(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return jC(this,null,(function*(){let t=this.trackSettings||{};RO.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),RO.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),RO.addEnum({key:502700,value:0});let{sampleRate:i,channelCount:r}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:i,channelCount:r}))),this.pipeline.source.channelCount=r||1,this.pipeline.replaceSource(e),yield HC(mL.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:n,customSource:i})}switchDevice(e){return jC(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Ok)return;if(yield FM(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),GN.emit(sO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(pk){throw this.log.error("switch microphone failed ".concat(pk)),this.deviceId&&this.recapture(this.deviceId),pk}}}))}listenDeviceChange(){wM&&!wM.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&wM.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return jC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),wx(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield MM();t[0]?this.recapture(t[0].deviceId):wM.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return jC(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!Aw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!Aw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!Aw(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&RO.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){var t;uN<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(RO.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),wM.off("audioInputAdded",this.handleMicrophoneAdded,this),wM.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return jC(this,null,(function*(){try{yield HC(mL.prototype,this,"recapture").call(this,e)}catch(pk){let i=(yield MM()).find((t=>t.deviceId!==e));if(!i)throw pk;yield HC(mL.prototype,this,"recapture").call(this,i.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},_L=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],r=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],r=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:r++,i.push(this.dataView.getInt8(o));break;case 3:2!==r&&i.push(this.dataView.getInt8(o)),r=0;break;default:i.push(this.dataView.getInt8(o)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let i=this.dataView.getUint8(n);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i);for(let n=0;n<i.byteLength;n++,t++)r.setInt8(n,this.dataView.getInt8(t));return r}},fL=class{constructor(){BC(this,"_seiMessageList",[]),BC(this,"_smallSeiMessageList",[]),BC(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)n.push(255);n.push(r);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new _L(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let r=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=r.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)s.setInt8(c++,r[e].dataView.getInt8(t));for(let i=0;i<e.data.byteLength;i++)s.setInt8(c++,a.getInt8(i));return e.data=o,r.length}return 0}},gL=class extends hL{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,dM),BC(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),BC(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),BC(this,"small"),BC(this,"isNeedToSetBandwidth"),BC(this,"muteImage"),BC(this,"manager"),BC(this,"_seiCodec",new fL),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(LC(MC({},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(oP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return jC(this,null,(function*(){var t,i,r;if(Rw(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.deleteWatermark("mute"),yield null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,HC(gL.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,HC(gL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=MC({},e),i=t.width>t.height;t.width*t.height<=19200&&cD&&cN&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=i?240:180,t.height=i?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&yN&&(t.width=i?1280:720,t.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(LC(MC({},this.profile),{width:1920,height:1080})))}applyProfile(){return jC(this,null,(function*(){var e;if(!this.mediaTrack)return;let t=this.settings;return(t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===TN?yield this.recapture(this.deviceId):(yield null==(e=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,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:Fb.VIDEO,videoType:Fb.BIG})):void 0}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return oP&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Zw()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return jC(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),GN.emit(sO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(pk){throw this.log.error("switch camera failed ".concat(pk)),this.deviceId&&this.recapture(this.deviceId),pk}}))}listenDeviceChange(){wM&&!wM.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&wM.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return jC(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),wx(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield LM();t[0]?this.recapture(t[0].deviceId):wM.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return jC(this,null,(function*(){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.reduce(((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 jC(this,null,(function*(){return Aw(this.mirror)&&!this.isScreen&&this.setMirror("view"),HC(gL.prototype,this,"play").call(this,e,t)}))}close(){wM.off("videoInputAdded",this.handleCameraAdded,this),wM.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return jC(this,null,(function*(){try{yield HC(gL.prototype,this,"recapture").call(this,e)}catch(pk){let i=(yield LM()).find((t=>t.deviceId!==e));if(!i)throw pk;yield HC(gL.prototype,this,"recapture").call(this,i.deviceId)}}))}},TL=lO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:TL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(ux){}var EL,vL=function(e){return jC(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:pN?{max:e.width}:{ideal:e.width,max:e.width},height:pN?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:r=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:n,sampleRate:48e3}}return t}(e);cO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(lN&&uN<74||pN||hD)&&cO.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){cO.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return jC(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&Iw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==TL)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){cO.warn("cropTo target failed ".concat(r))}}))}(n,e.captureElement))}if(e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return Aw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);cO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},yL=class extends gL{constructor(e){super(e,2),BC(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),BC(this,"objectFit","contain"),BC(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return jC(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield vL({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof ib?e:new ib({code:eb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return jC(this,null,(function*(){throw new Error("Method not implemented.")}))}},SL=class extends mL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},IL="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});";function AL(e){return jC(this,null,(function*(){let t=_M();EL||(EL=uM(t,URL.createObjectURL(new Blob([IL],{type:"application/javascript"})))),yield EL;let i=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(i,0,t))),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(i))),i.port.close()}})}))}var RL=class extends vM{constructor(e){super(),this.room=e,BC(this,"_localAudioTrack"),BC(this,"_localScreenAudioTrack"),BC(this,"log",cO.createLogger({id:"am"})),BC(this,"denoiser"),BC(this,"mixChangedDebounce"),BC(this,"encodePipeline",[]),BC(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),null!=(i=this._localAudioPipline)&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),i=document.createElement("a");i.href=t,i.download="".concat(n[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(a),o.abort("download")},l=AL(r).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(Aw(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");this.log.warn("getPCM");let i=new Float32Array(1920),r=0,n=new AbortController;return AL([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){!t[0][0]||(i.set(t[0][0],r),r+=t[0][0].length,r>=1920&&(r=0,e(i),i=new Float32Array(1920)))}}),n).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){return e instanceof SL?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof mL?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof DL?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}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 SL?delete this._localScreenAudioTrack:e instanceof mL&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}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}};function CL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return tL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let i=new ib({code:eb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});cO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var bL=class extends JM{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,BC(this,"tinyId"),BC(this,"isRemote",!0),BC(this,"jitterBufferDelay",0),BC(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===bL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let i=this.kind===Fb.AUDIO;RO[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(RO.addEnum({key:i?504701:514703,value:ON()}),zN.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(DN()||PN()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===Fb.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," hasFlag: ").concat(this.hasFlag," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},kL=bL;BC(kL,"STATE_SUBSCRIBE","subscribe"),FC([CL(5,1)],kL.prototype,"waitHasMediaTrack",1),FC([AP(bP.INIT,kL.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),GN.emit(sO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===Fb.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(t)}}),5e3),this.player.once(PP.ERROR,(e=>{e.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))})))},ignoreError:!0}),dL(521716,!1)],kL.prototype,"subscribe",1),FC([AP(kL.STATE_SUBSCRIBE,bP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),GN.emit(sO.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],kL.prototype,"unsubscribe",1);var DL=class extends kL{constructor(e,t){super(e,t,1),BC(this,"volume",0),BC(this,"mediaType",1),BC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}decodeFrame(e){if(!this.manager)return e;let t=e;for(let i of this.manager.decodePipeline)if(i&&(t=i({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},NL=[-1,-1,1,-1,-1,1,1,1],wL=[0,0,1,0,0,1,1,1],OL=class extends bP{constructor(e,t){if(super(),this.context=e,BC(this,"name"),BC(this,"input"),BC(this,"output"),BC(this,"texture"),BC(this,"ctx2d",null),BC(this,"fbo"),BC(this,"width",0),BC(this,"height",0),BC(this,"x",0),BC(this,"y",0),BC(this,"program"),BC(this,"vertexShader"),BC(this,"fragmentShader"),BC(this,"totalFrames",0),BC(this,"dropFrames",0),BC(this,"matchInputSize",!0),BC(this,"texCoordBuffer"),BC(this,"positionBuffer"),BC(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),BC(this,"cost",0),BC(this,"_canvas",null),BC(this,"_image"),BC(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 bx)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==TN?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(wL),this.positionBuffer=this.createBuffer(NL),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(hb){this.context.destroy(new ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(hb.message||hb)}))}}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 Cx&&this.render(e)||this.context instanceof bx&&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(e){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 Cx){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(e,t,i,r,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,r,n),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:r,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},MC({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};function PL(){}FC([AP(bP.INIT,"connected",{sync:!0})],OL.prototype,"connect",1),FC([AP("connected",bP.INIT,{ignoreError:!0,sync:!0})],OL.prototype,"disconnect",1),FC([AP([],"closed",{sync:!0})],OL.prototype,"close",1);var ML=e=>e();function LL(){this.dispose()}var xL=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,VL=1,UL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new zL(e,this,this.streamId++);return KL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},FL=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=PL,this.error=PL,this.next=PL,this.dispose=PL,this.subscribe=PL,this.doDefer()}subscribe(e){return e instanceof UL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(ML),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}},BL=class extends FL{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)}},HL=class extends FL{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:PL,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:PL,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:PL;if(super(),this._next=t,this._error=i,this._complete=r,this.then=PL,e instanceof UL){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{KL.defer(n,0)})),KL.create(n),KL.pipe(n),this.sourceId=n.id,this.subscribe(e),KL.subscribe({id:n.id,end:!0}),t==PL?this._next=e=>KL.next(n,0,e):this.next=e=>{KL.next(n,0,e),t(e)},r==PL?this._complete=()=>KL.complete(n,0):this.complete=()=>{this.dispose(),KL.complete(n,0),r()},i==PL?this._error=e=>KL.complete(n,0,e):this.error=e=>{this.dispose(),KL.complete(n,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function jL(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 WL(e,t,i){if(xL()){let r=Object.defineProperties(Object.setPrototypeOf(e,UL.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}});KL.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof UL&&KL.addSource(r,t)}return r}return e}function GL(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return i=>{if(i instanceof UL){let n=WL((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,KL.pipe(n),n}return t=>i(new e(t,...r))}}}function JL(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var zL=class extends BL{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{KL.defer(this.source,this.id)}))}next(e){KL.next(this.source,this.id,e),this.sink.next(e)}complete(){KL.complete(this.source,this.id),this.sink.complete()}error(e){KL.complete(this.source,this.id,e),this.sink.error(e)}},KL={addSource(e,t){JL("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){JL("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;JL("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){JL("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){JL("defer",{id:e.id,streamId:t})},pipe(e){JL("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){JL("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=VL++),JL("create",{name:e.toString(),id:e.id})}},qL=class extends FL{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 YL(){return e=>{let t=new qL(e);if(e instanceof UL){let i=WL((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,KL.pipe(i),i}return WL(t.add.bind(t),"share",arguments)}}function QL(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>WL((function(i){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;r<n&&!i.disposed;)i.next(t[r++]);i.disposed||i.subscribe(e)}),"startWith",arguments)}function XL(e){let t=arguments,i=YL()(WL((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=PL,i.complete=PL,i.error=PL,i}function $L(e,t){return i=>{let r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function ZL(e,t){if("on"in e&&"off"in e)return WL($L((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return WL($L((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return WL($L((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function ex(){return WL((e=>e.complete()),"empty",arguments)}var tx=GL(class extends BL{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"),ix=GL(class extends BL{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),rx=GL(class extends BL{constructor(e,t){super(e);let i=new BL(e);i.next=()=>e.complete(),i.complete=LL,i.subscribe(t)}},"takeUntil"),nx=GL(class extends BL{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),ox=GL(class extends BL{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map"),sx=class extends BL{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()}},ax=class extends BL{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){let i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},cx=class extends sx{},lx=class extends ax{next(e){this.subInner(e,cx),this.next=e=>{this.currentSink.dispose(),this.subInner(e,cx)}}},dx=GL(lx,"switchMap");var ux,hx=(ux=GL(lx,"switchMapTo"),(e,t)=>ux((()=>e),t)),px=GL(class extends BL{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),mx=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:PL,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:PL,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:PL;return r=>new HL(r,e,t,i)},_x=jL(function(e){return WL((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),ox((()=>performance.now())),YL()),fx=[0,1,1,1,0,0,1,0],gx=class extends OL{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),BC(this,"_intervalId",0),BC(this,"_sequence",0),BC(this,"checkGLError",!1),BC(this,"checkVisibilityChange"),e instanceof bx?this.ctx2d=e.ctx||null:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(fx)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),OP.clearTask(this._intervalId),this._intervalId=OP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(OP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Cx){let e=this.context.ctx.getError();e&&this.context.destroy(new ib({code:eb.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(),!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(e){if(this._intervalId&&(OP.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),OP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),OP.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Tx=class extends gx{constructor(e,t){super(e,t),BC(this,"_videoTrack"),BC(this,"_muteOb"),BC(this,"_closedOb",ZL(this,"closed")),BC(this,"_subscription"),BC(this,"_canvasContainer"),Number(_N)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ZL(this._videoTrack,"mute"),jL(ZL(this._videoTrack,"ended"),rx(this._closedOb),mx((()=>{this.context.destroy(new ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=jL(this._muteOb,rx(this._closedOb),hx((e=>t=>{let i=performance.now();jL(_x,nx((t=>t-i<e)),ix(1))(t)})(5e3)),mx((()=>{var e;null==(e=this._videoTrack)||!e.muted||this.context.destroy(new ib({code:eb.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()}},Ex=class extends Tx{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},vx=class extends Tx{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},yx=class extends OL{constructor(e,t){super(e,MC({name:"imageSource"},t)),BC(this,"_lastImage"),BC(this,"_totalFrames",0),BC(this,"_autoResize",!1),BC(this,"_canvasRendered"),BC(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===TN&&(this._canvasRendered=XL(),jL(this._canvasRendered,QL(this._image),dx((e=>e instanceof HTMLCanvasElement?ZL(e,"rendered"):ex())),rx(ZL(this,"closed")),mx((()=>{this.update(0)}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),gP()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){let{width:i,height:r}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),({videoWidth:i,videoHeight:r}=n),!i||!r)return!1;n.width=i,n.height=r}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if(({width:i,height:r}=n),n!==this._lastImage)this._lastImage=n;else if(i===this.width&&r===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&(({width:i,height:r}=n),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===i&&this.height===r&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(i,r)}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)}},Sx=class extends yx{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",jL(ZL(this._player,PP.PLAYER_STATE_CHANGED),rx(ZL(this,"closed")),tx((e=>{let{state:t}=e;return"PLAYING"===t})),mx((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},Ix=class extends Sx{constructor(e,t,i){super(e,new dM({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},Ax=class extends bP{constructor(e){super(),BC(this,"frameRate"),BC(this,"_canvas"),BC(this,"log"),BC(this,"hasAlpha",!1),BC(this,"name"),BC(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Ix(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Tx(this,e)}createVideoImageSource(e,t){return new yx(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Sx(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};BC(Ax,"_ids",0);var Rx={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Cx=class extends Ax{constructor(){super(...arguments),BC(this,"defaultProgam"),BC(this,"defaultVShader"),BC(this,"defaultFShader"),BC(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Ax._ids++)),this.ctx=this._canvas.getContext("webgl2",Rx),!this.ctx)throw new ib({code:eb.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 ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,RO.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}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,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}};FC([AP(bP.INIT,"created",{sync:!0,fail(e){RO.addFailedEvent({key:512700,error:e.cause})},success(){RO.addSuccessEvent({key:512700})}})],Cx.prototype,"create",1),FC([AP("created",bP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],Cx.prototype,"destroy",1);var bx=class extends Ax{constructor(){super(...arguments),BC(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Ax._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,RO.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(),RO.addSuccessEvent({key:512703})}};FC([AP(bP.INIT,"created",{sync:!0,fail(e){RO.addFailedEvent({key:512701,error:e.cause})},success(){RO.addSuccessEvent({key:512701})}})],bx.prototype,"create",1),FC([AP("created",bP.INIT,{ignoreError:!0,sync:!0})],bx.prototype,"destroy",1);var kx=class extends kL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),BC(this,"mediaType",4),BC(this,"source"),BC(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}play(e,t){return(bw(null==t?void 0:t.canvasRender)?t.canvasRender:17===TN)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then((()=>{this.player.calculateStat()}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), ".concat(!!this.player.element)),!this.player.element)return;let e=new bx({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let i=new gx(e,{name:"remotePlayer",logger:this.log});t.connect(i),this.player.setCanvas(e._canvas),gP()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=function(e){return[15,30,45,60].reduce(((t,i)=>Math.abs(i-e)<Math.abs(t-e)?i:t))}(t);!Cw(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),super.stop()}decodeFrame(e){return this.manager?this.manager.decodePipeline.reduce(((e,t)=>t?t({frame:e,track:this}):e),e):e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},Dx=class extends kx{constructor(e,t){super(e,t,2),BC(this,"mediaType",2),BC(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}},Nx=new Map;function wx(e,t){let i=LC(MC({},t),{timestamp:nb()});Nx.has(e)?Nx.get(e).push(i):Nx.set(e,[i])}GN.on(sO.JOIN_SUCCESS,(e=>{let{room:t}=e;wx(t.userId,{eventId:32788})})),GN.on(sO.LEAVE_START,(e=>{let{room:t}=e;wx(t.userId,{eventId:32789})})),GN.on(sO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),wx(t.room.userId,{eventId:e})}})),GN.on(sO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),wx(t.room.userId,{eventId:e})}})),GN.on(sO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Fb.AUDIO?wx(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):wx(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),GN.on(sO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===Fb.AUDIO?wx(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):wx(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),GN.on(sO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&wx(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&wx(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&wx(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),GN.on(sO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&wx(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&wx(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&wx(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),GN.on(sO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&wx(t.room.userId,{eventId:t.kind===Fb.VIDEO?32780:32781})})),GN.on(sO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&wx(t.room.userId,{eventId:t.kind===Fb.VIDEO?32782:32783})})),GN.on(sO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&wx(i.userId,{eventId:t})})),GN.on(sO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:i,prevState:r,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===r?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&wx(i.userId,{eventId:t,remoteUserId:o})})),GN.on(sO.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{userId:t,remoteUserId:i,codec:r,isHWCodec:n,prevImplementation:o,streamType:s}=e,a=n?1:0;o||(a=n?3:2);let c="h264"===r?0:2,l={eventId:4004,param1:a,param2:c,streamType:s||2};i&&(l.remoteUserId=i,l.eventId=4005),wx(t,l),RO.addEnum({key:i?514701:513701,value:a}),RO.addEnum({key:i?514700:513700,value:c})})),GN.on(sO.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:i}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===Fb.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,i&&(e.param1=8)),wx(t.userId,e)}}));var Ox=UC(WC(),1),Px=class extends Ox.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,BC(this,"userMap",new Map),BC(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let r="peer leave [".concat(e,"]");Aw(t)||(r+=":".concat(xk[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:r,userId:n,tinyId:o}=e,s=jw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:jw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Mx(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return tL(((e,n)=>{let o=new WeakMap;return GN.on(sO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),r&&(s.totalSizeInSecond+=r(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:n,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}var Lx,xx=!0,Vx={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"},Ux={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},Fx=((Lx=Fx||{})[Lx.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",Lx[Lx.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",Lx[Lx.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",Lx[Lx.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",Lx[Lx.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",Lx[Lx.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",Lx[Lx.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",Lx[Lx.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",Lx[Lx.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",Lx[Lx.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",Lx[Lx.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",Lx[Lx.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",Lx[Lx.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",Lx[Lx.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",Lx[Lx.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",Lx[Lx.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",Lx[Lx.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",Lx[Lx.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",Lx[Lx.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",Lx[Lx.INVALID_OPERATION=5100]="INVALID_OPERATION",Lx[Lx.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",Lx[Lx.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",Lx[Lx.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",Lx[Lx.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",Lx[Lx.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",Lx[Lx.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",Lx[Lx.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",Lx[Lx.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",Lx[Lx.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",Lx[Lx.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",Lx[Lx.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",Lx[Lx.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",Lx[Lx.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",Lx[Lx.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",Lx[Lx.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",Lx[Lx.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",Lx[Lx.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",Lx[Lx.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",Lx[Lx.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",Lx[Lx.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",Lx[Lx.DEVICE_ERROR=5300]="DEVICE_ERROR",Lx[Lx.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",Lx[Lx.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",Lx[Lx.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",Lx[Lx.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",Lx[Lx.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",Lx[Lx.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",Lx[Lx.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",Lx[Lx.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",Lx[Lx.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",Lx[Lx.SERVER_ERROR=5400]="SERVER_ERROR",Lx[Lx.NEED_TO_BUY=5401]="NEED_TO_BUY",Lx[Lx.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",Lx[Lx.OPERATION_FAILED=5500]="OPERATION_FAILED",Lx[Lx.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",Lx[Lx.REJOIN_FAILED=5502]="REJOIN_FAILED",Lx[Lx.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",Lx[Lx.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",Lx[Lx.OPERATION_ABORT=5998]="OPERATION_ABORT",Lx[Lx.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",Lx);var Bx=LC(MC({},Yk),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(r,"(), received type: ").concat(Sw(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(r,"(), received type: ").concat(Sw(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},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: '".concat("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=Hx(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=Hx(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=Hx(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=Hx(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=Hx(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=Hx(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=Hx(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 Hx(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var jx=class extends Error{constructor(e){let{code:t,extraCode:i,message:r="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=r||function(e){let t,{code:i,params:r,enableDocLink:n=!1}=e,s="",a=Fx[i];try{t=Bx[a]}catch(o){t=Bx.UNKNOWN_ERROR}return Iw(t)?s=t(r):Rw(t)&&(s=t),r.fnName&&!s.includes(r.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(r.fnName,"()")),n&&(s+=" doc:"),s}({code:t===Ux.SERVER_ERROR?t:i||t,params:MC({fnName:o,error:s},n)}),super(c),BC(this,"name","RtcError"),BC(this,"code"),BC(this,"extraCode"),BC(this,"functionName"),BC(this,"message"),BC(this,"handler"),BC(this,"originError"),this.name=Fx[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes("system"))&&(this.handler=()=>{let e=document.createElement("a");jD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):WD&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let r=e;if(e instanceof ib){let{stack:n}=e,o={code:Ux.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case eb.INVALID_PARAMETER:o.code=Ux.INVALID_PARAMETER,o.message=e.message;break;case eb.INVALID_OPERATION:o.code=Ux.INVALID_OPERATION;break;case eb.NOT_SUPPORTED:case eb.NOT_SUPPORTED_H264:o.code=Ux.ENV_NOT_SUPPORTED,e.getCode()===eb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(Yk.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case eb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case eb.SERVER_TIMEOUT:case eb.SWITCH_ROLE_FAILED:o.code=Ux.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case eb.API_CALL_ABORTED:o.code=Ux.OPERATION_ABORT;break;case eb.DEVICE_NOT_FOUND:case eb.DEVICE_AUTO_RECOVER_FAILED:case eb.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case eb.UNKNOWN:break;default:o.code=Ux.OPERATION_FAILED}r=new jx(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof jx)return e;r=new jx({code:Ux.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var Wx=jx,Gx={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Jx={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}}},zx={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(Rw(e)&&!document.getElementById(e))throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},Kx={name:"userId",required:!0,type:"string"},qx={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Vx.AUDIO_PROFILE_STANDARD,Vx.AUDIO_PROFILE_STANDARD_STEREO,Vx.AUDIO_PROFILE_HIGH,Vx.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Yx(e,t){if(!e)throw new Wx({code:Ux.INVALID_OPERATION,extraCode:5101,fnName:t})}function Qx(e,t,i){if(!e)throw new Wx({code:Ux.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var Xx={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 Wx({code:Ux.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(Rw(e.roomId))throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:zx,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Gx},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&PO())throw new Wx({code:Ux.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:LC(MC({},zx),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Gx}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:qx},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&PO())throw new Wx({code:Ux.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:qx}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zx,publish:{type:"boolean"},option:Jx},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&PO())throw new Wx({code:Ux.ENV_NOT_SUPPORTED,extraCode:5201});if(!FO())throw new Wx({code:Ux.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zx,publish:{type:"boolean"},option:Jx}},muteRemoteAudio:[Kx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Kx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zx,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){Yx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Qx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new Wx({code:Ux.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:LC(MC({},zx),{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){Yx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(Qx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new Wx({code:Ux.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&&Aw(e.streamType))throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){Yx(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(!lP)throw new Wx({code:Ux.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new Wx({code:Ux.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});Yx(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 Wx({code:Ux.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 Wx({code:Ux.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(Yx(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new Wx({code:Ux.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},$x={TRTC:Xx},Zx=class extends Error{};function eV(e,t){let i=zw(e);for(let r=0;r<t.length;r++)Jw(i[r],t[r]);return i}function tV(e){this._resolve=Promise.resolve(e)}function iV(e){this._reject=Promise.reject(e)}var rV=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=eV;let i=rV.instances.get(e);i?i.set(t,this):rV.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let i=rV.instances.get(e);return i&&i.get(t)||new rV(e,t)}static gets(e,t){let i=rV.instances.get(e),r=[];return i&&i.forEach(((e,i)=>{t.test(i)&&r.push(e)})),r}action(e,t,i){let r=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},n=t=>{var i,r;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new Zx("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:tV,reject:iV};try{switch(this.state){case 1:if(0===e)throw new Zx("already started");break;case 4:if(2===e)throw new Zx("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(r,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new Zx("already start");break;case 3:switch(e.type){case 2:throw new Zx("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Zx("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new Zx("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 Zx("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Zx("start not allowed after update");case 0:throw new Zx("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new Zx("keep start")),new Zx("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}},nV=rV;nV.instances=new WeakMap;var oV=new WeakMap,sV=(e,t)=>{if(t instanceof Zx){let{stack:i}=t;t=new Wx({code:Ux.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function aV(e,t){return tL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=nV.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(sV.bind(null,r))):i.apply(this,o)}))}function cV(e,t){let{merge:i,debounce:r}=t||{};return tL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=nV.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=r;return new Promise(((r,o)=>{var a,l;let d=null==(a=oV.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return r();c.action(2,t.bind(this),s).catch(sV.bind(null,n)).then(r,o)}),e);oV.has(this)?null==(l=oV.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):oV.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(sV.bind(null,n))}))}function lV(e){return tL(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(nV.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=nV.get(this,s);return a?a.action(3,t.bind(this),n).catch(sV.bind(null,i)):t.apply(this,n)}))}var dV={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"},uV=new Set([dV.ERROR,dV.AUTOPLAY_FAILED,dV.KICKED_OUT,dV.REMOTE_USER_ENTER,dV.REMOTE_USER_EXIT,dV.REMOTE_AUDIO_AVAILABLE,dV.REMOTE_AUDIO_UNAVAILABLE,dV.REMOTE_VIDEO_AVAILABLE,dV.REMOTE_VIDEO_UNAVAILABLE,dV.CONNECTION_STATE_CHANGED,dV.PUBLISH_STATE_CHANGED,dV.SCREEN_SHARE_STOPPED,dV.DEVICE_CHANGED]);function hV(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function pV(e){return e===Vx.QOS_PREFERENCE_CLEAR?"detail":e===Vx.QOS_PREFERENCE_SMOOTH?"motion":""}var mV=class{constructor(){BC(this,"_log"),this._log=cO.createLogger({id:"fd"})}download(e,t){return jC(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=Vw();if(t=Iw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Vw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),RO.addSuccessEvent({key:522700,cost:Vw()-r}),t.data}catch(hb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(hb)),RO.addFailedEvent({key:522700,error:hb}),hb}}))}downloadWithFetch(e,t){return jC(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)throw new Error("network response was not ok");return i="arraybuffer"===t?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(pk){throw pk}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?i({data:n.response}):r(new Error("XHR failed"))},n.onerror=r,n.send(null)}))}loadWasm(e,t){return jC(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Vw(),r=null,n=null;if(Iw(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&Iw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(pb){n=pb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(pb){n=pb}if(r){let t=Vw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),RO.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),RO.addFailedEvent({key:522701,error:n}),n}))}};FC([FP({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],mV.prototype,"download",1);var _V=new mV;function fV(e){let{TRTC:t,room:i,errorModule:r,assetsPath:n}=e;return{TRTC:t,room:i,assetsPath:n,fileDownloader:_V,innerEmitter:GN,constants:ab,environment:Qk,utils:sb,eventLogger:zN,log:this.room.getLogger(),loggerManager:cO,errorModule:r,kvStatManager:RO,rtcDectection:uO,trtc:this,clearStarted:(e,t)=>{let i=e.getAlias(),r=nV.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:AL,createAudioNode:SM}}var gV=new WeakMap;function TV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return tL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{vV.call(this,t,n,i,this._name)}catch(hb){return Promise.reject(hb)}return e.apply(this,n)}))}function EV(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return tL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{vV.call(this,t,n,i,this._name)}catch(hb){throw hb}return e.apply(this,n)}))}function vV(e,t,i,r){if(Dw(e))for(let n=0;n<e.length;n++)yV.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else yV.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function yV(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:Ux.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(Aw(i)){if(t.required)throw new Wx(s(5001));if(Aw(t.defaultValue))return void(Iw(t.validate)&&t.validate.call(this,i,r,n,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let r=0;r<t.type.length;r++)null===t.type[r]&&null===i&&(e=!0),Iw(t.type[r])&&i instanceof t.type[r]&&(e=!0),Rw(t.type[r])&&Sw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new Wx({code:Ux.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Pw(e)?Mw(e):Rw(e)?e:Sw(e)))},value:i}})}else if(!Aw(t.type)&&Sw(i)!==t.type)throw new Wx(s(5002));if(!1===t.allowEmpty){let e=Cw(i)&&(0===i||Number.isNaN(i)),t=Rw(i)&&""===i.trim();if(e||t)throw new Wx(s(5003))}if(t.notLessThanZero&&Cw(i)&&i<0)throw new Wx(s(5006));if(!Aw(t.min)&&Cw(i)&&i<t.min)throw new Wx(s(5007));if(!Aw(t.max)&&Cw(i)&&i>t.max)throw new Wx(s(5008));if(Rw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Wx(s(5004))}else if(Iw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Wx(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new Wx(s(5005));let{properties:a}=t;Ew(a)&&kw(i)&&Object.keys(a).forEach((e=>{yV.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;Ew(c)&&Dw(i)&&i.forEach(((e,t)=>{yV.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),Iw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function SV(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n}=e;return tL(((e,o)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];var l;function d(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(Sw(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(Sw(t))}}let u=this._log||cO;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?u.info("".concat(o,"() ").concat(JSON.stringify(a,((e,t)=>d(e,t,["userSig","privateMapKey"]))))):u.info("".concat(o,"()"));let h=r?r(...a):gO[o];try{let i=e.apply(this,a),r=Vw();return Ow(i)?i.then((e=>(u.info("".concat(o,"() success ").concat(t.call(this,...a))),RO.addSuccessEvent({key:h,cost:Vw()-r}),e))).catch((e=>{var i;let r=(e=Wx.convertFrom.call(this,e,o,1===a.length?a[0]:a)).extraCode||e.code,n=null!=(i=e.message)&&i.includes(r)?"":" code:".concat(r);throw u.error("".concat(o,"() failed ").concat(t.call(this,...a)," ").concat(e).concat(n," params: ").concat(JSON.stringify(a,d))),RO.addFailedEvent({key:h,error:e}),e})):(RO.addSuccessEvent({key:h}),i)}catch(p){let e=(p=Wx.convertFrom.call(this,p,o)).extraCode||p.code,t=null!=(l=p.message)&&l.includes(e)?"":" code:".concat(e);throw u.error("".concat(o,"() failed ").concat(p).concat(t," params: ").concat(JSON.stringify(a,d))),RO.addFailedEvent({key:h,error:p}),p}}))}var IV=e=>tL(((t,i)=>function(r,n){return jC(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new Wx({code:Ux.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(Iw(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new Wx({code:Ux.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return vV.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),AV=0,RV=class{constructor(e,t){BC(this,"player"),BC(this,"publisher"),BC(this,"mixInput"),this.mixInput=new EM(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||(Aw(e.volume)||(this.volume=e.volume),Aw(e.loop)||(this.loop=e.loop),Aw(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)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function CV(e,t){if(t&&"function"!=typeof t)throw new Wx({code:Ux.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var bV=class{constructor(e){this.core=e,BC(this,"log"),BC(this,"mixedMusicMap",new Map),BC(this,"cacheMusicMap",new Map),AV+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(AV)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(AV)),this.core=e}getName(){return bV.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return bV.startValidateRule;case"update":return bV.updateValidateRule;case"stop":return bV.stopValidateRule}}start(e){return jC(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:i,url:r}=e;if(this.mixedMusicMap.has(i))return;let n=this.cacheMusicMap.get(i);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new RV(e,t.audioManager),this.cacheMusicMap.set(i,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),RO.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return jC(this,null,(function*(){let{id:t,operation:i,seekFrom:r,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),Aw(i)||o.setOperation(i),Aw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return jC(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:i,volume:r,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&RO.addCount({key:502711}),i&&RO.addCount({key:502703}),r&&RO.addCount({key:502704}),n&&RO.addCount({key:502705}),o&&RO.addCount({key:502706}),s&&RO.addCount({key:502707}),"function"!=typeof a&&RO.addCount({key:502709}),"function"!=typeof l&&RO.addCount({key:502710}),"function"!=typeof c&&RO.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},kV=bV;BC(kV,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],r=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=r.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new Wx({code:Ux.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new Wx({code:Ux.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});CV("onTimeUpdate",e.onTimeUpdate),CV("onEnded",e.onEnded),CV("onDurationChange",e.onDurationChange)}}),BC(kV,"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){CV("onTimeUpdate",e.onTimeUpdate),CV("onEnded",e.onEnded),CV("onDurationChange",e.onDurationChange)}}),BC(kV,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),BC(kV,"Name","AudioMixer");var DV,NV=0,wV=class{constructor(e){this.core=e,BC(this,"log"),BC(this,"audioContext",_M()),BC(this,"workletNode"),NV+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(NV)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(NV)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,r,n){if(!e.room.audioManager.hasAudioTrack)throw new Wx({code:Ux.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return DV||(DV=this.doPreload(e)),DV}doPreload(e){return jC(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield uM(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return wV.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return wV.startValidateRule(this.core);case"update":return wV.updateValidateRule;case"stop":return wV.stopValidateRule}}start(e){return jC(this,null,(function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:i,sign:r,status:n,message:o}=yield function(e){return jC(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Fb.MAIN;return"https://".concat(XN[t]||tw(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(r,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(LC(MC({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new Wx({code:Ux.INVALID_PARAMETER,message:o});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:r,status:n}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return jC(this,null,(function*(){}))}stop(){return jC(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},OV=wV;BC(OV,"updateValidateRule",{type:"object"}),BC(OV,"stopValidateRule",{type:"object"}),BC(OV,"Name","AIDenoiser");var PV=UC(WC(),1),MV=class extends PV.EventEmitter{constructor(){super(),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 jC(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!cD&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(ub){zN.uploadEvent({log:"stat-pressure-detector-start-failed",error:ub})}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&cO.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(pk){zN.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:pk})}}},LV=new MV;function xV(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),o=r%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(i);return s.push(...new Uint8Array(a.buffer)),s.push(128),new _L(new DataView(new Uint8Array(s).buffer),!0)}function VV(e){return"empty"===e.type||0===e.data.byteLength}function UV(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function FV(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}function BV(e){let{frame:t,seiMessageList:i}=e;if(!i||0===i.length||0===t.data.byteLength)return t;let r=9-FV(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(xV),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function HV(e){let{frame:t,onSEI:i}=e;try{let e=new DataView(t.data);if(VV(t)||!UV(e))return t;let r=[],n=0,o=-1,s=-1;for(let i=0;i<t.data.byteLength;i++){let a=e.getUint8(i);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=i-n;if(-1===o?o=a:-1===s&&(s=a,r.push(new _L(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(i+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==i||i(r.reverse())}catch(ub){}return t}var jV=0,WV=class{constructor(e){this.core=e,BC(this,"log"),BC(this,"_seiMessageList",[]),BC(this,"_smallSeiMessageList",[]),BC(this,"_subStreamSeiMessageList",[]),jV++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(jV)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(jV)),this.core=e,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:i}=e;try{return BV({frame:t,seiMessageList:8===i?this._smallSeiMessageList:2===i?this._subStreamSeiMessageList:this._seiMessageList})}catch(pk){this.log.warn(pk)}return t}decode(e){let{frame:t,track:i}=e;return HV({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(dV.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:i.userId,streamType:2===i.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:aP?this.encode:BV,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:aP?this.decode:HV,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update(e){let{buffer:t,options:i}=e;var r;let n=[i.seiPayloadType,t],o=!!i.small;i.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(r=this.core.room.scriptTransformWorker)||r.postMessage({type:"sei",data:n,isMain:!i.toSubStream,small:o})}getName(){return WV.Name}getAlias(){return"sei"}getGroup(){return"sei"}},GV=WV;BC(GV,"autoStart",!0),BC(GV,"Name","SEI");var JV,zV=0,KV=class{constructor(e){this.core=e,BC(this,"_core"),BC(this,"log"),BC(this,"dumpLocalVideoMap",{}),BC(this,"dumpRemoteVideoMap",{}),BC(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++zV)}),this.log.info("created")}getName(){return KV.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 jC(this,null,(function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return jC(this,null,(function*(){try{if(JV)yield JV;else{let e=Date.now();JV=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(lb,".js")),yield JV,this.log.info("download debug dialog script cost: ".concat(Date.now()-e,"ms"))}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(mO){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(mO))}}))}closeDebugDiaLog(){var e;null==(e=this.dialog)||e.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo(e){let{frame:t,mediaType:i}=e;return this.encodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=2===i?"sub":"main",r=this.dumpLocalVideoMap[e];r&&(r.data.push(t.data),r.duration>0&&Date.now()-r.startTimestamp>1e3*r.duration&&r.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:i}=e;return this.decodeVideoDump({frame:t,onDump:()=>{if(!i)return;let e=this.dumpRemoteVideoMap["".concat(i.userId,"-").concat(i.streamType)];e&&(e.data.push(t.data),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}encodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}decodeVideoDump(e){let{frame:t,onDump:i}=e;return null==i||i(),t}loadScript(e){return new Promise(((t,i)=>{this.log.info("loading debug dialog from ".concat(e));let r=document.createElement("script");r.type="text/javascript",r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=e,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)}))}},qV=KV;BC(qV,"Name","Debug"),BC(qV,"autoStart",!0),FC([FP({settings:{timeout:3e3,retries:3},onError(e,t,i){var r;null!=(r=null==e?void 0:e.message)&&r.includes("timeout")?t():i(e)}})],qV.prototype,"loadScript",1);var YV=UC(WC(),1),QV=Symbol("instance"),XV=new Map,$V="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 ZV(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(eU.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var eU=class extends YV.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=eU.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[QV];r?this.name=r.name+"-"+r.count++:i[QV]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=XV.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);XV.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=eU.instances.get(e),t||eU.instances.set(e,t=new eU(e,void 0,Object.create(eU.prototype)))):(t=eU.instances2.get(e),t||eU.instances2.set(e,t=new eU(e.constructor.name,void 0,Object.create(eU.prototype)))),t}static getState(e){var t;return null===(t=eU.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};$V(eU.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){ZV.call(this,e)}};eU.STATECHANGED="stateChanged",eU.UPDATEAFSM="updateAFSM",eU.INIT="[*]",eU.ON="on",eU.OFF="off",eU.instances=new Map,eU.instances2=new WeakMap;var tU=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},iU=class{constructor(e,t,i){BC(this,"trackDoneOB"),BC(this,"startOB"),BC(this,"stopOB"),BC(this,"inputFrameCount",0),BC(this,"decodedFrameCount",0),BC(this,"type","auto"),BC(this,"config"),BC(this,"decoder"),BC(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=ZL(t,eU.INIT),this.stopOB=XL(this.trackDoneOB),this.startOB=XL(),"auto"===i.type?this.type="webCodecs":this.type=i.type;let o=XL();jL(this.startOB,QL(0),dx((e=>{let i=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),jL(i,rx(this.stopOB),mx((()=>{}),(i=>{t.log.error(i),r.addFailedEvent({key:tU(this.type),error:i}),e>4?this.startOB.error(i):this.startOB.next(e+1)}))),jL(i,ix(1),px(ex))})),rx(this.stopOB),mx((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{r.addSuccessEvent({key:tU(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 YL()((t=>jC(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(hb){e.log.error(hb),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"}))}},rU={type:"object"},nU=class{constructor(e){this.core=e,BC(this,"log"),BC(this,"contextMap",new Map),BC(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return nU.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return nU.Name}getValidateRule(e){return rU}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:i}=e;return this.decodeProcessorMap.has(i)?this.decodeProcessorMap.get(i)({frame:t,track:i}):t},type:3})}decode(e){return t=>{let{frame:i,track:r}=t;if(r!==e.track)return i;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(i);let n=new iU(this.core,r,e);return jL(n.trackDoneOB,ix(1),mx((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:r})}))),this.contextMap.set(r,n),n.decodeFrame(i)}}stop(e){let{track:t}=e,i=this.contextMap.get(t);!i||(i.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new iU(this.core,e.track,e))}}},oU=nU;BC(oU,"Name","AudioDecoder");var sU=0,aU=new Set,cU=null;db("5.8.7-beta.8");var lU={RtcError:Wx,ErrorCode:Ux,ErrorCodeDictionary:Fx},dU=class extends $C.EventEmitter{constructor(e,t){super(),BC(this,"_room"),BC(this,"_eventListened",new Set),BC(this,"_localVideoTrack",null),BC(this,"_localAudioTrack",null),BC(this,"_localScreenTrack",null),BC(this,"_localScreenAudioTrack",null),BC(this,"_localVideoConfig",null),BC(this,"_localScreenConfig",null),BC(this,"_localAudioConfig",null),BC(this,"_remoteVideoConfigMap",new Map),BC(this,"_remoteAudioConfigMap",new Map),BC(this,"_remoteAudioVolumeMap",new Map),BC(this,"_remoteAudioMuteMap",new Map),BC(this,"_mediaTrackMap",new WeakMap),BC(this,"_log",cO.createLogger({id:"t".concat(++sU)})),BC(this,"_plugins",new Map),BC(this,"_networkQuality",null),BC(this,"_speakerId"),BC(this,"_getPCMAbortCtrl"),this._room=new e(MC({logger:this._log,frameWorkType:dU.frameWorkType},t)),this._log.debug("TRTC.create() ".concat(JSON.stringify(t,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),t.plugins&&t.plugins.forEach((e=>{this._use(e,t.assetsPath)})),this._use(kV,t.assetsPath),this._use(OV,t.assetsPath),this._use(oU,t.assetsPath),this._use(qV),t.enableSEI&&lP&&this._use(GV),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(dV.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new Wx({code:Ux.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:i}=e;e.emit=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{return i.apply(e,n)}catch(hb){let i=UN({key:qk.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return cO.warn("".concat(i,"\n\n").concat(hb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;xx&&(xx=!1,5!==cO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Ib,"/en/index.html")),console.info("* Changelog: ".concat(Ib,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),cO.info("TRTC Web SDK Version:",lb),cO.info("UA:",navigator.userAgent),cO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),kN().then((e=>{e&&cO.info(bN)})))}();let i=new dU(e,t||{});return aU.add(i),i}get room(){return this._room}_listenEvents(){xP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(dV.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(dV.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(dV.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(dV.ERROR,Wx.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(dV.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=LC(MC({},e),{uplinkRTT:Math.min(e.uplinkRTT,Gk),downlinkRTT:Math.min(e.downlinkRTT,Gk)});this.emit(dV.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{xP(t,t).add("player-state-changed",(i=>{let r=LC(MC({},i),{userId:e.userId});t.kind===Fb.VIDEO&&(r.streamType=hV(t.streamType)),this.emit(t.kind===Fb.AUDIO?dV.AUDIO_PLAY_STATE_CHANGED:dV.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===eb.PLAY_NOT_ALLOWED&&this.emit(dV.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{VP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:r}=i,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(r),a||this._remoteVideoConfigMap.delete("".concat(r,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(r,"_","sub")),n!==s&&(this.emit(s?dV.REMOTE_AUDIO_AVAILABLE:dV.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?dV.REMOTE_VIDEO_AVAILABLE:dV.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"}),a?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"})),t.hasAuxiliary!==i.hasAuxiliary&&(this.emit(i.hasAuxiliary?dV.REMOTE_VIDEO_AVAILABLE:dV.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(dV.SEI_MESSAGE,LC(MC({},e),{streamType:hV(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(dV.ERROR,new Wx({code:Ux.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,Gk),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/Kk},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/Kk},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(dV.STATISTICS,l)})).add("custom-message",(e=>{this.emit(dV.CUSTOM_MESSAGE,e)})),xP(this,wM).add("audioInputAdded",(e=>{this.emit(dV.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(dV.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(dV.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(dV.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>jC(this,null,(function*(){if(this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),cU&&cU.deviceId===Pk){let e=(yield VM()).find((e=>e.deviceId===Pk));e&&cU.groupId!==e.groupId&&(cU=e,this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>jC(this,null,(function*(){this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield VM())[0];if(!t||!cU||cU.groupId===t.groupId)return;let i=cU.deviceId===e.deviceId,r=cU.deviceId===Pk&&cU.deviceId===t.deviceId;(i||r)&&(cU=t,this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}use(e){let t,i;"plugin"in e?(t=e.plugin,i=e.assetsPath):t=e,this._use(t,i||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name))return void this._log.warn("duplicate install plugin",e.Name);let i=new e(fV.call(this,{TRTC:dU,room:this._room,errorModule:lU,assetsPath:t}));this._plugins.set(e.Name,i),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return jC(this,null,(function*(){var t,i;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Rw(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,bw(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,dU.frameWorkType),this._checkTrackToPublish(),LV.start()}))}exitRoom(){return jC(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return jC(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(){VP(this),this.removeAllListeners(),this._room.destroy(),aU.delete(this),0===aU.size&&LV.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}))}startLocalAudio(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:r,option:n}=t,o=new mL(e._room.audioManager),s={},a={muted:!0};n&&(Aw(n.microphoneId)?Aw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&Cw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),Aw(n.profile)||(Rw(n.profile)?xb[n.profile]&&o.setProfile(xb[n.profile]):o.setProfile(n.profile)),Cw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),Aw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),Aw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),Aw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(dV.ERROR,new Wx({code:Ux.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(dV.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=Wx.convertFrom(t.error)),e.emit(dV.PUBLISH_STATE_CHANGED,LC(MC({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),Aw(r)||o.setMute(r),xP(o,o).add("player-state-changed",(t=>{e.emit(dV.AUDIO_PLAY_STATE_CHANGED,LC(MC({},t),{userId:""}))})),e.listeners(dV.AUDIO_FRAME).length>0&&(e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(dU.EVENT.AUDIO_FRAME,{data:t})}))),e._getPCMAbortCtrl&&o.on("input-media-track-changed",(()=>{e._getPCMAbortCtrl&&(e._getPCMAbortCtrl.abort("inputMediaTrackChanged"),e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(dU.EVENT.AUDIO_FRAME,{data:t})})))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=LC(MC({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return jC(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:r}=e,n={};r&&(r.microphoneId?yield this._localAudioTrack.switchDevice(r.microphoneId):Aw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),Aw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),Aw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!Aw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),Aw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Jw(this._localAudioConfig,e)}))}stopLocalAudio(){return jC(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),VP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:r=!0,mute:n,option:o}=t,s=new gL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:Aw(o.useFrontCamera)?Aw(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?Fb.FACING_MODE_USER:Fb.FACING_MODE_ENVIRONMENT,Aw(o.profile)||(Rw(o.profile)?Vb[o.profile]&&s.setProfile(Vb[o.profile]):s.setProfile(o.profile)),Aw(o.fillMode)||(c.objectFit=o.fillMode),Aw(o.mirror)||(c.mirror=o.mirror),Aw(o.small)||(KO()?Rw(o.small)?s.small=Vb[o.small]:!0===o.small?s.small=Vb["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(dV.ERROR,new Wx({code:Ux.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(dV.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=Wx.convertFrom(t.error)),e.emit(dV.PUBLISH_STATE_CHANGED,LC(MC({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),Aw(n)||(yield s.setMute(n)),s.mediaTrack){if(null!=o&&o.qosPreference){let e=pV(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=pV(Vx.QOS_PREFERENCE_SMOOTH));s.outMediaTrack&&(s.outMediaTrack.contentHint=s.mediaTrack.contentHint)}xP(s,s).add("player-state-changed",(t=>{e.emit(dV.VIDEO_PLAY_STATE_CHANGED,LC(MC({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=LC(MC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return jC(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(Aw(n.profile)||(Rw(n.profile)?Vb[n.profile]&&this._localVideoTrack.setProfile(Vb[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&Aw(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):Aw(n.useFrontCamera)?Aw(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?Fb.FACING_MODE_USER:Fb.FACING_MODE_ENVIRONMENT),Aw(n.fillMode)||(o.objectFit=n.fillMode),Aw(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=pV(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=e)}if(n.small){let e=!this._localVideoTrack.small;KO()?(!0===n.small?this._localVideoTrack.small=Vb["120p"]:Rw(n.small)?this._localVideoTrack.small=Vb[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===n.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!Aw(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),Aw(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Jw(this._localVideoConfig,e)}))}stopLocalVideo(){return jC(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),VP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:r=!0,option:n}=t,o=new yL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=Wx.convertFrom(t.error)),e.emit(dV.PUBLISH_STATE_CHANGED,LC(MC({},t),{error:i}))})),e._listenOutputTrackChanged(o),"main"===t.streamType&&(o.mediaType=4);let s=null,a={},c={};n&&(Aw(n.profile)||(Rw(n.profile)?Ub[n.profile]&&o.setProfile(Ub[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),Aw(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(a.videoTrack=n.videoTrack),n.audioTrack&&(a.audioTrack=n.audioTrack),n.captureElement&&(a.captureElement=n.captureElement),n.preferDisplaySurface&&(a.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(a);if(null!=n&&n.qosPreference){let e=pV(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=pV(Vx.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(Fb.ENDED,(()=>{e._stopScreenShare(),e.emit(dV.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new SL(e._room.audioManager),yield s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),xP(o,o).add("player-state-changed",(t=>{e.emit(dV.VIDEO_PLAY_STATE_CHANGED,LC(MC({},t),{userId:"",streamType:"sub"}))})),r&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=LC(MC({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return jC(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(Aw(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=pV(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!Aw(i)&&(i&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!i&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Jw(this._localScreenConfig,e)}))}stopScreenShare(){return jC(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return jC(this,null,(function*(){let{view:t,userId:i,streamType:r,option:n}=e,o="".concat(i,"_").concat(r);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(r));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===r?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(Aw(n.fillMode)||(a.objectFit=n.fillMode),Aw(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===r&&!Aw(n.small)&&(s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user))),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!Aw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return jC(this,null,(function*(){var t,i;let{view:r,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(Aw(s.fillMode)||(l.objectFit=s.fillMode),Aw(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!Aw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),Jw(h,e);let p=Aw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=Aw(r)?h.view:r,_=Aw(null==s?void 0:s.viewRoot)?null==(i=h.option)?void 0:i.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:_})}))}stopRemoteVideo(e){return jC(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return jC(this,null,(function*(){let i=[],r=this._room.remotePublishedUserMap.get(e.userId);if(r){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=r;"main"===e.streamType&&(n.stop(),t.hasVideo&&i.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return jC(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){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 jC(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return jC(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return jC(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,i),this._eventListened.add(e),e===dU.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(dU.EVENT.AUDIO_FRAME,{data:e})})),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",(()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(dU.EVENT.AUDIO_FRAME,{data:e})})))})))),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{uV.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(i)))}catch(hb){}return super.emit(e,...i)}off(e,t,i){var r,n;return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners(),null==(r=this._getPCMAbortCtrl)||r.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,i),e===dU.EVENT.AUDIO_FRAME&&(null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},i=null,r="main",n=!1;if(Rw(t)?e=t:(e=t.userId,n=!0===t.processed,t.streamType&&(r=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(i=t.remoteAudioTrack)}else i="sub"===r?this._localScreenAudioTrack:this._localAudioTrack;return i?n&&i.outMediaTrack&&i.outMediaTrack!==i.mediaTrack?i.outMediaTrack.clone():i.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main",processed:r=!1}=e,n=null;if(""===t)"main"===i&&this._localVideoTrack&&(n=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(n=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(n="main"===i?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return n?r&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:i="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===i&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===i&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===i&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_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 jC(this,null,(function*(){(yield VM()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),cU=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return jC(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let i=this._room.remotePublishedUserMap.get(t);if(!i)return;let r={},n=i.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let i=this._remoteAudioVolumeMap.get(t),o=Cw(i)?i:100;r.volume=o,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),jL(ZL(n,"decode-failed"),rx(ZL(n,eU.INIT)),mx((()=>{this.startPlugin(oU.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:r,track:n})}catch(o){throw this._remoteAudioConfigMap.delete(t),o}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return jC(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.get(i.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return jC(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),Aw(t)&&n&&n.view&&!Hw(i)){let e=Kw(n.view);e.length>0&&(yield r.play(e,i))}if(!Aw(t)){let e=Kw(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return jC(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(pb){}Aw(t.muted)||i.setPlayerMute(t.muted),Aw(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!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(dV.TRACK,{userId:i,streamType:hV(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let r=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&r.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0: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)),0!==r.length)return this._room.publish(...r).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:i,receiveWhenViewVisible:r=!1,viewRoot:n}=e;if(Aw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(hV(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Dw(i)&&0===i.length||!r)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(Kw(i));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return jC(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),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(),this._remoteAudioVolumeMap.clear(),function(e){let t=gV.get(e);t&&(t.forEach((e=>clearTimeout(e))),gV.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{VP(e.remoteAudioTrack),VP(e.remoteVideoTrack),VP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return jC(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),VP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return jC(this,null,(function*(){if(cU&&!OM(cU))this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:cU});else{let e=yield VM();if(e[0]&&!OM(e[0]))cU=e[0],this.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!cU||OM(cU))&&(this._initActiveSpeaker(),GN.off("102",this._initActiveSpeaker))};GN.on("102",e)}}}))}_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;this._room.subscribe(e).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:LC(MC({seiPayloadType:243},t),{small:!(null==(i=this._localVideoTrack)||!i.small)})}),RO.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),RO.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){cO.setLogLevel(e),Aw(t)||(t?cO.enableUploadLog():cO.disableUploadLog())}static isSupported(){return VO()}static getCameraList(){return LM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return MM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return VM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return jC(this,null,(function*(){(yield VM()).forEach((t=>{t.deviceId===e&&(aU.forEach((i=>{i._setCurrentSpeaker(e),i.emit(dV.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),cU=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(AO.version=s),t){case"count":AO.addCount({key:i,useUV:o});break;case"enum":AO.addEnum({key:i,value:r,useUV:o});break;case"number":AO.addNumber({key:i,value:r,split:n})}}},uU=dU;BC(uU,"_loggerManager",cO),BC(uU,"EVENT",dV),BC(uU,"ERROR_CODE",Ux),BC(uU,"TYPE",Vx),BC(uU,"frameWorkType",30),FC([SV({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"}})})],uU.prototype,"use",1),FC([TV($x.TRTC.enterRoom),aV("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})),tL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),SV()],uU.prototype,"enterRoom",1),FC([SV()],uU.prototype,"exitRoom",1),FC([TV($x.TRTC.switchRole),cV("room",{merge:(e,t)=>t}),SV()],uU.prototype,"switchRole",1),FC([SV()],uU.prototype,"destroy",1),FC([TV($x.TRTC.startLocalAudio),aV("audio",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(o=null==r?void 0:r.option)?void 0:o.microphoneId)})),SV()],uU.prototype,"startLocalAudio",1),FC([TV($x.TRTC.updateLocalAudio),cV("audio",{debounce:{delay:200,getKey:()=>"".concat(sU,"-localAudio"),isNeedToDebounce:e=>{var t;return!Aw(null==(t=e.option)?void 0:t.captureVolume)}}}),SV()],uU.prototype,"updateLocalAudio",1),FC([lV("audio"),SV()],uU.prototype,"stopLocalAudio",1),FC([TV($x.TRTC.startLocalVideo),aV("video",((e,t)=>{let[i]=e,[r]=t;var n,o;return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(o=null==r?void 0:r.option)?void 0:o.cameraId)})),SV()],uU.prototype,"startLocalVideo",1),FC([TV($x.TRTC.updateLocalVideo),cV("video"),SV()],uU.prototype,"updateLocalVideo",1),FC([lV("video"),SV()],uU.prototype,"stopLocalVideo",1),FC([TV($x.TRTC.startScreenShare),aV("screen",(()=>!0)),SV()],uU.prototype,"startScreenShare",1),FC([TV($x.TRTC.updateScreenShare),cV("screen"),SV()],uU.prototype,"updateScreenShare",1),FC([SV()],uU.prototype,"stopScreenShare",1),FC([TV($x.TRTC.startRemoteVideo),aV((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),SV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],uU.prototype,"startRemoteVideo",1),FC([TV($x.TRTC.updateRemoteVideo),cV((e=>"v".concat(e.userId).concat(e.streamType))),SV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],uU.prototype,"updateRemoteVideo",1),FC([TV($x.TRTC.stopRemoteVideo),tL((e=>function(t){return jC(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)}))})),SV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],uU.prototype,"stopRemoteVideo",1),FC([lV((e=>"v".concat(e.userId).concat(e.streamType)))],uU.prototype,"_stopRemoteVideo",1),FC([TV(...$x.TRTC.muteRemoteAudio),SV({getRemoteId:e=>e})],uU.prototype,"muteRemoteAudio",1),FC([EV(...$x.TRTC.setRemoteAudioVolume),function(e,t){return tL(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let s=gV.get(this);s||(s=new Map,gV.set(this,s));let a=t(...n),c=s.get(a);if(!c||c<=0){i.apply(this,n);let t=setTimeout((()=>{var e;null==(e=gV.get(this))||e.delete(a)}),e);s.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;i.apply(this,n),null==(e=gV.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),SV({getRemoteId:e=>e})],uU.prototype,"setRemoteAudioVolume",1),FC([IV("start"),eL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),aV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),SV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>TO[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],uU.prototype,"startPlugin",1),FC([IV("update"),cV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),SV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>EO[e.getName()]})],uU.prototype,"updatePlugin",1),FC([IV("stop"),lV(((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return"*"===i?new RegExp("".concat(r,".*")):r+i})),SV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>vO[e.getName()]})],uU.prototype,"stopPlugin",1),FC([EV(...$x.TRTC.enableAudioVolumeEvaluation)],uU.prototype,"enableAudioVolumeEvaluation",1),FC([SV()],uU.prototype,"getVideoSnapshot",1),FC([SV()],uU.prototype,"_setCurrentSpeaker",1),FC([aV((e=>"a".concat(e.userId)),(()=>!0))],uU.prototype,"_startRemoteAudio",1),FC([tL((e=>function(t){return jC(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(LC(MC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),lV((e=>"a".concat(e.userId)))],uU.prototype,"_stopRemoteAudio",1),FC([lV("room")],uU.prototype,"_exitRoom",1),FC([lV("screen")],uU.prototype,"_stopScreenShare",1),FC([TV(...$x.TRTC.sendSEIMessage),Mx({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}})],uU.prototype,"sendSEIMessage",1),FC([TV($x.TRTC.sendCustomMessage),Mx({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],uU.prototype,"sendCustomMessage",1),FC([TV($x.TRTC.create)],uU,"_create",1);var hU=uU,pU=class{constructor(){this._set=new Set,GN.on(sO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}};function mU(){return jC(this,null,(function*(){let e,t;try{let t=yield MM();e=t&&t.length}catch(u){}try{let e=yield LM();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=uO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};zN.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),zN.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var _U=UC(WC()),fU="1",gU="2",TU="3",EU="4",vU="5",yU="6",SU={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},IU=[SU.UPDATE_REMOTE_MUTE_STAT,SU.UPLINK_NETWORK_STATS,SU.USER_LIST_RES,SU.MUTE_RESULT,SU.SERVER_FIRST_PACKAGE_RECEIVED,SU.RECEIVE_CUSTOM_MSG],AU={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},RU="publish_change",CU="join",bU="leave",kU="quality_report",DU="mute_uplink",NU="publish",wU="publish_state_change",OU="unpublish",PU="subscribe",MU="unsubscribe",LU="subscribe_change",xU="start_publishing",VU="stop_publishing",UU="start_push_user_cdn",FU="stop_push_user_cdn",BU="start_mcu_mix",HU="stop_mcu_mix",jU="start_publish_cdn_stream",WU="update_publish_cdn_stream",GU="stop_publish_cdn_stream",JU="get_user_list",zU="change_role",KU="update_constraint_config",qU="rebuild_pc",YU="join/v2",QU="publish/v2",XU="subscribe/v3",$U="ability_status_report",ZU="reconnect",eF="channel_msg",tF=new Set;var iF=class extends _U.default{constructor(e){var t,i;super(),BC(this,"room"),BC(this,"url"),BC(this,"backupUrl"),BC(this,"race"),BC(this,"destroyed",!1),BC(this,"_socketInUse"),BC(this,"_socket"),BC(this,"_backupSocket"),BC(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),BC(this,"_currentState","DISCONNECTED"),BC(this,"_isReconnecting",!1),BC(this,"_seq",0),BC(this,"_log"),BC(this,"_lastMessageTime",-1),BC(this,"_connnectStartTime",-1),BC(this,"_stopConnectRetry"),BC(this,"bytesSent",0),BC(this,"bytesReceived",0),BC(this,"keepAlive",!1),BC(this,"signalDomainWhenUnifiedProxy"),BC(this,"stopKeepAliveTimeout"),BC(this,"rtt",0),this.room=e.room,this.race=!!Aw(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-tF.size>0&&this.room.enableSPC&&(this.keepAlive=!0,tF.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=cO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=Vw();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield xw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?Fb.BACKUP:Fb.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(r?Fb.MAIN:Fb.BACKUP),t(new ib({code:eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===Fb.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(pk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(pk){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit(vU,new ib({code:eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(Fb.MAIN),this.unbindAndCloseSocket(Fb.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(vU,new ib({code:eb.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=$w(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(SU),o=Object.keys(SU)[n.indexOf(i)],s=AU[o]||i;switch(IU.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case SU.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){rb=e-(new Date).getTime();let t=new Date;t.setTime(e),cO.info("baseTime from server: ".concat(t," offset: ").concat(rb))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(Vw()-this._connnectStartTime)),RO.addSuccessEvent({key:521701,cost:Vw()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(fU,{signalInfo:this._signalInfo});else{let e=new ib({code:eb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:UN({key:qk.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),RO.addFailedEvent({key:521701,error:e}),this.emit(vU,e)}break;case SU.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return jC(this,null,(function*(){try{if(!this.room.joinParams)return;YN(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(ub){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?Fb.MAIN:Fb.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return jC(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:ZU,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:AU.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),RO.addSuccessEvent({key:521702,cost:Vw()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(RO.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(ub){this._log.error(ub),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),this.bytesSent+=$w(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new ib({code:eb.API_CALL_TIMEOUT,message:UN({key:qk.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),r),d=t=>{t.data.seq===u&&(clearTimeout(l),this.off(n,d),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,d);let u=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return WN({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(TU,t))},onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),tF.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(Fb.MAIN),this.unbindAndCloseSocket(Fb.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(AU.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(AU.JOIN_ROOM_RESULT,t))};this.on(AU.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(gU,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(TU):"DISCONNECTED"===e&&this.emit(yU))}};FC([FP({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],iF.prototype,"connect",1);var rF=UC(WC()),nF=0,oF=!1,sF=new Set,aF=!1,cF=class{constructor(e){BC(this,"userId"),BC(this,"tinyId"),BC(this,"_sdpSemantics"),BC(this,"_isUplink"),BC(this,"_room"),BC(this,"_log"),BC(this,"_signalChannel"),BC(this,"_isErrorObserved",!1),BC(this,"_waitForPeerConnectionConnectedPromise"),BC(this,"_waitForPeerConnectionConnectedPromiseReject",null),BC(this,"_peerConnection",null),BC(this,"_emitter",new rF.default),BC(this,"_currentState","DISCONNECTED"),BC(this,"_isReconnecting",!1),BC(this,"_reconnectionCount",0),BC(this,"_reconnectionTimer",-1),BC(this,"_isFirstConnection",!0),BC(this,"_prevTime",-1),BC(this,"_localAddress"),BC(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=cO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Vw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,RO.addSuccessEvent({key:521705,cost:Math.min(Vw()-this._prevTime,3e4)})):this._isReconnecting&&RO.addSuccessEvent({key:521706,cost:Vw()-this._prevTime}),this._prevTime=-1}catch(mO){throw this._isFirstConnection?(this._isFirstConnection=!1,RO.addFailedEvent({key:521705,error:mO})):this._isReconnecting&&this._reconnectionCount>=3&&RO.addFailedEvent({key:521706,error:mO}),mO}}initialize(){let e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),sF.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new ib({code:eb.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ck;let e=null;if(this._isUplink){if(!QO()||0===this._peerConnection.getSenders().length)return ck;e=this._peerConnection.getSenders()[0].transport}else{if(!YO()||0===this._peerConnection.getReceivers().length)return ck;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:ck}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===lk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===lk.FAILED||e.target.connectionState===lk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new ib({message:r,code:eb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===lk.CONNECTED||e.target.connectionState===lk.COMPLETED)&&(this.logSelectedCandidate(),zN.logSuccessEvent({userId:this._room.userId,eventType:_k.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(nF=0,oF=!1,aF=!0,sF.add(this)):sF.delete(this),GN.emit(sO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return jC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(jO(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{GN.off(sO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new ib({code:eb.API_CALL_TIMEOUT,message:"connection timeout"});nF+=1,(e=>nF>2&&!oF&&0===sF.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),oF=!0,this._emitter.emit("firewall-restriction")),t(e)}),bk);GN.on(sO.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(TU,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=hk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new ib({code:this._isUplink?eb.UPLINK_RECONNECTION_FAILED:eb.DOWNLINK_RECONNECTION_FAILED,message:UN({key:this._isUplink?qk.UPLINK_RECONNECTION_FAILED:qk.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(TU,this.reconnect,this),-1)}on(e,t,i){this._emitter.on(e,t,i)}off(e,t,i){this._emitter.off(e,t,i)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}setOffer(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}};FC([dL(521712,!1)],cF.prototype,"setOffer",1),FC([dL(521713,!1)],cF.prototype,"setAnswer",1);var lF=UC(XC()),dF=function(e){return lF.default.parse(e)},uF=function(e){return lF.default.write(e)};function hF(e){return Object.keys(e).filter((t=>e[t]))}var pF=class extends cF{constructor(e){super(LC(MC({},e),{isUplink:!1})),BC(this,"_flag",0),BC(this,"isRobot",!1),BC(this,"role","anchor"),BC(this,"remoteAudioTrack"),BC(this,"remoteVideoTrack"),BC(this,"remoteAuxiliaryTrack"),BC(this,"ssrc",{audio:0,video:0,auxiliary:0}),BC(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new DL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new kx(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Dx(this._room,this)}get videoCodec(){var e,t;let i=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return i?i.includes("H264")?"h264":"vp8":"h264"}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 jw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Fb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===Xb?Fb.MAIN:Fb.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=Fb.AUDIO;i.kind===Fb.VIDEO&&(n=r===Fb.MAIN?Fb.VIDEO:Fb.AUXILIARY);let o=this.remoteAudioTrack;n===Fb.VIDEO?o=this.remoteVideoTrack:n===Fb.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,r)=>{/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&i.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let r=[...i];for(let n=0;n<r.length;n++){let[e,i]=r[n];t.splice(e+n,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=dF(e);return t.media.forEach((e=>{e.type===Fb.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),uF(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],i=dF(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),uF(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return jC(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===lk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===lk.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(pb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(pb.message," ").concat(JSON.stringify(this.muteState))),new ib({code:eb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):pb}}))}unsubscribe(e){return jC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(r," stream already unsubscribed"));let e=MC({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(r," [").concat(hF(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=MU,n=AU.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=LU,n=AU.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:r,data:i,responseCommand:n,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new ib({code:i.code,message:UN({key:qk.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(pk){throw e.closePeerConnection(!0),pk}}()}))}exchangeSDP(e){return jC(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,r={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:PU,commandDesc:"exchange sdp",data:r,responseCommand:AU.SUBSCRIBE_RESULT,timeout:Tk});if(!this._peerConnection){let e=new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(pk){throw this._isSDPExchanging=!1,pk}}))}createOffer(){return jC(this,null,(function*(){let e={voiceActivityDetection:!1};$O()&&this._sdpSemantics===Ek?(this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Bb.RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Bb.RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Bb.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield xO();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=dF(e);return t.media.forEach((e=>{var t,i;if(e.type===Fb.VIDEO){let r=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&r.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,n=i.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));let n=e=>{let{payload:t}=e;return!r.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!r.has(Number(e)))).join(" ")}})),uF(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=dF(e);return t.media.forEach((e=>{e.type===Fb.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),uF(t)}(t.sdp),this._sdpSemantics===Ek&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return jC(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===yk)throw new ib({code:eb.NOT_SUPPORTED_H264,message:UN({key:qk.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new ib({code:t,message:UN({key:qk.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:r,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{dF(e).media.forEach((e=>{if(e.ssrcs)if(e.type===Fb.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Xb)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(Xb)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes($b)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(pk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return jC(this,null,(function*(){if(!(HC(pF.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(pk){let t=yw(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}get audioReceiver(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}},mF=pF;FC([tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],mF.prototype,"subscribe",1),FC([dL(521717,!1)],mF.prototype,"unsubscribe",1),FC([eL(cF.prototype.afterConnect),ZM(cF.prototype.beforeConnect)],mF.prototype,"connect",1);var _F=mF,fF={voiceActivityDetection:!1},gF=class extends cF{constructor(e){super(LC(MC({},e),{isUplink:!0})),BC(this,"localMainAudioTrack",null),BC(this,"localMainVideoTrack",null),BC(this,"localAuxAudioTrack",null),BC(this,"localAuxVideoTrack",null),BC(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),BC(this,"_isPublishingAux",!1),BC(this,"_publishingLocalAudioTrack"),BC(this,"_publishingLocalVideoTrack"),BC(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),BC(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(XO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Fb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),$O()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i)):(r&&(t.localMainVideoTrack=r),i&&(t.localMainAudioTrack=i)),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==r?void 0:r.outMediaTrack,a=null==i?void 0:i.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||Fb.AUDIO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?Fb.VIDEO:s||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||Fb.VIDEO,{direction:Bb.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:Fb.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:Fb.VIDEO,videoType:o?Fb.AUXILIARY:Fb.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:Fb.VIDEO,videoType:Fb.SMALL}),e.push(2))}yield t.setTransceiverDirection(Bb.SENDONLY,e),yield t.doPublishChange(),null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==r?void 0:r.outMediaTrack,o=null==i?void 0:i.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return i&&o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(r)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return jC(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Bb.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Bb.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!XO())return i&&i.outMediaTrack&&!r&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):r&&r.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(r),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),void t.emitConnectionStateChangedEvent("DISCONNECTED",r));let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=LC(MC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=LC(MC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(Bb.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:wU,data:t,responseCommand:AU.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:OU,commandDesc:"unpublish",responseCommand:AU.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===eb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),oP){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:KU,data:this._mediaSettings,responseCommand:AU.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),$O()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return jC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Bb.INACTIVE&&(yield this.setTransceiverDirection(Bb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return jC(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;XO()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let i=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(i&&i.track){this._log.warn("sender already exists, remove sender first");let e=i.track;this.removeSender(i),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===Fb.VIDEO&&e instanceof gL&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===vk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=dF(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===Fb.VIDEO)return!0;return!1}removeSender(e){let t=null;XO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&Iw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),$O()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return jC(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),1===r&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Bb.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return jC(this,null,(function*(){if(!hD)return;let i=!1,r=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(Bb.INACTIVE,"|").concat(Bb.RECVONLY,"|").concat(Bb.SENDONLY,")")))&&o++,t.includes(o)){if(e===Bb.INACTIVE&&i.includes("a=".concat(Bb.RECVONLY)))return r=!0,"a=".concat(e);if(e===Bb.SENDONLY&&i.includes("a=".concat(Bb.INACTIVE)))return r=!0,"a=".concat(Bb.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return jC(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===Fb.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===Fb.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===Fb.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return jC(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return!1;if(i=$O()?e.kind===Fb.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?Fb.AUXILIARY:Fb.MAIN," stream")),e.kind===Fb.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===Fb.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return jC(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(fF);hD&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this.setOffer(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===Fb.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:r,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:RU,data:n,responseCommand:AU.UPDATE_OFFER_RESULT,timeout:gk,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(hb){throw this._log.error(hb),hb}}))}setBandwidth(e){return jC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!rP())return o?r===Fb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if($O()){let t=0;r===Fb.VIDEO&&(t=n===Fb.SMALL?2:n===Fb.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===r));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(r," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return r===Fb.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";hD&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===Fb.SMALL?n=1:i===Fb.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return hD&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return jC(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(ub){throw this.closePeerConnection(!0),this.uninstallEvents(),ub}}))}exchangeSDP(){return jC(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(ub){throw ub}}))}createOffer(){return jC(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(fF);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(ub){throw ub}}))}doExchangeSDP(){let e={command:NU,responseCommand:AU.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof yL||this.localAuxVideoTrack instanceof yL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:r}=e.data;return 0===t?this.acceptAnswer(r):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=dF(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),uF(r)}acceptAnswer(e){return jC(this,null,(function*(){var t,i,r,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(r=this._publishingLocalAudioTrack)?void 0:r.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?Fb.AUXILIARY:Fb.BIG;s=yield this.setBandwidth({bandwidth:e,type:Fb.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:Fb.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:Fb.VIDEO,videoType:Fb.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(uB){throw this._log.error("failed to accept remote answer ".concat(uB)),uB}}))}sendMutedFlag(e){var t,i,r;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(DU,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return jC(this,null,(function*(){if(!(HC(gF.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:OU,responseCommand:AU.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(pk){let t=yw(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&GN.emit(sO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{dF(e).media.forEach(((e,t)=>{if(e.type===Fb.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===vk&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(pk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Fb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Fb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Fb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Fb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===yk?(this._log.error(Yk.NOT_SUPPORTED_H264ENCODE),new ib({code:eb.NOT_SUPPORTED_H264,message:UN({key:qk.NOT_SUPPORTED_H264ENCODE})})):new ib({code:eb.UNKNOWN,message:UN({key:qk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:AU.PUBLISH_RESULT,code:e,message:t}})})}},TF=gF;FC([tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this._emitter.off("closed",n),r(new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],TF.prototype,"publish",1),FC([dL(521715,!1)],TF.prototype,"unpublish",1),FC([eL(cF.prototype.afterConnect),ZM(cF.prototype.beforeConnect)],TF.prototype,"connect",1);var EF=TF,vF=class{constructor(e,t){this.room=e,BC(this,"_log"),BC(this,"_prevReportTime",0),BC(this,"_prevReport",{}),BC(this,"_prevStats",null),BC(this,"_prevEncoderImplementation",""),BC(this,"_prevAuxEncoderImpl",""),BC(this,"_prevQualityLimitationReason",""),BC(this,"_prevAuxQualityLimitationReason",""),BC(this,"_prevDecoderImplementationMap",new Map),BC(this,"totalBytesSent",0),BC(this,"totalBytesReceived",0),BC(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return jC(this,null,(function*(){var t;let i={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=e.getPeerConnection(),n=e.getSSRC();if(r)try{if((this._spcStats||(yield r.getStats())).forEach((t=>{var r,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===Fb.VIDEO){if(t.ssrc===n.video?(a=Fb.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=Fb.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=Fb.AUXILIARY),!a)return;if(i[a].bytesSent=t.bytesSent,i[a].packetsSent=t.packetsSent,i[a].framesEncoded=t.framesEncoded,Aw(t.keyFramesEncoded)||(i[a].keyFramesEncoded=t.keyFramesEncoded),Aw(t.nackCount)||(i[a].nackCount=t.nackCount),Aw(t.pliCount)||(i[a].pliCount=t.pliCount),Aw(t.retransmittedPacketsSent)||(i[a].retransmittedPacketsSent=t.retransmittedPacketsSent),Aw(t.totalEncodeTime)||(i[a].totalEncodeTime=t.totalEncodeTime),Aw(t.totalPacketSendDelay)||(i[a].totalPacketSendDelay=t.totalPacketSendDelay),!Aw(t.encoderImplementation)&&(a===Fb.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===Fb.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let i=2,r=this._prevEncoderImplementation;a===Fb.AUXILIARY&&(i=7,r=this._prevAuxEncoderImpl),GN.emit("262",{userId:e.userId,streamType:i,prevImplementation:r,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===Fb.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===Fb.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!Aw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),GN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(r=e.localMainVideoTrack)?void 0:r.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!Aw(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),GN.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else i.audio.bytesSent=t.bytesSent,i.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?jO(t)&&(this.totalBytesSent=t.bytesSent,Cw(t.currentRoundTripTime)&&(i.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===Fb.AUDIO?(i.audio.audioLevel=t.audioLevel||0,i.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(i.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===Fb.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(Fb.VIDEO)?i.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(Fb.AUXILIARY)?i.auxiliary.fpsCapture=t.framesPerSecond:i.small.fpsCapture=t.framesPerSecond));if(!Aw(t.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(i.audio.audioLevel=t.audioLevel||0),!Aw(t.frameWidth)){let r=Fb.SMALL;t.trackIdentifier===e.getVideoTrackId(Fb.VIDEO)||t.ssrc===n.video?r=Fb.VIDEO:(t.trackIdentifier===e.getVideoTrackId(Fb.AUXILIARY)||t.ssrc===n.auxiliary)&&(r=Fb.AUXILIARY),i[r].frameWidth=t.frameWidth,i[r].frameHeight=t.frameHeight,i[r].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();i.audio.micAudioLevel=t,0===i.audio.audioLevel&&(i.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=i.audio.bytesSent+i.video.bytesSent+i.auxiliary.bytesSent),Object.keys(i).forEach((t=>{t===Fb.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=i[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=i[t])):t===Fb.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=i[t]):t===Fb.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=i[t])}))}catch(pb){this._log.warn("failed to getStats on sender connection ".concat(pb))}return 0===i.rtt&&(i.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),i}))}getReceiverStats(e){return jC(this,null,(function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},o=e.getPeerConnection();if(o)try{let{ssrc:r}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let i=(t.mediaType||t.kind)===Fb.AUDIO;if(i){if(t.ssrc!==r.audio||!s.hasAudio)return;n.audio.packetsReceived=t.packetsReceived,n.audio.bytesReceived=t.bytesReceived,n.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(n.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(n.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(n.audio.concealedSamples=t.concealedSamples);let{remoteAudioTrack:i}=e;i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,n.audio.p2pDelay=i.stat.end2EndDelay,n.hasAudio=!0}else{if(hD&&0===t.bytesReceived)return;let i;t.ssrc===r.video&&s.hasVideo&&(n.video.packetsReceived=t.packetsReceived,n.video.bytesReceived=t.bytesReceived,n.video.packetsLost=t.packetsLost,n.video.framesReceived=t.framesReceived,n.video.framesDecoded=t.framesDecoded,n.video.fpsDecoded=t.framesPerSecond,n.hasVideo=!0,i=e.remoteVideoTrack,s.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),GN.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,n.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)))}t.jitterBufferDelay&&(i?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===r.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&jO(t)&&(this.totalBytesReceived=t.bytesReceived,Cw(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));Aw(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===r.video)&&(n.video.frameWidth=t.frameWidth,n.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===r.auxiliary)&&(n.auxiliary.frameWidth=t.frameWidth,n.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!Aw(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=t.audioLevel||0,n.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===n.audio.audioLevel&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),Aw(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),Aw(null==(i=e.remoteAuxiliaryTrack.player.stat)?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(s){this._log.warn("failed to getStats on receiver connection ".concat(s))}return 0===n.rtt&&(n.rtt=(null==(r=this.room.networkQuality)?void 0:r.uplinkRTT)||0),n}))}getStats(e,t){return jC(this,null,(function*(){let i={},r=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:r};let t=Vw(),n=yield e.getStats(),o=Vw();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(i=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);r.push(e)}return{senderStats:i,receiverStats:r}}))}getDifferenceValue(e,t){if(KM(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;var n;if(!KM(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*Kk,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*Kk),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let r=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};r.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};r.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};r.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:r,msg_network_status:n}}let{statInterval:o}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=r.get("".concat(e.userId,"_").concat(Zb)),n=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(ek)),n=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let s=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let e=s.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=s.msg_device_info)&&n.uint32_audio_capture_cost?i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(s.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/o):delete i.msg_device_info.uint32_audio_capture_cost}let c=s.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=c.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,n=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let a=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/o),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/o),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/o),jD&&115===aN()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),Aw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),Aw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),Aw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),Aw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),Aw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),Aw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/o))}));let l=s.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let d=i.msg_down_stream_info;return d.forEach((e=>{let t=l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(KM(e.msg_audio_status)||KM(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,n=this.getDifferenceValue(r.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms_count);delete i.uint32_audio_cache_ms_count,i.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(r.uint32_audio_cache_ms,i.uint32_audio_cache_ms)/n)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(r.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(r.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let a=this.getDifferenceValue(r.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*a/o),i.uint32_audio_total_bitrate=Math.round(8*a/o)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),r=t.uint32_video_receive,n=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(r,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/o);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/o),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/o);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),a&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=a.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let i=e.audio.concealedSamples-t.audio.concealedSamples,r=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(i/r*1e3*o);if(n>1e3*o/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),i}getStatsReport(e){return jC(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,r);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},yF=UC(WC());function SF(e){return new Promise((t=>jC(this,null,(function*(){let i=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch(pb){}clearTimeout(i);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let i=performance.getEntriesByType("resource").reverse();for(let r of i)if(r.name===e){let e=Math.round(r.duration),i=Math.max(Math.round(r.domainLookupStart-r.startTime),0),n=r.redirectStart>0?Math.max(Math.round(r.redirectEnd-r.redirectStart),0):0,o=r.fetchStart>0?Math.max(Math.round(r.domainLookupStart-r.fetchStart),0):0,s=Math.round(r.domainLookupEnd-r.domainLookupStart),a=Math.round(r.requestStart-r.secureConnectionStart),c=Math.round(r.secureConnectionStart-r.connectStart),l=Math.round(r.responseStart-r.requestStart),d=Math.round(r.responseEnd-(r.responseStart||r.startTime));t=LC(MC({},t),{totalCost:e,local:i,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(i){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-r),t(o)}))))}var IF=class extends yF.default{constructor(e){let{signalChannel:t,room:i}=e;super(),BC(this,"_room"),BC(this,"_signalChannel"),BC(this,"_log"),BC(this,"uplinkRTT",0),BC(this,"uplinkLoss",0),BC(this,"downlinkRTT",0),BC(this,"downlinkLoss",0),BC(this,"pingResults",{}),BC(this,"_downlinkPrevStatMap",new Map),BC(this,"_downlinkLossAndRTTMap",new Map),BC(this,"_interval",-1),BC(this,"_uplinkNetworkQuality",0),BC(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=cO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(AU.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(gU,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=r.expectAudPkg+r.expectVidPkg,s=r.recvAudPkg+r.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return jC(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===lk.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:r,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=r-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:r,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=i,this.downlinkLoss=r,this.downlinkNetworkQuality=this.getNetworkQuality(r,i)}))}getStat(e){return jC(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!YO())return t;let i=e.getReceivers();try{for(let e=0;e<i.length;e++)(yield i[e].getStats()).forEach((e=>{"candidate-pair"===e.type&&Cw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===Fb.AUDIO||e.mediaType===Fb.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(r){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==lk.DISCONNECTED&&e.connectionState!==lk.FAILED&&e.connectionState!==lk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=OP.run(Fk,(()=>{var e;this.handleDownlinkNetworkQuality();let t=[...this._downlinkLossAndRTTMap.values()];GN.emit(sO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:t});let i=null==(e=this._room.scheduleResult.config)?void 0:e.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};i&&(r=LC(MC({},r),{pingResults:this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold?this.pingResults:{}})),this.emit(IF.EVENT_NETWORK_QUALITY,r);let n=Date.now();if(i&&(this.uplinkRTT>i.rttThreshold||this.downlinkRTT>i.rttThreshold)&&n-IF.lastPingTime>1e3*i.interval){IF.lastPingTime=Date.now();let e=i.domain.map((e=>SF(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(e).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=n,this.pingResults.data=e,e.forEach((e=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(OP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:r,audioDelay:n}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:r,audioDelay:n})}}))}},AF=IF;BC(AF,"EVENT_NETWORK_QUALITY","0"),BC(AF,"lastPingTime",0);var RF=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._eventMap=new Map,this._captureCostSum=0,this._captureCostCount=0,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=cO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&Iw(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];let o=t.apply(i,r);return Ow(o)?o.catch((e=>cO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(pk){cO.error("".concat(t.name,"() error observed ").concat(pk))}}}({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:lb,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,kN().then((e=>{this._basicInfo.string_os_version=PN(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),GN.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(sO.JOIN_START,this.handleJoinStart).addEvent(sO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(sO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(sO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(sO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(sO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(sO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(sO.JOIN_FAILED,this.handleJoinFailed).addEvent(sO.LEAVE_START,this.handleLeaveStart).addEvent(sO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(sO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(sO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(sO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(sO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(sO.PUBLISH_START,this.handlePublishStart).addEvent(sO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(sO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(sO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(sO.PLAY_TRACK_START,this.handlePlayStart).addEvent(sO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(sO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!ww(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===Fb.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(sO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(sO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(sO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(sO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(r.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")})).addEvent(sO.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)}))}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach(((e,t)=>GN.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),OP.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&&(Aw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Aw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),Aw(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:r,tcp:n,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=r,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof ib?Number(i.getExtraCode()||i.getCode()):eb.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:LC(MC({},bF),{msg_user_info:new kF({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new kF({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(r),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===r?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(r),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!ww(t)||!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(!ww(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(r&&(0===r.statsToReport.uint64_render_first_frame_time&&(r.statsToReport.uint64_render_first_frame_time=i),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-r.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:r}=n;0===e.uint32_video_render_first&&t-r<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:r,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(s)s.totalRTT+=t,s.totalLoss+=i,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:i,msg_down_stream_info:r}=e.report;if(i.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:r,uint32_video_height:n}=i.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(i.msg_audio_status){let{uint32_audio_level:e}=i.msg_audio_status;Math.floor(e/Kk*100)>0&&(this._localStreamStat.totalAudioLevel+=e/Kk,this._localStreamStat.audioLevelCount++)}r.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:r}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(r.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,r="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(r);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*OC(10,6)))}})),i){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/Kk*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/Kk,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof ib?i.getExtraCode()||i.getCode():eb.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&Wb))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&zb))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&Jb))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:t,count:i,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,Fb.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,Fb.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,CF);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>CF&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+CF):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>CF&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+CF):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>CF&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+CF)}getReportData(){this._basicInfo.uint32_networkType=uw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new kF({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Gw(this._signalInfo.relayIp),uint32_client_ip:Gw(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*OC(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:Gw(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return iO(e),e}report(){return jC(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(mO){this._log.warn(mO)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return jC(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),i=yield zk(e),r=i instanceof ArrayBuffer,n="".concat(sw(t,kb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i));let s=[this.uploadKVStat(RO),this.uploadKVStat(AO)];o||s.push(Jk({url:n,body:i})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return jC(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=LC(MC({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let i=yield zk(t),r="".concat(sw(+this._room.sdkAppId,kb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||Jk({url:r,body:i})}))}};FC([FP({settings:{timeout:500,retries:3}})],RF.prototype,"upload",1);var CF=5e3,bF={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},kF=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},DF=RF,NF=class{constructor(){BC(this,"_startTime"),BC(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Vw())}stop(){0===this._endTime&&(this._endTime=Vw())}getDuration(){return 0===this._endTime?Vw()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},wF=class{constructor(e){BC(this,"_room",null),BC(this,"_durationMap"),BC(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(sO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(sO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(sO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:o}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),Fb.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),Fb.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),Fb.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,Fb.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,Fb.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,Fb.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>GN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>GN.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);if(r.muteState.hasAudio&&"main"===i)if(r.remoteAudioTrack.isSubscribed){let e=new NF,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,Fb.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new NF,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,Fb.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDurationItem(o,Fb.AUDIO),this.stopDurationItem(o,Fb.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new NF,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===Fb.AUDIO?[n]:[],video:t===Fb.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},OF=class{constructor(e){BC(this,"_room"),BC(this,"_renderFreezeMap",new Map),BC(this,"_isVideoPlayingEventFiredMap",new Map),BC(this,"_dataFreezeMap",new Map),BC(this,"_monitorFreezeData",new Map),BC(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(sO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(sO.PLAY_TRACK_START,this.onPlayTrackStart).set(sO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,o="".concat(n,"_").concat(i);this.stopDataFreeze({key:o,userId:n,type:i})})).set(sO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let e="main",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}if(i.hasAuxiliary&&!r.hasAuxiliary){let e="auxiliary",t="".concat(r.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}})).set(sO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(ww(t)&&this.hitTest(t.room)&&n===Fb.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===Fb.MUTE?this.onVideoTrackMuted(t):r===Fb.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(sO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>GN.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>GN.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),o=new NF;n?n.durationItemList.push(o):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:r}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&r.hasVideo&&!r.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&r.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>Ik?this._monitorFreezeData.set(t,{userId:i,type:r,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return jC(this,arguments,(function(e){var t=this;let{userId:i,fps:r,type:n}=e;return function*(){let e="".concat(i,"_").concat(n),o=t._renderFreezeMap.get(e);if(r<=2){let r=Vw();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:r,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:n,isFreeze:!0,freezeTimeline:[{startTime:r,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=Vw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!ww(t)||!this.hitTest(t.room)||t.kind!==Fb.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<Ik&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,r=0;if(t)if(t.isFreeze){let e=Vw()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),r=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},PF=UC(WC(),1),MF=[1,0,0,0,1,1,0,1],LF=class extends OL{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof Cx)try{this.setTexBuffer(MF)}catch(pk){e.destroy(new ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(pk.message||pk)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},xF=class{constructor(e,t){this.node=e,this.layout=t,BC(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}},VF=class extends OL{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),BC(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new xF(e,t);this.inputs[t.zIndex]=i}resize(e,t){let i=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(i.width,i.height),this.context instanceof Cx&&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.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:s,fps:a,name:o},MC({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof Cx))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(r){}}))}},UF=class extends Ix{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),BC(this,"_bgTexture"),BC(this,"_waterMarkTexture"),BC(this,"_lastMaskTexture"),BC(this,"_lastMaskFbo"),BC(this,"_textureValid",!1),BC(this,"_selfieTextureValid",!1),BC(this,"_selfieSegmentation"),BC(this,"wasm"),BC(this,"_prePrograme"),BC(this,"_segmentationMask"),BC(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(hb){e.log.error(hb),e.destroy(new ib({code:eb.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(hb.message||hb)}))}}init(e){var t,i;let r=e.Wasm,n=this.context.ctx;if(this.wasm=new r.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(e.beautyParams){let{beauty:r,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(r,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(i=this.context._canvas)?void 0:i.height)}if(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)),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)}}onPredict(e){var t;let i=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),i.activeTexture(i.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this._bgTexture||null),i.activeTexture(i.TEXTURE3),i.bindTexture(i.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),i.drawArrays(i.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,i,r,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback(s);let{videoWidth:a,videoHeight:c}=s;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(i=this._selfieSegmentation)||i.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(r=this._selfieSegmentation)||r.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},FF=class extends PF.EventEmitter{constructor(e){super(),this.room=e,BC(this,"videoContext"),BC(this,"_glVideoContext"),BC(this,"_2dVideoContext"),BC(this,"destination"),BC(this,"smallVideoContext"),BC(this,"smallDestination"),BC(this,"smallTrackSource"),BC(this,"smallImageSource"),BC(this,"_isMirror",!1),BC(this,"cameraTrack"),BC(this,"cameraNode"),BC(this,"mirrorNode"),BC(this,"mixNode"),BC(this,"screenTrack"),BC(this,"screenNode"),BC(this,"selfModel",!1),BC(this,"blurRadius",3),BC(this,"arTrack"),BC(this,"Wasm"),BC(this,"waterMarkNode"),BC(this,"_waterMarkOption"),BC(this,"watermarkImageList",[]),BC(this,"_beautyParams"),BC(this,"isUsingArTrack",!1),BC(this,"_isMixScreen",!1),BC(this,"_virtualBackground"),BC(this,"_virtualBackgroundAbortCallback"),BC(this,"virtualBackgroundInstance"),BC(this,"_bgAssetPath"),BC(this,"log",cO.createLogger({id:"vm"})),BC(this,"_checkId",0),BC(this,"_use2d",!1),BC(this,"_autoSwitchRenderMode",!0),BC(this,"_selfieSegmentation"),BC(this,"encodePipeline",[]),BC(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new bx({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new bx({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 Cx({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("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(ub){this.emit("error",ub)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=OP.run(Hk,(()=>{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(),OP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(mN||this._isMixScreen||this._isMirror||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?RO.addFailedEvent({key:t,error:e}):RO.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 Cx({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}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,settings:n,player:o}=i;r?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new vx(this.smallVideoContext,r,this.log)),this.smallVideoContext.frameRate=r.frameRate,this.smallDestination.resolution=r,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),mN&&o.setCanvas(e);let s=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),s=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(s?s.label:"no output track")),i.setOutputMediaStreamTrack(s)}catch(hb){this.log.error("set main output failed",hb)}}update(){return jC(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)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})),16===TN?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ix?(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 Ix?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)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Ex(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new UF(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new LF(this.videoContext,this.log)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new VF(this.videoContext,this.log),i.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),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof yL)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof gL)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof kx){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof yL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof gL?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof kx&&e.source&&e.source.context.destroy()}setCameraTrack(e){return jC(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return jC(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 ib({code:eb.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:i,y:n,width:o,height:s}=e;r.drawImage(t,i,n,o,s)})),eO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return jC(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return jC(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return jC(this,null,(function*(){var t,i;let r;try{r=yield eO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new ib({code:eb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:o=0,width:s=r.width,height:a=r.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:r,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return jC(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 jC(this,null,(function*(){var e,t,i;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let r=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(i=this.cameraTrack)?void 0:i.settings.height);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()}))}setVirtualBackground(e){return jC(this,null,(function*(){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 eO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}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 ib({code:eb.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._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return jC(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()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,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}},BF=0,HF=class extends bP{constructor(e){super("room"),this.seq=++BF,this.role="anchor",this.joinParams=null,this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,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}},this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=cO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,bw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),bw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),bw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new DF({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new wF({room:this}),this.badCaseDetector=new OF({room:this}),this.audioManager=new RL(this),this.videoManager=new FF(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return jC(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return jC(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return jC(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Rw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Ew(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?($N([o,o]),Tb("https://".concat(o))):(r&&Tb(r),n&&$N(n))}GN.once(sO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:XN.main,sched_back_domain:XN.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return jC(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return jC(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 jC(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 ib({code:eb.INVALID_OPERATION,message:UN({key:qk.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Yk.INVALID_DESTROY),new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.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,GN.emit(sO.ROOM_DESTROY,{room:this})}schedule(e,t){return jC(this,null,(function*(){var i,r;let n=Vw();try{let{isCached:o,result:s,detailCost:a}=yield QN({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:lb,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(Qw(s,{keysToExclude:["username","credential"]}))),o&&GN.once(sO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=MC(MC({},this.scheduleResult),s),Cw(null==(i=s.config)?void 0:i.retryCount)&&uk(s.config.retryCount),Rw(null==(r=s.config)?void 0:r.loggerDomain)&&Tb(s.config.loggerDomain),GN.emit(sO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),RO.addSuccessEvent({key:521700,cost:Vw()-n,split:50})}catch(o){throw RO.addFailedEvent({key:521700,error:o}),o}}))}},jF=UC(WC(),1),WF=Symbol("instance"),GF=Symbol("cacheResult"),JF=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,QF.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},zF=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var KF=new Map;function qF(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(r,n,o)=>{let s=i.action||n;if(!i.context){let i=KF.get(r)||[];KF.has(r)||KF.set(r,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let r=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(i.context&&(r=XF.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[GF];r.state instanceof JF&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof JF&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new zF(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not in from config"))):e!==r.state&&(l=new zF(r._state,"".concat(r.name," ").concat(s," to ").concat(t," failed: current state ").concat(r._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=r.state,u=new JF(d,t,s);QF.call(r,u);let h=e=>{var n;return r[GF]=e,u.aborted||(QF.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[GF])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(QF.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new zF(r._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var YF="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 QF(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(XF.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var XF=class extends jF.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=XF.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let r=i[WF];r?this.name=r.name+"-"+r.count++:i[WF]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=KF.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);KF.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?r.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{r.push({from:e,to:i,action:o})})):n.push({to:i,action:o})})),r.forEach((e=>{let{from:t,to:r,action:n}=e;o.add(t),o.add(r),o.add(n+"ing"),i.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),i.add("".concat(n,"ing --\x3e ").concat(r," : ").concat(n," 🟢")),i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:r}=e;i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=XF.instances.get(e),t||XF.instances.set(e,t=new XF(e,void 0,Object.create(XF.prototype)))):(t=XF.instances2.get(e),t||XF.instances2.set(e,t=new XF(e.constructor.name,void 0,Object.create(XF.prototype)))),t}static getState(e){var t;return null===(t=XF.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};YF(XF.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){QF.call(this,e)}};XF.STATECHANGED="stateChanged",XF.UPDATEAFSM="updateAFSM",XF.INIT="[*]",XF.ON="on",XF.OFF="off",XF.instances=new Map,XF.instances2=new WeakMap;var $F=UC(WC()),ZF=UC(XC());function eB(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[r].payload))[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpFb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[r].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return i}var tB=(e,t)=>jC(void 0,null,(function*(){var i;let r=dF(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(r.media[0].iceUfrag),n.ice.password=r.media[0].icePwd||"",r.fingerprint&&(n.dtls.hash=r.fingerprint.type,n.dtls.fingerprint=r.fingerprint.hash,n.dtls.setup=r.setup||""),r.media[0].fingerprint&&(n.dtls.hash=r.media[0].fingerprint.type,n.dtls.fingerprint=r.media[0].fingerprint.hash),n.dtls.setup=r.media[0].setup||"";let o=r.media[0],s=r.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channel:o.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=o.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===a.payload){let e={id:i,params:[]};r&&e.params.push(r),a.rtcpFb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...eB(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return jC(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let i=eB(dF(t.sdp).media[0]);return e.close(),i}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),iB=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=dF(r),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:Fb.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(rB({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),uF(s)},rB=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:Fb.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(i.video.decoders||i.video.codecs).forEach((e=>{nB(s,e)}));else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264"))),t=i.video.codecs[e]||r.video.codecs[0];nB(s,t)}return s},nB=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var oB=(e,t,i)=>{let r=ZF.default.parse(e);return r.media.forEach(((e,n)=>{var o;(e.type===Fb.AUDIO||e.type===Fb.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,r)=>{var n;t.push(i),e.rtcpFb&&(null==(n=e.rtcpFb[r+1])?void 0:n.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===Fb.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===Fb.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===Fb.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>nB(e,t)))):i&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(i.video.decoders||i.video.codecs).forEach((t=>nB(e,t)))))),(null==(o=e.payloads)?void 0:o.includes("datachannel"))&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),ZF.default.write(r)},sB=UC(WC()),aB=class extends sB.EventEmitter{constructor(e){super(),this.room=e,BC(this,"mainFpsHealth",1),BC(this,"mainBitrateHealth",1),BC(this,"badMainBitrateHealthCount",0),BC(this,"lastEmitBadHealthTime",0),BC(this,"log"),!cD&&cN&&GN.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:i,isHWCodec:r,codec:n}=e;if(!t&&7!==i&&"h264"===n){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let t=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(this.mainFpsHealth=t)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){let{localMainVideoTrack:t}=this.room;t&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/t.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){GN.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};BC(aB,"EVENT_BAD_HEALTH","bad_health");var cB=aB;function lB(e){let{seiMessageList:t,isAudio:i}=e;return new TransformStream({transform(e,r){let n=e;i?audioEncodePipeline.forEach((e=>{n=e({frame:n})})):videoEncodePipeline.forEach((e=>{n=e({frame:n,seiMessageList:t})})),r.enqueue(n)}})}function dB(e,t){return new TransformStream({transform(i,r){let n=i;videoDecodePipeline.forEach((i=>{n=i({frame:n,onSEI:i=>{i.forEach((i=>{self.postMessage({type:"sei",seiPayloadType:i.seiPayloadType,data:i.seiPayload.buffer,userId:e,streamType:t})}))}})})),r.enqueue(n)}})}var uB,hB=((uB=hB||{}).TRACK="track",uB.DATA_CHANNEL_MESSAGE="data_channel_msg",uB[uB.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",uB[uB.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",uB.RECONNECTED="spc-reconnected",uB.RECONNECT_FAILED="spc-reconnect-failed",uB.ERROR="error",uB.SEI_MESSAGE="sei-message",uB),pB=0,mB=!1,_B=new Set,fB=1,gB=class extends $F.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),BC(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),BC(this,"currentState","DISCONNECTED"),BC(this,"_room"),BC(this,"_signalChannel"),BC(this,"_peerConnection",null),BC(this,"_datachannel",null),BC(this,"_enableCustomMessage"),BC(this,"_log"),BC(this,"_downlinkMIDMap",new Map),BC(this,"_downlinkMIDUserIDMap",new Map),BC(this,"_reconnectionTimer",-1),BC(this,"reconnectionCount",0),BC(this,"clientAbility"),BC(this,"_serverAbility",null),BC(this,"addDownlinkQueue",new Set),BC(this,"removeDownlinkQueue",new Set),BC(this,"_parsedAnswer",null),BC(this,"_updateSDPPromise",null),BC(this,"_waitForPCConnectedPromise"),BC(this,"clearConnectTimeout"),BC(this,"_isSDPLogged",!1),BC(this,"enableInsertableStreams",!1),BC(this,"insertableStreamsAbortMap",new Map),BC(this,"scriptTransformWorker"),BC(this,"_isRelayTried",!1),BC(this,"_rttOverCount",0),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=cO.createLogger({id:"spc".concat(fB++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(aP?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var i;null==(i=this.insertableStreamsAbortMap.get(e))||i.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let i=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return i?i.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=dF(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var r;if(e.ssrcs&&!Aw(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(r=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:r.id);switch(t){case 0:i.audioSsrc=n;break;case 1:i.bigVideoSsrc=n,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=n,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=n,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){cP&&(this.scriptTransformWorker=function(e){let t=[_L],i=[FV,VV,UV,xV,lB,dB],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(i.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],i=[];self.onmessage=r=>{"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&i.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=r=>{let{options:n}=r.transformer,o=n.isReceiver?dB(n.userId,n.streamType):lB({seiMessageList:n.isMain?n.small?i:e:t});r.transformer.readable.pipeThrough(o).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return jC(this,null,(function*(){var e;let t;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime?(this.stat.iceEndTime=Date.now(),RO.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&RO.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new EB(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield tB(t.sdp,(null==(e=this._room.scheduleResult.config)?void 0:e.remove264FromSDP)||!1),yield this.setOffer(t),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),RO.addSuccessEvent({key:521707}),this.clientAbility}catch(hb){throw RO.addFailedEvent({key:521707,error:hb}),this._log.error("initialize failed ".concat(hb," \noffer: ").concat(null==t?void 0:t.sdp)),hb}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(pk){this._log.warn("setPriority error ",pk)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return jC(this,null,(function*(){var i,r;try{if("CONNECTED"===this.currentState)return;let n=Vw(),o={type:"answer",sdp:iB({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected();let s=(null==(i=this._room.scheduleResult.config)?void 0:i.priority)||(null==(r=this._room.joinParams)?void 0:r.priority)||new URLSearchParams(location.search).get("priority");s&&this.setPriority(s),t||RO.addSuccessEvent({key:521703,cost:Vw()-n})}catch(pb){let i=pb instanceof ib&&pb.code===eb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(pb),e),this.reset(),!i&&!this.isReconnecting&&(RO.addFailedEvent({key:521703,error:pb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),pb}}))}reconnect(){return jC(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(TU,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:qU,responseCommand:AU.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new ib({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),RO.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),GN.emit(sO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(ub){if(!this.isReconnecting)return;if(null!=ub&&ub.message.includes("timeout")){let e=yw(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield rO(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==ub?void 0:ub.code," ").concat(ub)),RO.addFailedEvent({key:521704,error:ub}),this.reconnectionCount>=hk()&&this._log.warn("SDK has tried reconnect for ".concat(hk()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return jC(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(TU,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===lk.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(i)),e.target.connectionState===lk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===lk.FAILED||e.target.connectionState===lk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===lk.CONNECTED||e.target.connectionState===lk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),GN.emit(sO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return ck;let e=null;return QO()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,YO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:ck):ck}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(hB.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return jC(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(jO(i)){let t=e.get(i.localCandidateId),r=e.get(i.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&dw(t.networkType)),r&&this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},r=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),n(),t(new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{GN.off(sO.LEAVE_SUCCESS,r,this),this.off(hB.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new ib({code:eb.API_CALL_TIMEOUT,message:"connection timeout"});pB+=1,(e=>pB>2&&!mB&&0===_B.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),mB=!0,this.emit(hB.FIREWALL_RESTRICTION)),t(e)}),bk);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},GN.on(sO.LEAVE_SUCCESS,r,this),this.on(hB.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return jC(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(pk){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(pk)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=Fb.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=dF(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(Fb.AUDIO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(Fb.VIDEO,{direction:Fb.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=rB({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:dF(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(r,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-audio")}],s.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(Fb.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=Fb.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(Fb.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(a.mid,i)}removeDownlink(e){return jC(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=dF(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(i=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(rP()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&r?o=r:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth: ".concat(o))}}))}setStartBitrate(e,t){var i,r;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=dF(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=dF(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=dF(this._peerConnection.remoteDescription.sdp));let s=hD?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:hD?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:hD?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:hD?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:hD?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:hD?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:hD?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:hD?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:hD?1e3*n:n}]);let a={type:"offer",sdp:uF(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(Aw(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=uF(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>jC(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(uB){this._log.error(uB),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:r,stopped:n}=e;return{mid:t,currentDirection:i,direction:r,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(uB)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return jC(this,null,(function*(){if(!hD||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach((t=>{i[t].direction!==e&&(i[t].direction=e)}));for(let r of t){let t=this._parsedAnswer.media[r].direction;e===Bb.INACTIVE&&t===Bb.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===Bb.SENDONLY&&t===Bb.INACTIVE&&(this._parsedAnswer.media[r].direction=Bb.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return dF(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:oB(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return jC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((i=>{var r;if(i.type===Fb.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(r=i.payloads)||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],nB(i,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return jC(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];Aw(t)?r=this._parsedAnswer.media.slice(1,4):2===t?r.push(this._parsedAnswer.media[1]):3===t?r.push(this._parsedAnswer.media[2]):7===t&&r.push(this._parsedAnswer.media[3]),r.forEach((t=>{var r;if(t.type===Fb.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(r=t.payloads)||!r.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],nB(t,n),i=!0)}})),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>BN(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,i),{rttRatioThreshold:s,rttThreshold:a}=(null==(r=this._room.scheduleResult.config)?void 0:r.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return jC(this,null,(function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let t=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),RO.addSuccessEvent({key:r,cost:Date.now()-t})}catch(pb){this._log.warn("switchRelay ".concat(i," failed"),pb),RO.addFailedEvent({key:r,error:pb}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,i)=>{let r=setTimeout((()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,i).finally((()=>clearTimeout(r)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};FC([cL("reconnect")],gB.prototype,"startReconnection",1),FC([lL((e=>e.userId))],gB.prototype,"addDownlink",1),FC([lL((e=>e))],gB.prototype,"removeDownlink",1),FC([aL(!0)],gB.prototype,"updateSDP",1),FC([dL(521712,!1)],gB.prototype,"setOffer",1),FC([dL(521713,!1)],gB.prototype,"setAnswer",1);var TB=class{constructor(e){BC(this,"tag"),BC(this,"len"),BC(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},EB=class{constructor(e){BC(this,"tinyId"),BC(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new TB(new Uint8Array(e).slice(i,i+2+2+n).buffer);r.push(o),i+=4+n}r.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},vB=new Set;function yB(){let e=Math.floor(4294967296*Math.random());return vB.has(e)?yB():(vB.add(e),e)}var SB=UC(WC()),IB=class extends SB.default{constructor(e){super(),BC(this,"userId"),BC(this,"tinyId"),BC(this,"_sdpSemantics"),BC(this,"_isUplink"),BC(this,"_room"),BC(this,"_log"),BC(this,"_currentState","DISCONNECTED"),BC(this,"_prevTime",-1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=cO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(GN.emit(sO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},AB=class extends IB{constructor(e){super(LC(MC({},e),{isUplink:!0})),BC(this,"localMainAudioTrack",null),BC(this,"localMainVideoTrack",null),BC(this,"localAuxAudioTrack",null),BC(this,"localAuxVideoTrack",null),BC(this,"_isPublishingAux",!1),BC(this,"_publishingLocalAudioTrack"),BC(this,"_publishingLocalVideoTrack"),BC(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),BC(this,"_flag",0),BC(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:i}=this,r=Object.keys(t).find((e=>t[e]!==i[e]));if(r){if(!e)return void(this._checkPublishStateTimeoutId=OP.run(jk,(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(r," local:").concat(t[r]," server:").concat(i[r]," ").concat(PN()," ").concat(DN())),RO.addCount({key:521e3})}OP.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,r;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(XO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(i=o[2])||!i.track),n.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((e=>{e.track&&(e.track.kind===Fb.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&zb),bigVideo:!!(this.flag&Wb),smallVideo:!!(this.flag&Gb),auxVideo:!!(this.flag&Jb)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}close(e){var t;let i=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t,i;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),null==(i=this.singlePC)||i.switchVideoEncoder("vp8")))}publish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(i&&(t._publishingLocalAudioTrack=i,h.audio=!0,p.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new ib({code:eb.NOT_SUPPORTED_H264,message:UN({key:qk.NOT_SUPPORTED_H264ENCODE})});cD&&115===aN()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(Vb["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(h.auxVideo=!0,p.auxVideo=r.muted):(h.bigVideo=!0,p.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:QU,responseCommand:AU.SPC_PUBLISH_RESULT,data:LC(MC({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=r;let{scaleResolutionDownBy:e}=r;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,r.streamType)}i&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=i),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!$O())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r,n;let o=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&o.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(o)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.singlePC.setTransceiverDirection(Bb.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;let n=this.getTrackByMediaType(t);i.enqueue((null==(r=this.singlePC)?void 0:r.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let i=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:i,isSmall:r}))}enableSmall(e){return jC(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Bb.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Bb.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return jC(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){let e=r&&r===t.localAuxVideoTrack,n=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=LC(MC({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=LC(MC({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(Bb.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:wU,data:t,responseCommand:AU.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(i.data.code,i.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:OU,commandDesc:"unpublish",responseCommand:AU.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===eb.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),oP){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:KU,data:this._mediaSettings,responseCommand:AU.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),XO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return jC(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===Bb.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Bb.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return jC(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?Fb.AUXILIARY:Fb.MAIN," stream")),XO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return jC(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===Fb.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Bb.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return jC(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!r||i.find((e=>e.track===r)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?Fb.AUXILIARY:Fb.MAIN," stream")),r.kind===Fb.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===Fb.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0}))}setBandwidth(e){return jC(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===Fb.AUDIO?e.audio=i:"big"===n?e.bigVideo=i:"small"===n?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:DU,responseCommand:AU.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&GN.emit(sO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fb.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===Fb.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===Fb.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===Fb.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===Fb.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===yk?(this._log.error(Yk.NOT_SUPPORTED_H264ENCODE),new ib({code:eb.NOT_SUPPORTED_H264,message:UN({key:qk.NOT_SUPPORTED_H264ENCODE})})):new ib({code:eb.UNKNOWN,message:UN({key:qk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:AU.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return jC(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};FC([eL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],AB.prototype,"publish",1),FC([eL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],AB.prototype,"unpublish",1);var RB=AB;function CB(e){return Object.keys(e).filter((t=>e[t]))}var bB=class extends IB{constructor(e){super(LC(MC({},e),{isUplink:!1})),BC(this,"_flag",0),BC(this,"isRobot",!1),BC(this,"role","anchor"),BC(this,"remoteAudioTrack"),BC(this,"remoteVideoTrack"),BC(this,"remoteAuxiliaryTrack"),BC(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),BC(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new DL(this._room,this),this.remoteVideoTrack=new kx(this._room,this),this.remoteAuxiliaryTrack=new Dx(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return jw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===Fb.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t;let i=e.streams[0],{track:r,receiver:n}=e;if(!i.id.includes(this.tinyId))return;let o=i.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(r.kind));let s=Fb.AUDIO;r.kind===Fb.VIDEO&&(s=o===Fb.MAIN?Fb.VIDEO:Fb.AUXILIARY);let a=this.remoteAudioTrack;s===Fb.VIDEO?a=this.remoteVideoTrack:s===Fb.AUXILIARY&&(a=this.remoteAuxiliaryTrack),null!=(t=this.singlePC)&&t.scriptTransformWorker&&this.initReceiverTransform(n,o,r.kind===Fb.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a,n),a.setInputMediaStreamTrack(r)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let i=t.createEncodedStreams(),r=new AbortController,n={abortController:r,enqueue:t=>{var i;return null!=(i=this.singlePC)&&i.isUsingH264?e.decodeFrame(t):t}};i.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let i=n.enqueue(e);i&&t.enqueue(i)}})).pipeTo(i.writable,r).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(t,r)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return jC(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(CB(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(hb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(hb.message," ").concat(JSON.stringify(this.muteState))),new ib({code:eb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):hb}}))}checkTrackEnded(e){var t,i,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(i=this.remoteVideoTrack.mediaTrack)?void 0:i.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),cN&&uN<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return jC(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:r}=e;return function*(){var e;if("main"===r&&!t.isMainStreamSubscribed||"auxiliary"===r&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(r," stream already unsubscribed"));let n=MC({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(CB(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=MU,n=AU.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=LU,n=AU.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new ib({code:i.code,message:UN({key:qk.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return jC(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:yB(),bigVideoSsrc:yB(),bigVideoRtxSsrc:yB(),auxVideoSsrc:yB(),auxVideoRtxSsrc:yB()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:XU,responseCommand:AU.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==r.data.code)throw new ib({code:r.data.code,message:r.data.message})}catch(r){throw yield e.removeDownlink(),r}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{let t=e._room.scheduleResult.config;((null==t?void 0:t.jitterDelay)||(null==t?void 0:t.jitterDelayAux))&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return jC(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((null==e?void 0:e.jitterDelay)||(null==e?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!this.singlePC||!this._peerConnection||HN(t)&&HN(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return Cw(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),Cw(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,HN(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e;try{if(0===t&&0===i)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||HN(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&HN(i)||!n&&HN(t))return;let o=n?i||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(r=null==e?void 0:e.track)?void 0:r.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!r.find((e=>{let r=e.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return e.jitterBufferTarget<r})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(pb){this._log.warn("set jitterBuffer delay error: ".concat(pb)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};FC([aL(),tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise(((t,r)=>{let n=e=>{this.off("closed",n),r(new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],bB.prototype,"subscribe",1),FC([aL()],bB.prototype,"unsubscribe",1),FC([lL((()=>"jitter"))],bB.prototype,"setJitterBufferDelay",1);var kB=bB;var DB=UC(WC());var NB=class extends DB.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,BC(this,"log"),BC(this,"cmdIdSeqMap",new Map),BC(this,"messageMap",new Map),this.log=cO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(AU.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:i}=e,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(i))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send(eF,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(e){let{data:t}=e.data,i=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(i){let e={userId:i,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),(e=>e.charCodeAt(0))).buffer};if(t.ordered){let t="".concat(i,"_").concat(e.cmdId),r=this.messageMap.get(t);if(r&&0!==r.lastSeq)if(Math.abs(r.lastSeq-e.seq)>NB.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>r.lastSeq){if(e.seq===r.lastSeq+1)this.emitMessage(e);else if(!r.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);r.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else r||(r={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,r),setTimeout((()=>this.emitMessage(e,!0)),100)),r.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(t.srcTinyId));let i=r=>{r.tinyId===t.srcTinyId&&(this.room.off("peer-join",i),this.onReceiveMsg(e))};this.room.on("peer-join",i),rO(2e3).then((()=>this.room.off("peer-join",i)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==r.lastSeq&&n.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(r.lastSeq," -> ").concat(n.seq)),r.lastSeq=n.seq,clearTimeout(null==(i=r.cachedMessageMap.get(n.seq))?void 0:i.timeoutId),r.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},wB=NB;BC(wB,"SEQ_INTERVAL",300);var{isString:OB,isUndefined:PB,getNetworkType:MB,isEmpty:LB}=sb,xB=class extends HF{constructor(e){super(e),this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this.signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=ZO,this._changeBigSmallRecords=new Map,this.forceRelay=!1,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._updateAudioLevelTaskId=-1,this._stats=new vF(this,this._log),this.userManager=new Px(this.userId,this._log),this._version=lb,this.sdpSemantics=vk,PB(e.sdpSemantics)?uO.isUnifiedPlanDefault()&&(this.sdpSemantics=Ek):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(MB())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!PB(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ZO,!PB(e.enableSPC)&&ZO&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new cB(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return jC(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var r in e)DC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&bC)for(var r of bC(e))t.indexOf(r)<0&&NC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);GN.emit(sO.REMOTE_PUBLISH_STATE_CHANGED,MC({room:this},t)),this.emit("remote-publish-state-changed",MC({},t))})),this.joinParams=e,new Promise(((t,i)=>jC(this,null,(function*(){var r,n;this._joinReject=i;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof ib&&o.code===eb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this.signalChannel)||r.destroy(),yield this.initialize()}let s=Vw();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),RO.addSuccessEvent({key:521708,cost:Vw()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(hO){RO.addFailedEvent({key:521708,error:hO}),i(hO)}this._joinReject=null}))))}))}initSinglePC(){return jC(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new gB({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(ub){throw this.fallbackToMPC(),new ib({code:eb.SPC_INITIALIZED_FAILED,message:null==ub?void 0:ub.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>jC(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(vU,(e=>{this.clearJoinTimeout(),GN.emit(sO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),bw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&ZO&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:MN(),netType:uw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new ib({code:eb.JOIN_ROOM_FAILED,message:UN({key:qk.JOIN_ROOM_TIMEOUT})}))}),c),GN.emit(sO.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?YU:CU,a),this.signalChannel.once(AU.JOIN_ROOM_RESULT,(t=>{this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;GN.emit(sO.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this.singlePC&&this.singlePC.connect(LC(MC({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),r(new ib({code:eb.JOIN_ROOM_FAILED,extraCode:n,message:UN({key:qk.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return jC(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),i.push(this.signalChannel.connect())),yield Promise.all(i),yield this.doJoin(LC(MC({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),zN.logSuccessEvent({userId:this.userId,eventType:_k.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(hB.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof RB&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(hB.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof EF&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(pk){this._log.warn("reJoin fail ".concat(pk)),this.reset(),zN.logFailedEvent({userId:this.userId,eventType:_k.REJOIN,error:pk}),this.emit("error",new ib({code:eb.JOIN_ROOM_FAILED,message:UN({key:qk.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return jC(this,null,(function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||function(e){let t=[...tF.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(r&&r.isConnected&&r.keepAlive);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this.signalChannel=r):(this.signalChannel=new iF({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new wB(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new AF({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(AF.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),xP(this,this.signalChannel).add(gU,(e=>{GN.emit(sO.SIGNAL_CONNECTION_STATE_CHANGED,MC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(EU,(e=>{this.reset(),this.emit("error",e)})).add(AU.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(AU.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(AU.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(AU.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(zN.uploadEvent({log:"stat-banned:".concat(i),userId:this.userId}),"user_time_out"===i)return this._log.warn("".concat(i," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===i?"error":"info"]("user was banned because of [".concat(i,"]")),this.reset(),this.emit("banned",{reason:i})})),this.signalChannel.once(fU,(e=>{this.tinyId=e.signalInfo.tinyId,GN.emit(sO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),GN.emit(sO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&GN.emit(sO.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||VP(this)}leave(){return jC(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(pk){}this._log.info("leave() => leaving room"),GN.emit(sO.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(bU)}))}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=OP.run(Fk,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),OP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return jC(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(Nx.has(e)){let t=Nx.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 Nx.delete(e),t}return[]}(this.userId):[],n=LC(MC({str_sdk_version:cb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:MC({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:uw()},i.msg_device_info)});if(this.heartbeatReport=n,GN.emit(sO.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(kU,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",LC(MC({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==Qb)).map((e=>{let{userId:t,srcTinyId:i,flag:r}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=r);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:i,flag:r}}));e.data.mixRobotList.forEach((e=>{let{userId:i,srcTinyId:r,flag:n,mixUserList:o}=e;t.unshift({userId:i,tinyId:r,flag:n,isRobot:!0,mixUserList:o})})),GN.emit(sO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof EF&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n}=e,o=new(this.singlePC?kB:_F)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==eb.ICE_TRANSPORT_ERROR&&(i===eb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",LC(MC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=OP.run(Fk,this.syncUserList.bind(this)))}stopSyncUserListInterval(){OP.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this.signalChannel)&&e.isConnected?this.signalChannel.sendWaitForResponse({command:JU,responseCommand:AU.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:r}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:r}=e;return{userId:t,tinyId:i,role:r}}));throw UN({key:qk.SIGNAL_RESPONSE_FAILED,data:{signalResponse:AU.USER_LIST_RES,code:i,message:r}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!aF)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===lk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof cF&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===lk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return jC(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),zN.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new EF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let t of[...this.remotePublishedUserMap.values()]){let e=new _F({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.subscribeState,"auxiliary"))}}))}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),OP.clearTask(this._audioVolumeIntervalId))}switchRole(e){return jC(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:zU,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:AU.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:r}=t.data;if(0!==i)throw new ib({code:eb.SWITCH_ROLE_FAILED,message:UN({key:qk.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof ib&&e.getCode()===eb.API_CALL_TIMEOUT&&(e=new ib({code:eb.SWITCH_ROLE_FAILED,message:UN({key:qk.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof mL&&(t instanceof SL?i.audio=t:e.audio=t),t instanceof gL&&(t instanceof yL&&2===t.mediaType?i.video=t:e.video=t)}));let r=LB(e),n=LB(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new RB({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new EF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",LC(MC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==eb.ICE_TRANSPORT_ERROR&&(t===eb.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");r||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof mL&&(t instanceof SL?i.audio=t:e.audio=t),t instanceof gL&&(t instanceof yL&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");LB(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),LB(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(r){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&iP()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&GN.emit(sO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return jC(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return jC(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:Fb.VIDEO,videoType:Fb.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=MC({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),GN.emit(sO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(hF(n),"] prev: [").concat(hF(i.subscribeState),"]")),yield i.subscribe(n,r),this._log.info("subscribe ".concat(e," ").concat(r," done"));for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());GN.emit(sO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(pb){let i=pb instanceof ib?pb.getCode():eb.UNKNOWN,n=pb;throw pb instanceof ib?i===eb.REMOTE_STREAM_NOT_EXIST&&(n=new ib({code:eb.API_CALL_ABORTED,message:UN({key:qk.API_CALL_ABORTED,data:{message:pb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new ib({code:i,message:UN({key:qk.SUBSCRIBE_FAILED,data:{message:pb.message,userId:e,streamType:r}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return jC(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let r=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(r));try{yield i.unsubscribe({remoteTracks:t,streamType:r})}catch(pb){this._log.warn("unsubscribe() => failed ".concat(pb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),GN.emit(sO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void OP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),GN.emit(sO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&OP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=OP.run(Bk,(()=>{var i;CM.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];null==(i=this.remotePublishedUserMap)||i.forEach((e=>{if(e.muteState.hasAudio){!CM.isRunning&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());r.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",r)}),{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return jC(this,null,(function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let r=null==(i=this.uplinkConnection.getPeerConnection())?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=OP.run(Bk,(()=>jC(this,null,(function*(){let e=yield r.getStats();this._updateAudioLevelTaskId<0||e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),OP.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!nP||!i)return;let r=null==(t=i.getSynchronizationSources()[0])?void 0:t.audioLevel;r&&(e.remoteAudioTrack.volume=Math.min(2*r,1))}getLocalAudioStats(){return jC(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return jC(this,null,(function*(){var e,t;let i={};return i[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i}))}getTransportStats(){return jC(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return jC(this,null,(function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)"main"===e&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),"auxiliary"===e&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return jC(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(sb.getTurnServer(e)))):sb.isPlainObject(e)&&i.push(sb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:BU,data:e,timeout:5e3,responseCommand:AU.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:HU,data:e,timeout:5e3,responseCommand:AU.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?xU:UU,data:e,timeout:5e3,responseCommand:t?AU.START_PUBLISH_TENCENT_CDN_RES:AU.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?VU:FU,data:e,timeout:5e3,responseCommand:t?AU.STOP_PUBLISH_TENCENT_CDN_RES:AU.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:jU,data:e,timeout:5e3,responseCommand:AU.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:WU,data:e,timeout:5e3,responseCommand:AU.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:GU,data:e,timeout:5e3,responseCommand:AU.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:$U,data:e,timeout:5e3,responseCommand:AU.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=sb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return jC(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(Vk-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=Vk}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(Vk-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Vk};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(OB(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!PB(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new ib({code:eb.INVALID_PARAMETER,message:UN({key:qk.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!PB(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new ib({code:eb.INVALID_PARAMETER,message:UN({key:qk.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!PB(e.userDefinePushArgs)){if(!(OB(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new ib({code:eb.INVALID_PARAMETER,message:UN({key:qk.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}LB(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&aP)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new ib({code:eb.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return FC([qF(["left",XF.INIT],"joined"),FP({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),YN(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),tL((e=>{let t=new pU;return function(i,r,n){return jC(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new ib({code:eb.INVALID_OPERATION,message:UN({key:qk.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===i.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),GN.emit(sO.JOIN_START,{room:this,roomId:o,params:i});let s=sb.getEnv();s||(s=Db.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Hb.OLD_CLOUD_LADDER)?s=Db.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Hb.WEBRTC)&&(s=Db.WEBRTC))),zN.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),uO.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,mU.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!sb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=sb.performanceNow(),GN.emit(sO.JOIN_SUCCESS,{room:this}),30===n&&!i.component&&zN.uploadEvent({log:"stat-conv-".concat(Number(SN),"-").concat(location.hostname),userId:this.userId}),t}catch(a){throw t.delete({room:this,roomId:o}),GN.emit(sO.JOIN_FAILED,{room:this,error:a}),a}}))}}))],xB.prototype,"join",1),FC([qF("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),tL((e=>function(){return jC(this,null,(function*(){GN.emit(sO.LEAVE_START,{room:this}),yield e.call(this),GN.emit(sO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),cL("leave room"),BP({fnName:"publish",validateArgs:!1}),BP({fnName:"unsubscribe",validateArgs:!1})],xB.prototype,"leave",1),FC([aL(),tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return jC(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;GN.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),FP({settings:{retries:hk,timeout:e=>yw(e)},onError(e,t,i){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),GN.emit(sO.PUBLISH_FAILED,{room:this}))}})],xB.prototype,"publish",1),FC([BP({fnName:"publish"}),function(e){return function(t,i,r){let n=r.value;return r.value=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let o=oL.get(this);if(o){let t=o.queue.filter(((t,r)=>{if(0===r)return!0;let n=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(n=!1)})),!n||(t.reject(new ib({code:eb.API_CALL_ABORTED,message:e})),!1)}));o.queue=t}return n.apply(this,i)},r}}("api-call"),aL(),tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>e.unpublish())),n})),eL((function(){var e,t;0===this.localTracks.size&&QO()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],xB.prototype,"unpublish",1),FC([function(e){return tL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return jC(this,null,(function*(){try{return yield t.apply(this,r)}catch(hb){e.call(this,hb)}}))}))}((e=>{if(e.code!==eb.API_CALL_ABORTED)throw e})),lL((e=>e.userId))],xB.prototype,"replaceTrack",1),FC([lL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),CL(),tL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(n))),n})),FP({settings:{retries:hk,timeout:e=>yw(e)},onError(e,t,i,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),GN.emit(sO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],xB.prototype,"subscribe",1),FC([BP({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.singlePC||t.forEach((e=>{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close("you unsubscribed")}))}}),lL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],xB.prototype,"unsubscribe",1),hU.create=hU._create.bind(hU,xB),hU}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r=function(e){try{return!!e()}catch(t){return!0}},i=!r((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),n=i,o=Function.prototype,s=o.call,a=n&&o.bind.bind(s,s),c=n?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=r,m=h,f=Object,_=c("".split),g=p((function(){return!f("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?_(e,""):f(e)}:f,v=function(e){return null==e},y=v,E=TypeError,T=function(e){if(y(e))throw E("Can't call method on "+e);return e},S=g,I=T,A=function(e){return S(I(e))},C=function(e){return e&&e.Math==Math&&e},b=C("object"==typeof globalThis&&globalThis)||C("object"==typeof window&&window)||C("object"==typeof self&&self)||C("object"==typeof t&&t)||function(){return this}()||Function("return this")(),R={},w={get exports(){return R},set exports(e){R=e}},k=b,D=Object.defineProperty,P=function(e,t){try{D(k,e,{value:t,configurable:!0,writable:!0})}catch(r){k[e]=t}return t},N=P,O="__core-js_shared__",M=b[O]||N(O,{}),L=M;(w.exports=function(e,t){return L[e]||(L[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=T,F=Object,B=function(e){return F(U(e))},j=B,H=c({}.hasOwnProperty),W=Object.hasOwn||function(e,t){return H(j(e),t)},G=c,z=0,$=Math.random(),J=G(1..toString),q=function(e){return"Symbol("+(void 0===e?"":e)+")_"+J(++z+$,36)},K="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Y=b,X=K,Q=Y.process,Z=Y.Deno,ee=Q&&Q.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var re=V,ie=re,ne=r,oe=!!Object.getOwnPropertySymbols&&!ne((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ie&&ie<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=R,ce=W,le=q,de=oe,ue=se,he=b.Symbol,pe=ae("wks"),me=ue?he.for||he:he&&he.withoutSetter||le,fe=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:me("Symbol."+e)),pe[e]},_e="object"==typeof document&&document.all,ge={all:_e,IS_HTMLDDA:void 0===_e&&void 0!==_e},ve=ge.all,ye=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===ve}:function(e){return"function"==typeof e},Ee=ye,Te=ge.all,Se=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Ee(e)||e===Te}:function(e){return"object"==typeof e?null!==e:Ee(e)},Ie=Se,Ae=String,Ce=TypeError,be=function(e){if(Ie(e))return e;throw Ce(Ae(e)+" is not an object")},Re={},we=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),ke=we&&r((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},Pe=Se,Ne=b.document,Oe=Pe(Ne)&&Pe(Ne.createElement),Me=function(e){return Oe?Ne.createElement(e):{}},Le=Me,xe=!we&&!r((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=i,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=b,je=ye,He=function(e,t){return arguments.length<2?(r=Be[e],je(r)?r:void 0):Be[e]&&Be[e][t];var r},We=c({}.isPrototypeOf),Ge=He,ze=ye,$e=We,Je=Object,qe=se?function(e){return"symbol"==typeof e}:function(e){var t=Ge("Symbol");return ze(t)&&$e(t.prototype,Je(e))},Ke=String,Ye=function(e){try{return Ke(e)}catch(t){return"Object"}},Xe=ye,Qe=Ye,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze(Qe(e)+" is not a function")},tt=et,rt=v,it=function(e,t){var r=e[t];return rt(r)?void 0:tt(r)},nt=Fe,ot=ye,st=Se,at=TypeError,ct=Fe,lt=Se,dt=qe,ut=it,ht=function(e,t){var r,i;if("string"===t&&ot(r=e.toString)&&!st(i=nt(r,e)))return i;if(ot(r=e.valueOf)&&!st(i=nt(r,e)))return i;if("string"!==t&&ot(r=e.toString)&&!st(i=nt(r,e)))return i;throw at("Can't convert object to primitive value")},pt=TypeError,mt=fe("toPrimitive"),ft=function(e,t){if(!lt(e)||dt(e))return e;var r,i=ut(e,mt);if(i){if(void 0===t&&(t="default"),r=ct(i,e,t),!lt(r)||dt(r))return r;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},_t=ft,gt=qe,vt=function(e){var t=_t(e,"string");return gt(t)?t:t+""},yt=we,Et=xe,Tt=ke,St=be,It=vt,At=TypeError,Ct=Object.defineProperty,bt=Object.getOwnPropertyDescriptor,Rt="enumerable",wt="configurable",kt="writable";De.f=yt?Tt?function(e,t,r){if(St(e),t=It(t),St(r),"function"==typeof e&&"prototype"===t&&"value"in r&&kt in r&&!r[kt]){var i=bt(e,t);i&&i[kt]&&(e[t]=r.value,r={configurable:wt in r?r[wt]:i[wt],enumerable:Rt in r?r[Rt]:i[Rt],writable:!1})}return Ct(e,t,r)}:Ct:function(e,t,r){if(St(e),t=It(t),St(r),Et)try{return Ct(e,t,r)}catch(i){}if("get"in r||"set"in r)throw At("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var Dt=Math.ceil,Pt=Math.floor,Nt=Math.trunc||function(e){var t=+e;return(t>0?Pt:Dt)(t)},Ot=Nt,Mt=function(e){var t=+e;return t!=t||0===t?0:Ot(t)},Lt=Mt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var r=Lt(e);return r<0?xt(r+t,0):Vt(r,t)},Ft=Mt,Bt=Math.min,jt=function(e){return e>0?Bt(Ft(e),9007199254740991):0},Ht=jt,Wt=function(e){return Ht(e.length)},Gt=A,zt=Ut,$t=Wt,Jt=function(e){return function(t,r,i){var n,o=Gt(t),s=$t(o),a=zt(i,s);if(e&&r!=r){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===r)return e||a||0;return!e&&-1}},qt={includes:Jt(!0),indexOf:Jt(!1)},Kt={},Yt=W,Xt=A,Qt=qt.indexOf,Zt=Kt,er=c([].push),tr=function(e,t){var r,i=Xt(e),n=0,o=[];for(r in i)!Yt(Zt,r)&&Yt(i,r)&&er(o,r);for(;t.length>n;)Yt(i,r=t[n++])&&(~Qt(o,r)||er(o,r));return o},rr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ir=tr,nr=rr,or=Object.keys||function(e){return ir(e,nr)},sr=we,ar=ke,cr=De,lr=be,dr=A,ur=or;Re.f=sr&&!ar?Object.defineProperties:function(e,t){lr(e);for(var r,i=dr(t),n=ur(t),o=n.length,s=0;o>s;)cr.f(e,r=n[s++],i[r]);return e};var hr,pr=He("document","documentElement"),mr=q,fr=R("keys"),_r=function(e){return fr[e]||(fr[e]=mr(e))},gr=be,vr=Re,yr=rr,Er=Kt,Tr=pr,Sr=Me,Ir="prototype",Ar="script",Cr=_r("IE_PROTO"),br=function(){},Rr=function(e){return"<"+Ar+">"+e+"</"+Ar+">"},wr=function(e){e.write(Rr("")),e.close();var t=e.parentWindow.Object;return e=null,t},kr=function(){try{hr=new ActiveXObject("htmlfile")}catch(t){}kr="undefined"!=typeof document?document.domain&&hr?wr(hr):function(){var e,t=Sr("iframe"),r="java"+Ar+":";return t.style.display="none",Tr.appendChild(t),t.src=String(r),(e=t.contentWindow.document).open(),e.write(Rr("document.F=Object")),e.close(),e.F}():wr(hr);for(var e=yr.length;e--;)delete kr[Ir][yr[e]];return kr()};Er[Cr]=!0;var Dr=Object.create||function(e,t){var r;return null!==e?(br[Ir]=gr(e),r=new br,br[Ir]=null,r[Cr]=e):r=kr(),void 0===t?r:vr.f(r,t)},Pr=fe,Nr=Dr,Or=De.f,Mr=Pr("unscopables"),Lr=Array.prototype;null==Lr[Mr]&&Or(Lr,Mr,{configurable:!0,value:Nr(null)});var xr,Vr,Ur,Fr=function(e){Lr[Mr][e]=!0},Br={},jr=ye,Hr=b.WeakMap,Wr=jr(Hr)&&/native code/.test(String(Hr)),Gr=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},zr=De,$r=Gr,Jr=we?function(e,t,r){return zr.f(e,t,$r(1,r))}:function(e,t,r){return e[t]=r,e},qr=Wr,Kr=b,Yr=Se,Xr=Jr,Qr=W,Zr=M,ei=_r,ti=Kt,ri="Object already initialized",ii=Kr.TypeError,ni=Kr.WeakMap;if(qr||Zr.state){var oi=Zr.state||(Zr.state=new ni);oi.get=oi.get,oi.has=oi.has,oi.set=oi.set,xr=function(e,t){if(oi.has(e))throw ii(ri);return t.facade=e,oi.set(e,t),t},Vr=function(e){return oi.get(e)||{}},Ur=function(e){return oi.has(e)}}else{var si=ei("state");ti[si]=!0,xr=function(e,t){if(Qr(e,si))throw ii(ri);return t.facade=e,Xr(e,si,t),t},Vr=function(e){return Qr(e,si)?e[si]:{}},Ur=function(e){return Qr(e,si)}}var ai={set:xr,get:Vr,has:Ur,enforce:function(e){return Ur(e)?Vr(e):xr(e,{})},getterFor:function(e){return function(t){var r;if(!Yr(t)||(r=Vr(t)).type!==e)throw ii("Incompatible receiver, "+e+" required");return r}}},ci={},li={},di={}.propertyIsEnumerable,ui=Object.getOwnPropertyDescriptor,hi=ui&&!di.call({1:2},1);li.f=hi?function(e){var t=ui(this,e);return!!t&&t.enumerable}:di;var pi=we,mi=Fe,fi=li,_i=Gr,gi=A,vi=vt,yi=W,Ei=xe,Ti=Object.getOwnPropertyDescriptor;ci.f=pi?Ti:function(e,t){if(e=gi(e),t=vi(t),Ei)try{return Ti(e,t)}catch(r){}if(yi(e,t))return _i(!mi(fi.f,e,t),e[t])};var Si={},Ii={get exports(){return Si},set exports(e){Si=e}},Ai=we,Ci=W,bi=Function.prototype,Ri=Ai&&Object.getOwnPropertyDescriptor,wi=Ci(bi,"name"),ki={EXISTS:wi,PROPER:wi&&"something"===function(){}.name,CONFIGURABLE:wi&&(!Ai||Ai&&Ri(bi,"name").configurable)},Di=ye,Pi=M,Ni=c(Function.toString);Di(Pi.inspectSource)||(Pi.inspectSource=function(e){return Ni(e)});var Oi=Pi.inspectSource,Mi=c,Li=r,xi=ye,Vi=W,Ui=we,Fi=ki.CONFIGURABLE,Bi=Oi,ji=ai.enforce,Hi=ai.get,Wi=String,Gi=Object.defineProperty,zi=Mi("".slice),$i=Mi("".replace),Ji=Mi([].join),qi=Ui&&!Li((function(){return 8!==Gi((function(){}),"length",{value:8}).length})),Ki=String(String).split("String"),Yi=Ii.exports=function(e,t,r){"Symbol("===zi(Wi(t),0,7)&&(t="["+$i(Wi(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!Vi(e,"name")||Fi&&e.name!==t)&&(Ui?Gi(e,"name",{value:t,configurable:!0}):e.name=t),qi&&r&&Vi(r,"arity")&&e.length!==r.arity&&Gi(e,"length",{value:r.arity});try{r&&Vi(r,"constructor")&&r.constructor?Ui&&Gi(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var i=ji(e);return Vi(i,"source")||(i.source=Ji(Ki,"string"==typeof t?t:"")),e};Function.prototype.toString=Yi((function(){return xi(this)&&Hi(this).source||Bi(this)}),"toString");var Xi=ye,Qi=De,Zi=Si,en=P,tn=function(e,t,r,i){i||(i={});var n=i.enumerable,o=void 0!==i.name?i.name:t;if(Xi(r)&&Zi(r,o,i),i.global)n?e[t]=r:en(t,r);else{try{i.unsafe?e[t]&&(n=!0):delete e[t]}catch(s){}n?e[t]=r:Qi.f(e,t,{value:r,enumerable:!1,configurable:!i.nonConfigurable,writable:!i.nonWritable})}return e},rn={},nn=tr,on=rr.concat("length","prototype");rn.f=Object.getOwnPropertyNames||function(e){return nn(e,on)};var sn={};sn.f=Object.getOwnPropertySymbols;var an,cn,ln,dn=He,un=rn,hn=sn,pn=be,mn=c([].concat),fn=dn("Reflect","ownKeys")||function(e){var t=un.f(pn(e)),r=hn.f;return r?mn(t,r(e)):t},_n=W,gn=fn,vn=ci,yn=De,En=function(e,t,r){for(var i=gn(t),n=yn.f,o=vn.f,s=0;s<i.length;s++){var a=i[s];_n(e,a)||r&&_n(r,a)||n(e,a,o(t,a))}},Tn=r,Sn=ye,In=/#|\.prototype\./,An=function(e,t){var r=bn[Cn(e)];return r==wn||r!=Rn&&(Sn(t)?Tn(t):!!t)},Cn=An.normalize=function(e){return String(e).replace(In,".").toLowerCase()},bn=An.data={},Rn=An.NATIVE="N",wn=An.POLYFILL="P",kn=An,Dn=b,Pn=ci.f,Nn=Jr,On=tn,Mn=P,Ln=En,xn=kn,Vn=function(e,t){var r,i,n,o,s,a=e.target,c=e.global,l=e.stat;if(r=c?Dn:l?Dn[a]||Mn(a,{}):(Dn[a]||{}).prototype)for(i in t){if(o=t[i],n=e.dontCallGetSet?(s=Pn(r,i))&&s.value:r[i],!xn(c?i:a+(l?".":"#")+i,e.forced)&&void 0!==n){if(typeof o==typeof n)continue;Ln(o,n)}(e.sham||n&&n.sham)&&Nn(o,"sham",!0),On(r,i,o,e)}},Un=!r((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fn=W,Bn=ye,jn=B,Hn=Un,Wn=_r("IE_PROTO"),Gn=Object,zn=Gn.prototype,$n=Hn?Gn.getPrototypeOf:function(e){var t=jn(e);if(Fn(t,Wn))return t[Wn];var r=t.constructor;return Bn(r)&&t instanceof r?r.prototype:t instanceof Gn?zn:null},Jn=r,qn=ye,Kn=Se,Yn=$n,Xn=tn,Qn=fe("iterator"),Zn=!1;[].keys&&("next"in(ln=[].keys())?(cn=Yn(Yn(ln)))!==Object.prototype&&(an=cn):Zn=!0);var eo=!Kn(an)||Jn((function(){var e={};return an[Qn].call(e)!==e}));eo&&(an={}),qn(an[Qn])||Xn(an,Qn,(function(){return this}));var to={IteratorPrototype:an,BUGGY_SAFARI_ITERATORS:Zn},ro=De.f,io=W,no=fe("toStringTag"),oo=function(e,t,r){e&&!r&&(e=e.prototype),e&&!io(e,no)&&ro(e,no,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Dr,co=Gr,lo=oo,uo=Br,ho=function(){return this},po=function(e,t,r,i){var n=t+" Iterator";return e.prototype=ao(so,{next:co(+!i,r)}),lo(e,n,!1),uo[n]=ho,e},mo=c,fo=et,_o=ye,go=String,vo=TypeError,yo=function(e,t,r){try{return mo(fo(Object.getOwnPropertyDescriptor(e,t)[r]))}catch(i){}},Eo=be,To=function(e){if("object"==typeof e||_o(e))return e;throw vo("Can't set "+go(e)+" as a prototype")},So=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,r={};try{(e=yo(Object.prototype,"__proto__","set"))(r,[]),t=r instanceof Array}catch(i){}return function(r,i){return Eo(r),To(i),t?e(r,i):r.__proto__=i,r}}():void 0),Io=Vn,Ao=Fe,Co=ye,bo=po,Ro=$n,wo=So,ko=oo,Do=Jr,Po=tn,No=Br,Oo=ki.PROPER,Mo=ki.CONFIGURABLE,Lo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=fe("iterator"),Uo="keys",Fo="values",Bo="entries",jo=function(){return this},Ho=function(e,t,r,i,n,o,s){bo(r,t,i);var a,c,l,d=function(e){if(e===n&&f)return f;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new r(this,e)}}return function(){return new r(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||n&&p[n],f=!xo&&m||d(n),_="Array"==t&&p.entries||m;if(_&&(a=Ro(_.call(new e)))!==Object.prototype&&a.next&&(Ro(a)!==Lo&&(wo?wo(a,Lo):Co(a[Vo])||Po(a,Vo,jo)),ko(a,u,!0)),Oo&&n==Fo&&m&&m.name!==Fo&&(Mo?Do(p,"name",Fo):(h=!0,f=function(){return Ao(m,this)})),n)if(c={values:d(Fo),keys:o?f:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&Po(p,l,c[l]);else Io({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==f&&Po(p,Vo,f,{name:n}),No[t]=f,c},Wo=function(e,t){return{value:e,done:t}},Go=A,zo=Fr,$o=Br,Jo=ai,qo=De.f,Ko=Ho,Yo=Wo,Xo=we,Qo="Array Iterator",Zo=Jo.set,es=Jo.getterFor(Qo),ts=Ko(Array,"Array",(function(e,t){Zo(this,{type:Qo,target:Go(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,r=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,Yo(void 0,!0)):Yo("keys"==r?i:"values"==r?t[i]:[i,t[i]],!1)}),"values"),rs=$o.Arguments=$o.Array;if(zo("keys"),zo("values"),zo("entries"),Xo&&"values"!==rs.name)try{qo(rs,"name",{value:"values"})}catch(Sj){}var is={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},ns=Me("span").classList,os=ns&&ns.constructor&&ns.constructor.prototype,ss=os===Object.prototype?void 0:os,as=b,cs=is,ls=ss,ds=ts,us=Jr,hs=fe,ps=hs("iterator"),ms=hs("toStringTag"),fs=ds.values,_s=function(e,t){if(e){if(e[ps]!==fs)try{us(e,ps,fs)}catch(Sj){e[ps]=fs}if(e[ms]||us(e,ms,t),cs[t])for(var r in ds)if(e[r]!==ds[r])try{us(e,r,ds[r])}catch(Sj){e[r]=ds[r]}}};for(var gs in cs)_s(as[gs]&&as[gs].prototype,gs);_s(ls,"DOMTokenList");var vs="undefined"!=typeof process&&"process"==h(process),ys=Si,Es=De,Ts=function(e,t,r){return r.get&&ys(r.get,t,{getter:!0}),r.set&&ys(r.set,t,{setter:!0}),Es.f(e,t,r)},Ss=He,Is=Ts,As=we,Cs=fe("species"),bs=function(e){var t=Ss(e);As&&t&&!t[Cs]&&Is(t,Cs,{configurable:!0,get:function(){return this}})},Rs=We,ws=TypeError,ks=function(e,t){if(Rs(t,e))return e;throw ws("Incorrect invocation")},Ds={};Ds[fe("toStringTag")]="z";var Ps="[object z]"===String(Ds),Ns=ye,Os=h,Ms=fe("toStringTag"),Ls=Object,xs="Arguments"==Os(function(){return arguments}()),Vs=Ps?Os:function(e){var t,r,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(Sj){}}(t=Ls(e),Ms))?r:xs?Os(t):"Object"==(i=Os(t))&&Ns(t.callee)?"Arguments":i},Us=c,Fs=r,Bs=ye,js=Vs,Hs=Oi,Ws=function(){},Gs=[],zs=He("Reflect","construct"),$s=/^\s*(?:class|function)\b/,Js=Us($s.exec),qs=!$s.exec(Ws),Ks=function(e){if(!Bs(e))return!1;try{return zs(Ws,Gs,e),!0}catch(Sj){return!1}},Ys=function(e){if(!Bs(e))return!1;switch(js(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qs||!!Js($s,Hs(e))}catch(Sj){return!0}};Ys.sham=!0;var Xs,Qs,Zs,ea,ta=!zs||Fs((function(){var e;return Ks(Ks.call)||!Ks(Object)||!Ks((function(){e=!0}))||e}))?Ys:Ks,ra=ta,ia=Ye,na=TypeError,oa=function(e){if(ra(e))return e;throw na(ia(e)+" is not a constructor")},sa=be,aa=oa,ca=v,la=fe("species"),da=function(e,t){var r,i=sa(e).constructor;return void 0===i||ca(r=sa(i)[la])?t:aa(r)},ua=i,ha=Function.prototype,pa=ha.apply,ma=ha.call,fa="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),_a=h,ga=c,va=function(e){if("Function"===_a(e))return ga(e)},ya=et,Ea=i,Ta=va(va.bind),Sa=function(e,t){return ya(e),void 0===t?e:Ea?Ta(e,t):function(){return e.apply(t,arguments)}},Ia=c([].slice),Aa=TypeError,Ca=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},ba=/(?:ipad|iphone|ipod).*applewebkit/i.test(K),Ra=b,wa=fa,ka=Sa,Da=ye,Pa=W,Na=r,Oa=pr,Ma=Ia,La=Me,xa=Ca,Va=ba,Ua=vs,Fa=Ra.setImmediate,Ba=Ra.clearImmediate,ja=Ra.process,Ha=Ra.Dispatch,Wa=Ra.Function,Ga=Ra.MessageChannel,za=Ra.String,$a=0,Ja={},qa="onreadystatechange";Na((function(){Xs=Ra.location}));var Ka=function(e){if(Pa(Ja,e)){var t=Ja[e];delete Ja[e],t()}},Ya=function(e){return function(){Ka(e)}},Xa=function(e){Ka(e.data)},Qa=function(e){Ra.postMessage(za(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Da(e)?e:Wa(e),r=Ma(arguments,1);return Ja[++$a]=function(){wa(t,void 0,r)},Qs($a),$a},Ba=function(e){delete Ja[e]},Ua?Qs=function(e){ja.nextTick(Ya(e))}:Ha&&Ha.now?Qs=function(e){Ha.now(Ya(e))}:Ga&&!Va?(ea=(Zs=new Ga).port2,Zs.port1.onmessage=Xa,Qs=ka(ea.postMessage,ea)):Ra.addEventListener&&Da(Ra.postMessage)&&!Ra.importScripts&&Xs&&"file:"!==Xs.protocol&&!Na(Qa)?(Qs=Qa,Ra.addEventListener("message",Xa,!1)):Qs=qa in La("script")?function(e){Oa.appendChild(La("script"))[qa]=function(){Oa.removeChild(this),Ka(e)}}:function(e){setTimeout(Ya(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},r=this.tail;r?r.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,rc,ic,nc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(K)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(K),lc=b,dc=Sa,uc=ci.f,hc=Za.set,pc=sc,mc=ba,fc=ac,_c=cc,gc=vs,vc=lc.MutationObserver||lc.WebKitMutationObserver,yc=lc.document,Ec=lc.process,Tc=lc.Promise,Sc=uc(lc,"queueMicrotask"),Ic=Sc&&Sc.value;if(!Ic){var Ac=new pc,Cc=function(){var e,t;for(gc&&(e=Ec.domain)&&e.exit();t=Ac.get();)try{t()}catch(Sj){throw Ac.head&&tc(),Sj}e&&e.enter()};mc||gc||_c||!vc||!yc?!fc&&Tc&&Tc.resolve?((nc=Tc.resolve(void 0)).constructor=Tc,oc=dc(nc.then,nc),tc=function(){oc(Cc)}):gc?tc=function(){Ec.nextTick(Cc)}:(hc=dc(hc,lc),tc=function(){hc(Cc)}):(rc=!0,ic=yc.createTextNode(""),new vc(Cc).observe(ic,{characterData:!0}),tc=function(){ic.data=rc=!rc}),Ic=function(e){Ac.head||tc(),Ac.add(e)}}var bc=Ic,Rc=function(e){try{return{error:!1,value:e()}}catch(Sj){return{error:!0,value:Sj}}},wc=b.Promise,kc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!kc&&!vs&&"object"==typeof window&&"object"==typeof document,Pc=b,Nc=wc,Oc=ye,Mc=kn,Lc=Oi,xc=fe,Vc=Dc,Uc=kc,Fc=re;Nc&&Nc.prototype;var Bc=xc("species"),jc=!1,Hc=Oc(Pc.PromiseRejectionEvent),Wc=Mc("Promise",(function(){var e=Lc(Nc),t=e!==String(Nc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var r=new Nc((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((r.constructor={})[Bc]=i,!(jc=r.then((function(){}))instanceof i))return!0}return!t&&(Vc||Uc)&&!Hc})),Gc={CONSTRUCTOR:Wc,REJECTION_EVENT:Hc,SUBCLASSING:jc},zc={},$c=et,Jc=TypeError,qc=function(e){var t,r;this.promise=new e((function(e,i){if(void 0!==t||void 0!==r)throw Jc("Bad Promise constructor");t=e,r=i})),this.resolve=$c(t),this.reject=$c(r)};zc.f=function(e){return new qc(e)};var Kc,Yc,Xc,Qc=Vn,Zc=vs,el=b,tl=Fe,rl=tn,il=So,nl=oo,ol=bs,sl=et,al=ye,cl=Se,ll=ks,dl=da,ul=Za.set,hl=bc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(Sj){}},ml=Rc,fl=sc,_l=ai,gl=wc,vl=zc,yl="Promise",El=Gc.CONSTRUCTOR,Tl=Gc.REJECTION_EVENT,Sl=Gc.SUBCLASSING,Il=_l.getterFor(yl),Al=_l.set,Cl=gl&&gl.prototype,bl=gl,Rl=Cl,wl=el.TypeError,kl=el.document,Dl=el.process,Pl=vl.f,Nl=Pl,Ol=!!(kl&&kl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var r,i,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&jl(t),t.rejection=1),!0===a?r=o:(d&&d.enter(),r=a(o),d&&(d.exit(),n=!0)),r===e.promise?l(wl("Promise-chain cycle")):(i=Ll(r))?tl(i,r,c,l):c(r)):l(o)}catch(Sj){d&&!n&&d.exit(),l(Sj)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var r,i=e.reactions;r=i.get();)xl(r,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,r){var i,n;Ol?((i=kl.createEvent("Event")).promise=t,i.reason=r,i.initEvent(e,!1,!0),el.dispatchEvent(i)):i={promise:t,reason:r},!Tl&&(n=el["on"+e])?n(i):e===Ml&&pl("Unhandled promise rejection",r)},Fl=function(e){tl(ul,el,(function(){var t,r=e.facade,i=e.value;if(Bl(e)&&(t=ml((function(){Zc?Dl.emit("unhandledRejection",i,r):Ul(Ml,r,i)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},jl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},Hl=function(e,t,r){return function(i){e(t,i,r)}},Wl=function(e,t,r){e.done||(e.done=!0,r&&(e=r),e.value=t,e.state=2,Vl(e,!0))},Gl=function(e,t,r){if(!e.done){e.done=!0,r&&(e=r);try{if(e.facade===t)throw wl("Promise can't be resolved itself");var i=Ll(t);i?hl((function(){var r={done:!1};try{tl(i,t,Hl(Gl,r,e),Hl(Wl,r,e))}catch(Sj){Wl(r,Sj,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(Sj){Wl({done:!1},Sj,e)}}};if(El&&(Rl=(bl=function(e){ll(this,Rl),sl(e),tl(Kc,this);var t=Il(this);try{e(Hl(Gl,t),Hl(Wl,t))}catch(Sj){Wl(t,Sj)}}).prototype,(Kc=function(e){Al(this,{type:yl,done:!1,notified:!1,parent:!1,reactions:new fl,rejection:!1,state:0,value:void 0})}).prototype=rl(Rl,"then",(function(e,t){var r=Il(this),i=Pl(dl(this,bl));return r.parent=!0,i.ok=!al(e)||e,i.fail=al(t)&&t,i.domain=Zc?Dl.domain:void 0,0==r.state?r.reactions.add(i):hl((function(){xl(i,r)})),i.promise})),Yc=function(){var e=new Kc,t=Il(e);this.promise=e,this.resolve=Hl(Gl,t),this.reject=Hl(Wl,t)},vl.f=Pl=function(e){return e===bl||undefined===e?new Yc(e):Nl(e)},al(gl)&&Cl!==Object.prototype)){Xc=Cl.then,Sl||rl(Cl,"then",(function(e,t){var r=this;return new bl((function(e,t){tl(Xc,r,e,t)})).then(e,t)}),{unsafe:!0});try{delete Cl.constructor}catch(Sj){}il&&il(Cl,Rl)}Qc({global:!0,constructor:!0,wrap:!0,forced:El},{Promise:bl}),nl(bl,yl,!1),ol(yl);var zl=Br,$l=fe("iterator"),Jl=Array.prototype,ql=function(e){return void 0!==e&&(zl.Array===e||Jl[$l]===e)},Kl=Vs,Yl=it,Xl=v,Ql=Br,Zl=fe("iterator"),ed=function(e){if(!Xl(e))return Yl(e,Zl)||Yl(e,"@@iterator")||Ql[Kl(e)]},td=Fe,rd=et,id=be,nd=Ye,od=ed,sd=TypeError,ad=function(e,t){var r=arguments.length<2?od(e):t;if(rd(r))return id(td(r,e));throw sd(nd(e)+" is not iterable")},cd=Fe,ld=be,dd=it,ud=function(e,t,r){var i,n;ld(e);try{if(!(i=dd(e,"return"))){if("throw"===t)throw r;return r}i=cd(i,e)}catch(Sj){n=!0,i=Sj}if("throw"===t)throw r;if(n)throw i;return ld(i),r},hd=Sa,pd=Fe,md=be,fd=Ye,_d=ql,gd=Wt,vd=We,yd=ad,Ed=ed,Td=ud,Sd=TypeError,Id=function(e,t){this.stopped=e,this.result=t},Ad=Id.prototype,Cd=function(e,t,r){var i,n,o,s,a,c,l,d=r&&r.that,u=!(!r||!r.AS_ENTRIES),h=!(!r||!r.IS_RECORD),p=!(!r||!r.IS_ITERATOR),m=!(!r||!r.INTERRUPTED),f=hd(t,d),_=function(e){return i&&Td(i,"normal",e),new Id(!0,e)},g=function(e){return u?(md(e),m?f(e[0],e[1],_):f(e[0],e[1])):m?f(e,_):f(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(n=Ed(e)))throw Sd(fd(e)+" is not iterable");if(_d(n)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&vd(Ad,a))return a;return new Id(!1)}i=yd(e,n)}for(c=h?e.next:i.next;!(l=pd(c,i)).done;){try{a=g(l.value)}catch(Sj){Td(i,"throw",Sj)}if("object"==typeof a&&a&&vd(Ad,a))return a}return new Id(!1)},bd=fe("iterator"),Rd=!1;try{var wd=0,kd={next:function(){return{done:!!wd++}},return:function(){Rd=!0}};kd[bd]=function(){return this},Array.from(kd,(function(){throw 2}))}catch(Sj){}var Dd=function(e,t){if(!t&&!Rd)return!1;var r=!1;try{var i={};i[bd]=function(){return{next:function(){return{done:r=!0}}}},e(i)}catch(Sj){}return r},Pd=wc,Nd=Gc.CONSTRUCTOR||!Dd((function(e){Pd.all(e).then(void 0,(function(){}))})),Od=Fe,Md=et,Ld=zc,xd=Rc,Vd=Cd;Vn({target:"Promise",stat:!0,forced:Nd},{all:function(e){var t=this,r=Ld.f(t),i=r.resolve,n=r.reject,o=xd((function(){var r=Md(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Od(r,t,e).then((function(e){l||(l=!0,o[c]=e,--a||i(o))}),n)})),--a||i(o)}));return o.error&&n(o.value),r.promise}});var Ud=Vn,Fd=Gc.CONSTRUCTOR,Bd=wc,jd=He,Hd=ye,Wd=tn,Gd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),Hd(Bd)){var zd=jd("Promise").prototype.catch;Gd.catch!==zd&&Wd(Gd,"catch",zd,{unsafe:!0})}var $d=Fe,Jd=et,qd=zc,Kd=Rc,Yd=Cd;Vn({target:"Promise",stat:!0,forced:Nd},{race:function(e){var t=this,r=qd.f(t),i=r.reject,n=Kd((function(){var n=Jd(t.resolve);Yd(e,(function(e){$d(n,t,e).then(r.resolve,i)}))}));return n.error&&i(n.value),r.promise}});var Xd=Fe,Qd=zc;Vn({target:"Promise",stat:!0,forced:Gc.CONSTRUCTOR},{reject:function(e){var t=Qd.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=be,eu=Se,tu=zc,ru=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var r=tu.f(e);return(0,r.resolve)(t),r.promise},iu=Vn,nu=Gc.CONSTRUCTOR,ou=ru;He("Promise"),iu({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return ou(this,e)}});var su=ye,au=Se,cu=So,lu=function(e,t,r){var i,n;return cu&&su(i=t.constructor)&&i!==r&&au(n=i.prototype)&&n!==r.prototype&&cu(e,n),e},du=Se,uu=h,hu=fe("match"),pu=Vs,mu=String,fu=function(e){if("Symbol"===pu(e))throw TypeError("Cannot convert a Symbol value to a string");return mu(e)},_u=be,gu=function(){var e=_u(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},vu=Fe,yu=W,Eu=We,Tu=gu,Su=RegExp.prototype,Iu=r,Au=b.RegExp,Cu=Iu((function(){var e=Au("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),bu=Cu||Iu((function(){return!Au("a","y").sticky})),Ru={BROKEN_CARET:Cu||Iu((function(){var e=Au("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),MISSED_STICKY:bu,UNSUPPORTED_Y:Cu},wu=De.f,ku=r,Du=b.RegExp,Pu=ku((function(){var e=Du(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Nu=r,Ou=b.RegExp,Mu=Nu((function(){var e=Ou("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Lu=we,xu=b,Vu=c,Uu=kn,Fu=lu,Bu=Jr,ju=rn.f,Hu=We,Wu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},Gu=fu,zu=function(e){var t=e.flags;return void 0!==t||"flags"in Su||yu(e,"flags")||!Eu(Su,e)?t:vu(Tu,e)},$u=Ru,Ju=function(e,t,r){r in e||wu(e,r,{configurable:!0,get:function(){return t[r]},set:function(e){t[r]=e}})},qu=tn,Ku=r,Yu=W,Xu=ai.enforce,Qu=bs,Zu=Pu,eh=Mu,th=fe("match"),rh=xu.RegExp,ih=rh.prototype,nh=xu.SyntaxError,oh=Vu(ih.exec),sh=Vu("".charAt),ah=Vu("".replace),ch=Vu("".indexOf),lh=Vu("".slice),dh=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,uh=/a/g,hh=/a/g,ph=new rh(uh)!==uh,mh=$u.MISSED_STICKY,fh=$u.UNSUPPORTED_Y,_h=Lu&&(!ph||mh||Zu||eh||Ku((function(){return hh[th]=!1,rh(uh)!=uh||rh(hh)==hh||"/a/i"!=rh(uh,"i")})));if(Uu("RegExp",_h)){for(var gh=function(e,t){var r,i,n,o,s,a,c=Hu(ih,this),l=Wu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===gh)return e;if((l||Hu(ih,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?"":Gu(e),t=void 0===t?"":Gu(t),h=e,Zu&&"dotAll"in uh&&(i=!!t&&ch(t,"s")>-1)&&(t=ah(t,/s/g,"")),r=t,mh&&"sticky"in uh&&(n=!!t&&ch(t,"y")>-1)&&fh&&(t=ah(t,/y/g,"")),eh&&(o=function(e){for(var t,r=e.length,i=0,n="",o=[],s={},a=!1,c=!1,l=0,d="";i<=r;i++){if("\\"===(t=sh(e,i)))t+=sh(e,++i);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:oh(dh,lh(e,i+1))&&(i+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Yu(s,d))throw new nh("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=Fu(rh(e,t),c?this:ih,gh),(i||n||u.length)&&(a=Xu(s),i&&(a.dotAll=!0,a.raw=gh(function(e){for(var t,r=e.length,i=0,n="",o=!1;i<=r;i++)"\\"!==(t=sh(e,i))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+sh(e,++i);return n}(e),r)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Bu(s,"source",""===h?"(?:)":h)}catch(Sj){}return s},vh=ju(rh),yh=0;vh.length>yh;)Ju(gh,rh,vh[yh++]);ih.constructor=gh,gh.prototype=ih,qu(xu,"RegExp",gh,{constructor:!0})}Qu("RegExp");var Eh=Fe,Th=c,Sh=fu,Ih=gu,Ah=Ru,Ch=Dr,bh=ai.get,Rh=Pu,wh=Mu,kh=R("native-string-replace",String.prototype.replace),Dh=RegExp.prototype.exec,Ph=Dh,Nh=Th("".charAt),Oh=Th("".indexOf),Mh=Th("".replace),Lh=Th("".slice),xh=function(){var e=/a/,t=/b*/g;return Eh(Dh,e,"a"),Eh(Dh,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Vh=Ah.BROKEN_CARET,Uh=void 0!==/()??/.exec("")[1];(xh||Uh||Vh||Rh||wh)&&(Ph=function(e){var t,r,i,n,o,s,a,c=this,l=bh(c),d=Sh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=Eh(Ph,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Vh&&c.sticky,m=Eh(Ih,c),f=c.source,_=0,g=d;if(p&&(m=Mh(m,"y",""),-1===Oh(m,"g")&&(m+="g"),g=Lh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Nh(d,c.lastIndex-1))&&(f="(?: "+f+")",g=" "+g,_++),r=new RegExp("^(?:"+f+")",m)),Uh&&(r=new RegExp("^"+f+"$(?!\\s)",m)),xh&&(i=c.lastIndex),n=Eh(Dh,p?r:c,g),p?n?(n.input=Lh(n.input,_),n[0]=Lh(n[0],_),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:xh&&n&&(c.lastIndex=c.global?n.index+n[0].length:i),Uh&&n&&n.length>1&&Eh(kh,n[0],r,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n&&h)for(n.groups=s=Ch(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var Fh=Ph;Vn({target:"RegExp",proto:!0,forced:/./.exec!==Fh},{exec:Fh});var Bh=h,jh=Array.isArray||function(e){return"Array"==Bh(e)},Hh=jh,Wh=ta,Gh=Se,zh=fe("species"),$h=Array,Jh=function(e){var t;return Hh(e)&&(t=e.constructor,(Wh(t)&&(t===$h||Hh(t.prototype))||Gh(t)&&null===(t=t[zh]))&&(t=void 0)),void 0===t?$h:t},qh=Sa,Kh=g,Yh=B,Xh=Wt,Qh=function(e,t){return new(Jh(e))(0===t?0:t)},Zh=c([].push),ep=function(e){var t=1==e,r=2==e,i=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Yh(c),f=Kh(m),_=qh(l,d),g=Xh(f),v=0,y=u||Qh,E=t?y(c,g):r||s?y(c,0):void 0;g>v;v++)if((a||v in f)&&(p=_(h=f[v],v,m),e))if(t)E[v]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:Zh(E,h)}else switch(e){case 4:return!1;case 7:Zh(E,h)}return o?-1:i||n?n:E}},tp={forEach:ep(0),map:ep(1),filter:ep(2),some:ep(3),every:ep(4),find:ep(5),findIndex:ep(6),filterReject:ep(7)},rp=r,ip=function(e,t){var r=[][e];return!!r&&rp((function(){r.call(null,t||function(){return 1},1)}))},np=tp.forEach,op=ip("forEach")?[].forEach:function(e){return np(this,e,arguments.length>1?arguments[1]:void 0)},sp=b,ap=is,cp=ss,lp=op,dp=Jr,up=function(e){if(e&&e.forEach!==lp)try{dp(e,"forEach",lp)}catch(Sj){e.forEach=lp}};for(var hp in ap)ap[hp]&&up(sp[hp]&&sp[hp].prototype);up(cp);var pp=et,mp=B,fp=g,_p=Wt,gp=TypeError,vp=function(e){return function(t,r,i,n){pp(r);var o=mp(t),s=fp(o),a=_p(o),c=e?a-1:0,l=e?-1:1;if(i<2)for(;;){if(c in s){n=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw gp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(n=r(n,s[c],c,o));return n}},yp={left:vp(!1),right:vp(!0)}.left;Vn({target:"Array",proto:!0,forced:!vs&&re>79&&re<83||!ip("reduce")},{reduce:function(e){var t=arguments.length;return yp(this,e,t,t>1?arguments[1]:void 0)}});var Ep=va,Tp=tn,Sp=Fh,Ip=r,Ap=fe,Cp=Jr,bp=Ap("species"),Rp=RegExp.prototype,wp=c,kp=Mt,Dp=fu,Pp=T,Np=wp("".charAt),Op=wp("".charCodeAt),Mp=wp("".slice),Lp=function(e){return function(t,r){var i,n,o=Dp(Pp(t)),s=kp(r),a=o.length;return s<0||s>=a?e?"":void 0:(i=Op(o,s))<55296||i>56319||s+1===a||(n=Op(o,s+1))<56320||n>57343?e?Np(o,s):i:e?Mp(o,s,s+2):n-56320+(i-55296<<10)+65536}},xp={codeAt:Lp(!1),charAt:Lp(!0)},Vp=xp.charAt,Up=c,Fp=B,Bp=Math.floor,jp=Up("".charAt),Hp=Up("".replace),Wp=Up("".slice),Gp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,$p=Fe,Jp=be,qp=ye,Kp=h,Yp=Fh,Xp=TypeError,Qp=fa,Zp=Fe,em=c,tm=function(e,t,r,i){var n=Ap(e),o=!Ip((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Ip((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[bp]=function(){return r},r.flags="",r[n]=/./[n]),r.exec=function(){return t=!0,null},r[n](""),!t}));if(!o||!s||r){var a=Ep(/./[n]),c=t(n,""[e],(function(e,t,r,i,n){var s=Ep(e),c=t.exec;return c===Sp||c===Rp.exec?o&&!n?{done:!0,value:a(t,r,i)}:{done:!0,value:s(r,t,i)}:{done:!1}}));Tp(String.prototype,e,c[0]),Tp(Rp,n,c[1])}i&&Cp(Rp[n],"sham",!0)},rm=r,im=be,nm=ye,om=v,sm=Mt,am=jt,cm=fu,lm=T,dm=function(e,t,r){return t+(r?Vp(e,t).length:1)},um=it,hm=function(e,t,r,i,n,o){var s=r+e.length,a=i.length,c=zp;return void 0!==n&&(n=Fp(n),c=Gp),Hp(o,c,(function(o,c){var l;switch(jp(c,0)){case"$":return"$";case"&":return e;case"`":return Wp(t,0,r);case"'":return Wp(t,s);case"<":l=n[Wp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Bp(d/10);return 0===u?o:u<=a?void 0===i[u-1]?jp(c,1):i[u-1]+jp(c,1):o}l=i[d-1]}return void 0===l?"":l}))},pm=function(e,t){var r=e.exec;if(qp(r)){var i=$p(r,e,t);return null!==i&&Jp(i),i}if("RegExp"===Kp(e))return $p(Yp,e,t);throw Xp("RegExp#exec called on incompatible receiver")},mm=fe("replace"),fm=Math.max,_m=Math.min,gm=em([].concat),vm=em([].push),ym=em("".indexOf),Em=em("".slice),Tm=function(e){return void 0===e?e:String(e)},Sm="$0"==="a".replace(/./,"$0"),Im=!!/./[mm]&&""===/./[mm]("a","$0");tm("replace",(function(e,t,r){var i=Im?"$":"$0";return[function(e,r){var i=lm(this),n=om(e)?void 0:um(e,mm);return n?Zp(n,e,i,r):Zp(t,cm(i),e,r)},function(e,n){var o=im(this),s=cm(e);if("string"==typeof n&&-1===ym(n,i)&&-1===ym(n,"$<")){var a=r(t,o,s,n);if(a.done)return a.value}var c=nm(n);c||(n=cm(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=pm(o,s);if(null===h)break;if(vm(u,h),!l)break;""===cm(h[0])&&(o.lastIndex=dm(s,am(o.lastIndex),d))}for(var p="",m=0,f=0;f<u.length;f++){for(var _=cm((h=u[f])[0]),g=fm(_m(sm(h.index),s.length),0),v=[],y=1;y<h.length;y++)vm(v,Tm(h[y]));var E=h.groups;if(c){var T=gm([_],v,g,s);void 0!==E&&vm(T,E);var S=cm(Qp(n,void 0,T))}else S=hm(_,s,g,v,E,n);g>=m&&(p+=Em(s,m,g)+S,m=g+_.length)}return p+Em(s,m)}]}),!!rm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}))||!Sm||Im);var Am=qt.includes,Cm=Fr;Vn({target:"Array",proto:!0,forced:r((function(){return!Array(1).includes()}))},{includes:function(e){return Am(this,e,arguments.length>1?arguments[1]:void 0)}}),Cm("includes");var bm=Mt,Rm=fu,wm=T,km=RangeError,Dm=c,Pm=jt,Nm=fu,Om=function(e){var t=Rm(wm(this)),r="",i=bm(e);if(i<0||Infinity==i)throw km("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(r+=t);return r},Mm=T,Lm=Dm(Om),xm=Dm("".slice),Vm=Math.ceil,Um=function(e){return function(t,r,i){var n,o,s=Nm(Mm(t)),a=Pm(r),c=s.length,l=void 0===i?" ":Nm(i);return a<=c||""==l?s:((o=Lm(l,Vm((n=a-c)/l.length))).length>n&&(o=xm(o,0,n)),e?s+o:o+s)}},Fm={start:Um(!1),end:Um(!0)},Bm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(K),jm=Fm.start;Vn({target:"String",proto:!0,forced:Bm},{padStart:function(e){return jm(this,e,arguments.length>1?arguments[1]:void 0)}});var Hm=r,Wm=we,Gm=fe("iterator"),zm=!Hm((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,r="";return e.pathname="c%20d",t.forEach((function(e,i){t.delete("b"),r+=i+e})),!t.size&&!Wm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Gm]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==r||"x"!==new URL("http://x",void 0).host})),$m=tn,Jm=function(e,t,r){for(var i in t)$m(e,i,t[i],r);return e},qm=vt,Km=De,Ym=Gr,Xm=function(e,t,r){var i=qm(t);i in e?Km.f(e,i,Ym(0,r)):e[i]=r},Qm=Ut,Zm=Wt,ef=Xm,tf=Array,rf=Math.max,nf=function(e,t,r){for(var i=Zm(e),n=Qm(t,i),o=Qm(void 0===r?i:r,i),s=tf(rf(o-n,0)),a=0;n<o;n++,a++)ef(s,a,e[n]);return s.length=a,s},of=nf,sf=Math.floor,af=function(e,t){var r=e.length,i=sf(r/2);return r<8?cf(e,t):lf(e,af(of(e,0,i),t),af(of(e,i),t),t)},cf=function(e,t){for(var r,i,n=e.length,o=1;o<n;){for(i=o,r=e[o];i&&t(e[i-1],r)>0;)e[i]=e[--i];i!==o++&&(e[i]=r)}return e},lf=function(e,t,r,i){for(var n=t.length,o=r.length,s=0,a=0;s<n||a<o;)e[s+a]=s<n&&a<o?i(t[s],r[a])<=0?t[s++]:r[a++]:s<n?t[s++]:r[a++];return e},df=af,uf=Vn,hf=b,pf=Fe,mf=c,ff=we,_f=zm,gf=tn,vf=Ts,yf=Jm,Ef=oo,Tf=po,Sf=ai,If=ks,Af=ye,Cf=W,bf=Sa,Rf=Vs,wf=be,kf=Se,Df=fu,Pf=Dr,Nf=Gr,Of=ad,Mf=ed,Lf=Ca,xf=df,Vf=fe("iterator"),Uf="URLSearchParams",Ff=Uf+"Iterator",Bf=Sf.set,jf=Sf.getterFor(Uf),Hf=Sf.getterFor(Ff),Wf=Object.getOwnPropertyDescriptor,Gf=function(e){if(!ff)return hf[e];var t=Wf(hf,e);return t&&t.value},zf=Gf("fetch"),$f=Gf("Request"),Jf=Gf("Headers"),qf=$f&&$f.prototype,Kf=Jf&&Jf.prototype,Yf=hf.RegExp,Xf=hf.TypeError,Qf=hf.decodeURIComponent,Zf=hf.encodeURIComponent,e_=mf("".charAt),t_=mf([].join),r_=mf([].push),i_=mf("".replace),n_=mf([].shift),o_=mf([].splice),s_=mf("".split),a_=mf("".slice),c_=/\+/g,l_=Array(4),d_=function(e){return l_[e-1]||(l_[e-1]=Yf("((?:%[\\da-f]{2}){"+e+"})","gi"))},u_=function(e){try{return Qf(e)}catch(Sj){return e}},h_=function(e){var t=i_(e,c_," "),r=4;try{return Qf(t)}catch(Sj){for(;r;)t=i_(t,d_(r--),u_);return t}},p_=/[!'()~]|%20/g,m_={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},f_=function(e){return m_[e]},__=function(e){return i_(Zf(e),p_,f_)},g_=Tf((function(e,t){Bf(this,{type:Ff,iterator:Of(jf(e).entries),kind:t})}),"Iterator",(function(){var e=Hf(this),t=e.kind,r=e.iterator.next(),i=r.value;return r.done||(r.value="keys"===t?i.key:"values"===t?i.value:[i.key,i.value]),r}),!0),v_=function(e){this.entries=[],this.url=null,void 0!==e&&(kf(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===e_(e,0)?a_(e,1):e:Df(e)))};v_.prototype={type:Uf,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,r,i,n,o,s,a,c=Mf(e);if(c)for(r=(t=Of(e,c)).next;!(i=pf(r,t)).done;){if(o=(n=Of(wf(i.value))).next,(s=pf(o,n)).done||(a=pf(o,n)).done||!pf(o,n).done)throw Xf("Expected sequence with length 2");r_(this.entries,{key:Df(s.value),value:Df(a.value)})}else for(var l in e)Cf(e,l)&&r_(this.entries,{key:l,value:Df(e[l])})},parseQuery:function(e){if(e)for(var t,r,i=s_(e,"&"),n=0;n<i.length;)(t=i[n++]).length&&(r=s_(t,"="),r_(this.entries,{key:h_(n_(r)),value:h_(t_(r,"="))}))},serialize:function(){for(var e,t=this.entries,r=[],i=0;i<t.length;)e=t[i++],r_(r,__(e.key)+"="+__(e.value));return t_(r,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var y_=function(){If(this,E_);var e=Bf(this,new v_(arguments.length>0?arguments[0]:void 0));ff||(this.length=e.entries.length)},E_=y_.prototype;if(yf(E_,{append:function(e,t){Lf(arguments.length,2);var r=jf(this);r_(r.entries,{key:Df(e),value:Df(t)}),ff||this.length++,r.updateURL()},delete:function(e){Lf(arguments.length,1);for(var t=jf(this),r=t.entries,i=Df(e),n=0;n<r.length;)r[n].key===i?o_(r,n,1):n++;ff||(this.length=r.length),t.updateURL()},get:function(e){Lf(arguments.length,1);for(var t=jf(this).entries,r=Df(e),i=0;i<t.length;i++)if(t[i].key===r)return t[i].value;return null},getAll:function(e){Lf(arguments.length,1);for(var t=jf(this).entries,r=Df(e),i=[],n=0;n<t.length;n++)t[n].key===r&&r_(i,t[n].value);return i},has:function(e){Lf(arguments.length,1);for(var t=jf(this).entries,r=Df(e),i=0;i<t.length;)if(t[i++].key===r)return!0;return!1},set:function(e,t){Lf(arguments.length,1);for(var r,i=jf(this),n=i.entries,o=!1,s=Df(e),a=Df(t),c=0;c<n.length;c++)(r=n[c]).key===s&&(o?o_(n,c--,1):(o=!0,r.value=a));o||r_(n,{key:s,value:a}),ff||(this.length=n.length),i.updateURL()},sort:function(){var e=jf(this);xf(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,r=jf(this).entries,i=bf(e,arguments.length>1?arguments[1]:void 0),n=0;n<r.length;)i((t=r[n++]).value,t.key,this)},keys:function(){return new g_(this,"keys")},values:function(){return new g_(this,"values")},entries:function(){return new g_(this,"entries")}},{enumerable:!0}),gf(E_,Vf,E_.entries,{name:"entries"}),gf(E_,"toString",(function(){return jf(this).serialize()}),{enumerable:!0}),ff&&vf(E_,"size",{get:function(){return jf(this).entries.length},configurable:!0,enumerable:!0}),Ef(y_,Uf),uf({global:!0,constructor:!0,forced:!_f},{URLSearchParams:y_}),!_f&&Af(Jf)){var T_=mf(Kf.has),S_=mf(Kf.set),I_=function(e){if(kf(e)){var t,r=e.body;if(Rf(r)===Uf)return t=e.headers?new Jf(e.headers):new Jf,T_(t,"content-type")||S_(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Pf(e,{body:Nf(0,Df(r)),headers:Nf(0,t)})}return e};if(Af(zf)&&uf({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return zf(e,arguments.length>1?I_(arguments[1]):{})}}),Af($f)){var A_=function(e){return If(this,qf),new $f(e,arguments.length>1?I_(arguments[1]):{})};qf.constructor=A_,A_.prototype=qf,uf({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:A_})}}var C_={URLSearchParams:y_,getState:jf},b_=Vn,R_=wc,w_=r,k_=He,D_=ye,P_=da,N_=ru,O_=tn,M_=R_&&R_.prototype;if(b_({target:"Promise",proto:!0,real:!0,forced:!!R_&&w_((function(){M_.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=P_(this,k_("Promise")),r=D_(e);return this.then(r?function(r){return N_(t,e()).then((function(){return r}))}:e,r?function(r){return N_(t,e()).then((function(){throw r}))}:e)}}),D_(R_)){var L_=k_("Promise").prototype.finally;M_.finally!==L_&&O_(M_,"finally",L_,{unsafe:!0})}var x_="\t\n\v\f\r \u2028\u2029\ufeff",V_=T,U_=fu,F_=x_,B_=c("".replace),j_=RegExp("^["+F_+"]+"),H_=RegExp("(^|[^"+F_+"])["+F_+"]+$"),W_=function(e){return function(t){var r=U_(V_(t));return 1&e&&(r=B_(r,j_,"")),2&e&&(r=B_(r,H_,"$1")),r}},G_={start:W_(1),end:W_(2),trim:W_(3)},z_=ki.PROPER,$_=r,J_=x_,q_=G_.trim;Vn({target:"String",proto:!0,forced:function(e){return $_((function(){return!!J_[e]()||"
"!=="
"[e]()||z_&&J_[e].name!==e}))}("trim")},{trim:function(){return q_(this)}});var K_="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Y_=Mt,X_=jt,Q_=RangeError,Z_=function(e){if(void 0===e)return 0;var t=Y_(e),r=X_(t);if(t!==r)throw Q_("Wrong length or index");return r},eg=Array,tg=Math.abs,rg=Math.pow,ig=Math.floor,ng=Math.log,og=Math.LN2,sg={pack:function(e,t,r){var i,n,o,s=eg(r),a=8*r-t-1,c=(1<<a)-1,l=c>>1,d=23===t?rg(2,-24)-rg(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=tg(e))!=e||Infinity===e?(n=e!=e?1:0,i=c):(i=ig(ng(e)/og),e*(o=rg(2,-i))<1&&(i--,o*=2),(e+=i+l>=1?d/o:d*rg(2,1-l))*o>=2&&(i++,o/=2),i+l>=c?(n=0,i=c):i+l>=1?(n=(e*o-1)*rg(2,t),i+=l):(n=e*rg(2,l-1)*rg(2,t),i=0));t>=8;)s[h++]=255&n,n/=256,t-=8;for(i=i<<t|n,a+=t;a>0;)s[h++]=255&i,i/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var r,i=e.length,n=8*i-t-1,o=(1<<n)-1,s=o>>1,a=n-7,c=i-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(r=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)r=256*r+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return r?NaN:l?-Infinity:Infinity;r+=rg(2,t),d-=s}return(l?-1:1)*r*rg(2,d-t)}},ag=B,cg=Ut,lg=Wt,dg=function(e){for(var t=ag(this),r=lg(t),i=arguments.length,n=cg(i>1?arguments[1]:void 0,r),o=i>2?arguments[2]:void 0,s=void 0===o?r:cg(o,r);s>n;)t[n++]=e;return t},ug=b,hg=c,pg=we,mg=K_,fg=ki,_g=Jr,gg=Ts,vg=Jm,yg=r,Eg=ks,Tg=Mt,Sg=jt,Ig=Z_,Ag=sg,Cg=$n,bg=So,Rg=rn.f,wg=dg,kg=nf,Dg=oo,Pg=ai,Ng=fg.PROPER,Og=fg.CONFIGURABLE,Mg="ArrayBuffer",Lg="DataView",xg="prototype",Vg="Wrong index",Ug=Pg.getterFor(Mg),Fg=Pg.getterFor(Lg),Bg=Pg.set,jg=ug[Mg],Hg=jg,Wg=Hg&&Hg[xg],Gg=ug[Lg],zg=Gg&&Gg[xg],$g=Object.prototype,Jg=ug.Array,qg=ug.RangeError,Kg=hg(wg),Yg=hg([].reverse),Xg=Ag.pack,Qg=Ag.unpack,Zg=function(e){return[255&e]},ev=function(e){return[255&e,e>>8&255]},tv=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},rv=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},iv=function(e){return Xg(e,23,4)},nv=function(e){return Xg(e,52,8)},ov=function(e,t,r){gg(e[xg],t,{configurable:!0,get:function(){return r(this)[t]}})},sv=function(e,t,r,i){var n=Ig(r),o=Fg(e);if(n+t>o.byteLength)throw qg(Vg);var s=o.bytes,a=n+o.byteOffset,c=kg(s,a,a+t);return i?c:Yg(c)},av=function(e,t,r,i,n,o){var s=Ig(r),a=Fg(e);if(s+t>a.byteLength)throw qg(Vg);for(var c=a.bytes,l=s+a.byteOffset,d=i(+n),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(mg){var cv=Ng&&jg.name!==Mg;if(yg((function(){jg(1)}))&&yg((function(){new jg(-1)}))&&!yg((function(){return new jg,new jg(1.5),new jg(NaN),1!=jg.length||cv&&!Og})))cv&&Og&&_g(jg,"name",Mg);else{(Hg=function(e){return Eg(this,Wg),new jg(Ig(e))})[xg]=Wg;for(var lv,dv=Rg(jg),uv=0;dv.length>uv;)(lv=dv[uv++])in Hg||_g(Hg,lv,jg[lv]);Wg.constructor=Hg}bg&&Cg(zg)!==$g&&bg(zg,$g);var hv=new Gg(new Hg(2)),pv=hg(zg.setInt8);hv.setInt8(0,2147483648),hv.setInt8(1,2147483649),!hv.getInt8(0)&&hv.getInt8(1)||vg(zg,{setInt8:function(e,t){pv(this,e,t<<24>>24)},setUint8:function(e,t){pv(this,e,t<<24>>24)}},{unsafe:!0})}else Wg=(Hg=function(e){Eg(this,Wg);var t=Ig(e);Bg(this,{type:Mg,bytes:Kg(Jg(t),0),byteLength:t}),pg||(this.byteLength=t,this.detached=!1)})[xg],zg=(Gg=function(e,t,r){Eg(this,zg),Eg(e,Wg);var i=Ug(e),n=i.byteLength,o=Tg(t);if(o<0||o>n)throw qg("Wrong offset");if(o+(r=void 0===r?n-o:Sg(r))>n)throw qg("Wrong length");Bg(this,{type:Lg,buffer:e,byteLength:r,byteOffset:o,bytes:i.bytes}),pg||(this.buffer=e,this.byteLength=r,this.byteOffset=o)})[xg],pg&&(ov(Hg,"byteLength",Ug),ov(Gg,"buffer",Fg),ov(Gg,"byteLength",Fg),ov(Gg,"byteOffset",Fg)),vg(zg,{getInt8:function(e){return sv(this,1,e)[0]<<24>>24},getUint8:function(e){return sv(this,1,e)[0]},getInt16:function(e){var t=sv(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=sv(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return rv(sv(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return rv(sv(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return Qg(sv(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return Qg(sv(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){av(this,1,e,Zg,t)},setUint8:function(e,t){av(this,1,e,Zg,t)},setInt16:function(e,t){av(this,2,e,ev,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){av(this,2,e,ev,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){av(this,4,e,tv,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){av(this,4,e,tv,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){av(this,4,e,iv,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){av(this,8,e,nv,t,arguments.length>2?arguments[2]:void 0)}});Dg(Hg,Mg),Dg(Gg,Lg);var mv={ArrayBuffer:Hg,DataView:Gg},fv=Vn,_v=va,gv=r,vv=be,yv=Ut,Ev=jt,Tv=da,Sv=mv.ArrayBuffer,Iv=mv.DataView,Av=Iv.prototype,Cv=_v(Sv.prototype.slice),bv=_v(Av.getUint8),Rv=_v(Av.setUint8);fv({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:gv((function(){return!new Sv(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(Cv&&void 0===t)return Cv(vv(this),e);for(var r=vv(this).byteLength,i=yv(e,r),n=yv(void 0===t?r:t,r),o=new(Tv(this,Sv))(Ev(n-i)),s=new Iv(this),a=new Iv(o),c=0;i<n;)Rv(a,c++,bv(s,i++));return o}});var wv,kv,Dv,Pv={},Nv={get exports(){return Pv},set exports(e){Pv=e}},Ov=K_,Mv=we,Lv=b,xv=ye,Vv=Se,Uv=W,Fv=Vs,Bv=Ye,jv=Jr,Hv=tn,Wv=Ts,Gv=We,zv=$n,$v=So,Jv=fe,qv=q,Kv=ai.enforce,Yv=ai.get,Xv=Lv.Int8Array,Qv=Xv&&Xv.prototype,Zv=Lv.Uint8ClampedArray,ey=Zv&&Zv.prototype,ty=Xv&&zv(Xv),ry=Qv&&zv(Qv),iy=Object.prototype,ny=Lv.TypeError,oy=Jv("toStringTag"),sy=qv("TYPED_ARRAY_TAG"),ay="TypedArrayConstructor",cy=Ov&&!!$v&&"Opera"!==Fv(Lv.opera),ly=!1,dy={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},uy={BigInt64Array:8,BigUint64Array:8},hy=function(e){var t=zv(e);if(Vv(t)){var r=Yv(t);return r&&Uv(r,ay)?r[ay]:hy(t)}},py=function(e){if(!Vv(e))return!1;var t=Fv(e);return Uv(dy,t)||Uv(uy,t)};for(wv in dy)(Dv=(kv=Lv[wv])&&kv.prototype)?Kv(Dv)[ay]=kv:cy=!1;for(wv in uy)(Dv=(kv=Lv[wv])&&kv.prototype)&&(Kv(Dv)[ay]=kv);if((!cy||!xv(ty)||ty===Function.prototype)&&(ty=function(){throw ny("Incorrect invocation")},cy))for(wv in dy)Lv[wv]&&$v(Lv[wv],ty);if((!cy||!ry||ry===iy)&&(ry=ty.prototype,cy))for(wv in dy)Lv[wv]&&$v(Lv[wv].prototype,ry);if(cy&&zv(ey)!==ry&&$v(ey,ry),Mv&&!Uv(ry,oy))for(wv in ly=!0,Wv(ry,oy,{configurable:!0,get:function(){return Vv(this)?this[sy]:void 0}}),dy)Lv[wv]&&jv(Lv[wv],sy,wv);var my={NATIVE_ARRAY_BUFFER_VIEWS:cy,TYPED_ARRAY_TAG:ly&&sy,aTypedArray:function(e){if(py(e))return e;throw ny("Target is not a typed array")},aTypedArrayConstructor:function(e){if(xv(e)&&(!$v||Gv(ty,e)))return e;throw ny(Bv(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,r,i){if(Mv){if(r)for(var n in dy){var o=Lv[n];if(o&&Uv(o.prototype,e))try{delete o.prototype[e]}catch(Sj){try{o.prototype[e]=t}catch(s){}}}ry[e]&&!r||Hv(ry,e,r?t:cy&&Qv[e]||t,i)}},exportTypedArrayStaticMethod:function(e,t,r){var i,n;if(Mv){if($v){if(r)for(i in dy)if((n=Lv[i])&&Uv(n,e))try{delete n[e]}catch(Sj){}if(ty[e]&&!r)return;try{return Hv(ty,e,r?t:cy&&ty[e]||t)}catch(Sj){}}for(i in dy)!(n=Lv[i])||n[e]&&!r||Hv(n,e,t)}},getTypedArrayConstructor:hy,isView:function(e){if(!Vv(e))return!1;var t=Fv(e);return"DataView"===t||Uv(dy,t)||Uv(uy,t)},isTypedArray:py,TypedArray:ty,TypedArrayPrototype:ry},fy=b,_y=r,gy=Dd,vy=my.NATIVE_ARRAY_BUFFER_VIEWS,yy=fy.ArrayBuffer,Ey=fy.Int8Array,Ty=!vy||!_y((function(){Ey(1)}))||!_y((function(){new Ey(-1)}))||!gy((function(e){new Ey,new Ey(null),new Ey(1.5),new Ey(e)}),!0)||_y((function(){return 1!==new Ey(new yy(2),1,void 0).length})),Sy=Se,Iy=Math.floor,Ay=Number.isInteger||function(e){return!Sy(e)&&isFinite(e)&&Iy(e)===e},Cy=Mt,by=RangeError,Ry=function(e){var t=Cy(e);if(t<0)throw by("The argument can't be less than 0");return t},wy=RangeError,ky=function(e,t){var r=Ry(e);if(r%t)throw wy("Wrong offset");return r},Dy=Vs,Py=ft,Ny=TypeError,Oy=function(e){var t=Py(e,"number");if("number"==typeof t)throw Ny("Can't convert number to bigint");return BigInt(t)},My=Sa,Ly=Fe,xy=oa,Vy=B,Uy=Wt,Fy=ad,By=ed,jy=ql,Hy=function(e){var t=Dy(e);return"BigInt64Array"==t||"BigUint64Array"==t},Wy=my.aTypedArrayConstructor,Gy=Oy,zy=function(e){var t,r,i,n,o,s,a,c,l=xy(this),d=Vy(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=By(d);if(m&&!jy(m))for(c=(a=Fy(d,m)).next,d=[];!(s=Ly(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=My(h,arguments[2])),r=Uy(d),i=new(Wy(l))(r),n=Hy(i),t=0;r>t;t++)o=p?h(d[t],t):d[t],i[t]=n?Gy(o):+o;return i},$y=Vn,Jy=b,qy=Fe,Ky=we,Yy=Ty,Xy=my,Qy=mv,Zy=ks,eE=Gr,tE=Jr,rE=Ay,iE=jt,nE=Z_,oE=ky,sE=vt,aE=W,cE=Vs,lE=Se,dE=qe,uE=Dr,hE=We,pE=So,mE=rn.f,fE=zy,_E=tp.forEach,gE=bs,vE=Ts,yE=De,EE=ci,TE=lu,SE=ai.get,IE=ai.set,AE=ai.enforce,CE=yE.f,bE=EE.f,RE=Math.round,wE=Jy.RangeError,kE=Qy.ArrayBuffer,DE=kE.prototype,PE=Qy.DataView,NE=Xy.NATIVE_ARRAY_BUFFER_VIEWS,OE=Xy.TYPED_ARRAY_TAG,ME=Xy.TypedArray,LE=Xy.TypedArrayPrototype,xE=Xy.aTypedArrayConstructor,VE=Xy.isTypedArray,UE="BYTES_PER_ELEMENT",FE="Wrong length",BE=function(e,t){xE(e);for(var r=0,i=t.length,n=new e(i);i>r;)n[r]=t[r++];return n},jE=function(e,t){vE(e,t,{configurable:!0,get:function(){return SE(this)[t]}})},HE=function(e){var t;return hE(DE,e)||"ArrayBuffer"==(t=cE(e))||"SharedArrayBuffer"==t},WE=function(e,t){return VE(e)&&!dE(t)&&t in e&&rE(+t)&&t>=0},GE=function(e,t){return t=sE(t),WE(e,t)?eE(2,e[t]):bE(e,t)},zE=function(e,t,r){return t=sE(t),!(WE(e,t)&&lE(r)&&aE(r,"value"))||aE(r,"get")||aE(r,"set")||r.configurable||aE(r,"writable")&&!r.writable||aE(r,"enumerable")&&!r.enumerable?CE(e,t,r):(e[t]=r.value,e)};Ky?(NE||(EE.f=GE,yE.f=zE,jE(LE,"buffer"),jE(LE,"byteOffset"),jE(LE,"byteLength"),jE(LE,"length")),$y({target:"Object",stat:!0,forced:!NE},{getOwnPropertyDescriptor:GE,defineProperty:zE}),Nv.exports=function(e,t,r){var i=e.match(/\d+/)[0]/8,n=e+(r?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=Jy[n],c=a,l=c&&c.prototype,d={},u=function(e,t){CE(e,t,{get:function(){return function(e,t){var r=SE(e);return r.view[o](t*i+r.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=SE(e);r&&(n=(n=RE(n))<0?0:n>255?255:255&n),o.view[s](t*i+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};NE?Yy&&(c=t((function(e,t,r,n){return Zy(e,l),TE(lE(t)?HE(t)?void 0!==n?new a(t,oE(r,i),n):void 0!==r?new a(t,oE(r,i)):new a(t):VE(t)?BE(c,t):qy(fE,c,t):new a(nE(t)),e,c)})),pE&&pE(c,ME),_E(mE(a),(function(e){e in c||tE(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,r,n){Zy(e,l);var o,s,a,d=0,h=0;if(lE(t)){if(!HE(t))return VE(t)?BE(c,t):qy(fE,c,t);o=t,h=oE(r,i);var p=t.byteLength;if(void 0===n){if(p%i)throw wE(FE);if((s=p-h)<0)throw wE(FE)}else if((s=iE(n)*i)+h>p)throw wE(FE);a=s/i}else a=nE(t),o=new kE(s=a*i);for(IE(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new PE(o)});d<a;)u(e,d++)})),pE&&pE(c,ME),l=c.prototype=uE(LE)),l.constructor!==c&&tE(l,"constructor",c),AE(l).TypedArrayConstructor=c,OE&&tE(l,OE,n);var h=c!=a;d[n]=c,$y({global:!0,constructor:!0,forced:h,sham:!NE},d),UE in c||tE(c,UE,i),UE in l||tE(l,UE,i),gE(n)}):Nv.exports=function(){},Pv("Uint8",(function(e){return function(t,r,i){return e(this,t,r,i)}}));var $E=dg,JE=Oy,qE=Vs,KE=Fe,YE=r,XE=my.aTypedArray,QE=my.exportTypedArrayMethod,ZE=c("".slice);QE("fill",(function(e){var t=arguments.length;XE(this);var r="Big"===ZE(qE(this),0,3)?JE(e):+e;return KE($E,this,r,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),YE((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var eT=b,tT=Fe,rT=my,iT=Wt,nT=ky,oT=B,sT=r,aT=eT.RangeError,cT=eT.Int8Array,lT=cT&&cT.prototype,dT=lT&&lT.set,uT=rT.aTypedArray,hT=rT.exportTypedArrayMethod,pT=!sT((function(){var e=new Uint8ClampedArray(2);return tT(dT,e,{length:1,0:3},1),3!==e[1]})),mT=pT&&rT.NATIVE_ARRAY_BUFFER_VIEWS&&sT((function(){var e=new cT(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));hT("set",(function(e){uT(this);var t=nT(arguments.length>1?arguments[1]:void 0,1),r=oT(e);if(pT)return tT(dT,this,r,t);var i=this.length,n=iT(r),o=0;if(n+t>i)throw aT("Wrong length");for(;o<n;)this[t+o]=r[o++]}),!pT||mT);var fT=K.match(/firefox\/(\d+)/i),_T=!!fT&&+fT[1],gT=/MSIE|Trident/.test(K),vT=K.match(/AppleWebKit\/(\d+)\./),yT=!!vT&&+vT[1],ET=va,TT=r,ST=et,IT=df,AT=_T,CT=gT,bT=re,RT=yT,wT=my.aTypedArray,kT=my.exportTypedArrayMethod,DT=b.Uint16Array,PT=DT&&ET(DT.prototype.sort),NT=!(!PT||TT((function(){PT(new DT(2),null)}))&&TT((function(){PT(new DT(2),{})}))),OT=!!PT&&!TT((function(){if(bT)return bT<74;if(AT)return AT<67;if(CT)return!0;if(RT)return RT<602;var e,t,r=new DT(516),i=Array(516);for(e=0;e<516;e++)t=e%4,r[e]=515-e,i[e]=e-2*t+3;for(PT(r,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(r[e]!==i[e])return!0}));kT("sort",(function(e){return void 0!==e&&ST(e),OT?PT(this,e):IT(wT(this),function(e){return function(t,r){return void 0!==e?+e(t,r)||0:r!=r?-1:t!=t?1:0===t&&0===r?1/t>0&&1/r<0?1:-1:t>r}}(e))}),!OT||NT);var MT=Vn,LT=we,xT=c,VT=W,UT=ye,FT=We,BT=fu,jT=Ts,HT=En,WT=b.Symbol,GT=WT&&WT.prototype;if(LT&&UT(WT)&&(!("description"in GT)||void 0!==WT().description)){var zT={},$T=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:BT(arguments[0]),t=FT(GT,this)?new WT(e):void 0===e?WT():WT(e);return""===e&&(zT[t]=!0),t};HT($T,WT),$T.prototype=GT,GT.constructor=$T;var JT="Symbol(test)"==String(WT("test")),qT=xT(GT.valueOf),KT=xT(GT.toString),YT=/^Symbol\((.*)\)[^)]+$/,XT=xT("".replace),QT=xT("".slice);jT(GT,"description",{configurable:!0,get:function(){var e=qT(this);if(VT(zT,e))return"";var t=KT(e),r=JT?QT(t,7,-1):XT(t,YT,"$1");return""===r?void 0:r}}),MT({global:!0,constructor:!0,forced:!0},{Symbol:$T})}var ZT=xp.charAt,eS=fu,tS=ai,rS=Ho,iS=Wo,nS="String Iterator",oS=tS.set,sS=tS.getterFor(nS);rS(String,"String",(function(e){oS(this,{type:nS,string:eS(e),index:0})}),(function(){var e,t=sS(this),r=t.string,i=t.index;return i>=r.length?iS(void 0,!0):(e=ZT(r,i),t.index+=e.length,iS(e,!1))}));var aS,cS=we,lS=c,dS=Fe,uS=r,hS=or,pS=sn,mS=li,fS=B,_S=g,gS=Object.assign,vS=Object.defineProperty,yS=lS([].concat),ES=!gS||uS((function(){if(cS&&1!==gS({b:1},gS(vS({},"a",{enumerable:!0,get:function(){vS(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol(),i="abcdefghijklmnopqrst";return e[r]=7,i.split("").forEach((function(e){t[e]=e})),7!=gS({},e)[r]||hS(gS({},t)).join("")!=i}))?function(e,t){for(var r=fS(e),i=arguments.length,n=1,o=pS.f,s=mS.f;i>n;)for(var a,c=_S(arguments[n++]),l=o?yS(hS(c),o(c)):hS(c),d=l.length,u=0;d>u;)a=l[u++],cS&&!dS(s,c,a)||(r[a]=c[a]);return r}:gS,TS=be,SS=ud,IS=Sa,AS=Fe,CS=B,bS=function(e,t,r,i){try{return i?t(TS(r)[0],r[1]):t(r)}catch(Sj){SS(e,"throw",Sj)}},RS=ql,wS=ta,kS=Wt,DS=Xm,PS=ad,NS=ed,OS=Array,MS=c,LS=2147483647,xS=/[^\0-\u007E]/,VS=/[.\u3002\uFF0E\uFF61]/g,US="Overflow: input needs wider integers to process",FS=RangeError,BS=MS(VS.exec),jS=Math.floor,HS=String.fromCharCode,WS=MS("".charCodeAt),GS=MS([].join),zS=MS([].push),$S=MS("".replace),JS=MS("".split),qS=MS("".toLowerCase),KS=function(e){return e+22+75*(e<26)},YS=function(e,t,r){var i=0;for(e=r?jS(e/700):e>>1,e+=jS(e/t);e>455;)e=jS(e/35),i+=36;return jS(i+36*e/(e+38))},XS=function(e){var t=[];e=function(e){for(var t=[],r=0,i=e.length;r<i;){var n=WS(e,r++);if(n>=55296&&n<=56319&&r<i){var o=WS(e,r++);56320==(64512&o)?zS(t,((1023&n)<<10)+(1023&o)+65536):(zS(t,n),r--)}else zS(t,n)}return t}(e);var r,i,n=e.length,o=128,s=0,a=72;for(r=0;r<e.length;r++)(i=e[r])<128&&zS(t,HS(i));var c=t.length,l=c;for(c&&zS(t,"-");l<n;){var d=LS;for(r=0;r<e.length;r++)(i=e[r])>=o&&i<d&&(d=i);var u=l+1;if(d-o>jS((LS-s)/u))throw FS(US);for(s+=(d-o)*u,o=d,r=0;r<e.length;r++){if((i=e[r])<o&&++s>LS)throw FS(US);if(i==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var f=h-m,_=36-m;zS(t,HS(KS(m+f%_))),h=jS(f/_),p+=36}zS(t,HS(KS(h))),a=YS(s,u,l==c),s=0,l++}}s++,o++}return GS(t,"")},QS=Vn,ZS=we,eI=zm,tI=b,rI=Sa,iI=c,nI=tn,oI=Ts,sI=ks,aI=W,cI=ES,lI=function(e){var t=CS(e),r=wS(this),i=arguments.length,n=i>1?arguments[1]:void 0,o=void 0!==n;o&&(n=IS(n,i>2?arguments[2]:void 0));var s,a,c,l,d,u,h=NS(t),p=0;if(!h||this===OS&&RS(h))for(s=kS(t),a=r?new this(s):OS(s);s>p;p++)u=o?n(t[p],p):t[p],DS(a,p,u);else for(d=(l=PS(t,h)).next,a=r?new this:[];!(c=AS(d,l)).done;p++)u=o?bS(l,n,[c.value,p],!0):c.value,DS(a,p,u);return a.length=p,a},dI=nf,uI=xp.codeAt,hI=function(e){var t,r,i=[],n=JS($S(qS(e),VS,"."),".");for(t=0;t<n.length;t++)r=n[t],zS(i,BS(xS,r)?"xn--"+XS(r):r);return GS(i,".")},pI=fu,mI=oo,fI=Ca,_I=C_,gI=ai,vI=gI.set,yI=gI.getterFor("URL"),EI=_I.URLSearchParams,TI=_I.getState,SI=tI.URL,II=tI.TypeError,AI=tI.parseInt,CI=Math.floor,bI=Math.pow,RI=iI("".charAt),wI=iI(/./.exec),kI=iI([].join),DI=iI(1..toString),PI=iI([].pop),NI=iI([].push),OI=iI("".replace),MI=iI([].shift),LI=iI("".split),xI=iI("".slice),VI=iI("".toLowerCase),UI=iI([].unshift),FI="Invalid scheme",BI="Invalid host",jI="Invalid port",HI=/[a-z]/i,WI=/[\d+-.a-z]/i,GI=/\d/,zI=/^0x/i,$I=/^[0-7]+$/,JI=/^\d+$/,qI=/^[\da-f]+$/i,KI=/[\0\t\n\r #%/:<>?@[\\\]^|]/,YI=/[\0\t\n\r #/:<>?@[\\\]^|]/,XI=/^[\u0000-\u0020]+/,QI=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,ZI=/[\t\n\r]/g,eA=function(e){var t,r,i,n;if("number"==typeof e){for(t=[],r=0;r<4;r++)UI(t,e%256),e=CI(e/256);return kI(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,r=1,i=null,n=0,o=0;o<8;o++)0!==e[o]?(n>r&&(t=i,r=n),i=null,n=0):(null===i&&(i=o),++n);return n>r&&(t=i,r=n),t}(e),r=0;r<8;r++)n&&0===e[r]||(n&&(n=!1),i===r?(t+=r?":":"::",n=!0):(t+=DI(e[r],16),r<7&&(t+=":")));return"["+t+"]"}return e},tA={},rA=cI({},tA,{" ":1,'"':1,"<":1,">":1,"`":1}),iA=cI({},rA,{"#":1,"?":1,"{":1,"}":1}),nA=cI({},iA,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),oA=function(e,t){var r=uI(e,0);return r>32&&r<127&&!aI(t,e)?e:encodeURIComponent(e)},sA={ftp:21,file:null,http:80,https:443,ws:80,wss:443},aA=function(e,t){var r;return 2==e.length&&wI(HI,RI(e,0))&&(":"==(r=RI(e,1))||!t&&"|"==r)},cA=function(e){var t;return e.length>1&&aA(xI(e,0,2))&&(2==e.length||"/"===(t=RI(e,2))||"\\"===t||"?"===t||"#"===t)},lA=function(e){return"."===e||"%2e"===VI(e)},dA={},uA={},hA={},pA={},mA={},fA={},_A={},gA={},vA={},yA={},EA={},TA={},SA={},IA={},AA={},CA={},bA={},RA={},wA={},kA={},DA={},PA=function(e,t,r){var i,n,o,s=pI(e);if(t){if(n=this.parse(s))throw II(n);this.searchParams=null}else{if(void 0!==r&&(i=new PA(r,!0)),n=this.parse(s,null,i))throw II(n);(o=TI(new EI)).bindURL(this),this.searchParams=o}};PA.prototype={type:"URL",parse:function(e,t,r){var i,n,o,s,a,c=this,l=t||dA,d=0,u="",h=!1,p=!1,m=!1;for(e=pI(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=OI(e,XI,""),e=OI(e,QI,"$1")),e=OI(e,ZI,""),i=lI(e);d<=i.length;){switch(n=i[d],l){case dA:if(!n||!wI(HI,n)){if(t)return FI;l=hA;continue}u+=VI(n),l=uA;break;case uA:if(n&&(wI(WI,n)||"+"==n||"-"==n||"."==n))u+=VI(n);else{if(":"!=n){if(t)return FI;u="",l=hA,d=0;continue}if(t&&(c.isSpecial()!=aI(sA,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&sA[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=IA:c.isSpecial()&&r&&r.scheme==c.scheme?l=pA:c.isSpecial()?l=gA:"/"==i[d+1]?(l=mA,d++):(c.cannotBeABaseURL=!0,NI(c.path,""),l=wA)}break;case hA:if(!r||r.cannotBeABaseURL&&"#"!=n)return FI;if(r.cannotBeABaseURL&&"#"==n){c.scheme=r.scheme,c.path=dI(r.path),c.query=r.query,c.fragment="",c.cannotBeABaseURL=!0,l=DA;break}l="file"==r.scheme?IA:fA;continue;case pA:if("/"!=n||"/"!=i[d+1]){l=fA;continue}l=vA,d++;break;case mA:if("/"==n){l=yA;break}l=RA;continue;case fA:if(c.scheme=r.scheme,n==aS)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=dI(r.path),c.query=r.query;else if("/"==n||"\\"==n&&c.isSpecial())l=_A;else if("?"==n)c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=dI(r.path),c.query="",l=kA;else{if("#"!=n){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=dI(r.path),c.path.length--,l=RA;continue}c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,c.path=dI(r.path),c.query=r.query,c.fragment="",l=DA}break;case _A:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=r.username,c.password=r.password,c.host=r.host,c.port=r.port,l=RA;continue}l=yA}else l=vA;break;case gA:if(l=vA,"/"!=n||"/"!=RI(u,d+1))continue;d++;break;case vA:if("/"!=n&&"\\"!=n){l=yA;continue}break;case yA:if("@"==n){h&&(u="%40"+u),h=!0,o=lI(u);for(var f=0;f<o.length;f++){var _=o[f];if(":"!=_||m){var g=oA(_,nA);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==aS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=lI(u).length+1,u="",l=EA}else u+=n;break;case EA:case TA:if(t&&"file"==c.scheme){l=CA;continue}if(":"!=n||p){if(n==aS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return BI;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=bA,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return BI;if(s=c.parseHost(u))return s;if(u="",l=SA,t==TA)return}break;case SA:if(!wI(GI,n)){if(n==aS||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var v=AI(u,10);if(v>65535)return jI;c.port=c.isSpecial()&&v===sA[c.scheme]?null:v,u=""}if(t)return;l=bA;continue}return jI}u+=n;break;case IA:if(c.scheme="file","/"==n||"\\"==n)l=AA;else{if(!r||"file"!=r.scheme){l=RA;continue}if(n==aS)c.host=r.host,c.path=dI(r.path),c.query=r.query;else if("?"==n)c.host=r.host,c.path=dI(r.path),c.query="",l=kA;else{if("#"!=n){cA(kI(dI(i,d),""))||(c.host=r.host,c.path=dI(r.path),c.shortenPath()),l=RA;continue}c.host=r.host,c.path=dI(r.path),c.query=r.query,c.fragment="",l=DA}}break;case AA:if("/"==n||"\\"==n){l=CA;break}r&&"file"==r.scheme&&!cA(kI(dI(i,d),""))&&(aA(r.path[0],!0)?NI(c.path,r.path[0]):c.host=r.host),l=RA;continue;case CA:if(n==aS||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&aA(u))l=RA;else if(""==u){if(c.host="",t)return;l=bA}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=bA}continue}u+=n;break;case bA:if(c.isSpecial()){if(l=RA,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=aS&&(l=RA,"/"!=n))continue}else c.fragment="",l=DA;else c.query="",l=kA;break;case RA:if(n==aS||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=VI(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||NI(c.path,"")):lA(u)?"/"==n||"\\"==n&&c.isSpecial()||NI(c.path,""):("file"==c.scheme&&!c.path.length&&aA(u)&&(c.host&&(c.host=""),u=RI(u,0)+":"),NI(c.path,u)),u="","file"==c.scheme&&(n==aS||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)MI(c.path);"?"==n?(c.query="",l=kA):"#"==n&&(c.fragment="",l=DA)}else u+=oA(n,iA);break;case wA:"?"==n?(c.query="",l=kA):"#"==n?(c.fragment="",l=DA):n!=aS&&(c.path[0]+=oA(n,tA));break;case kA:t||"#"!=n?n!=aS&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":oA(n,tA)):(c.fragment="",l=DA);break;case DA:n!=aS&&(c.fragment+=oA(n,rA))}d++}},parseHost:function(e){var t,r,i;if("["==RI(e,0)){if("]"!=RI(e,e.length-1))return BI;if(t=function(e){var t,r,i,n,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return RI(e,u)};if(":"==h()){if(":"!=RI(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=r=0;r<4&&wI(qI,h());)t=16*t+AI(h(),16),u++,r++;if("."==h()){if(0==r)return;if(u-=r,l>6)return;for(i=0;h();){if(n=null,i>0){if(!("."==h()&&i<4))return;u++}if(!wI(GI,h()))return;for(;wI(GI,h());){if(o=AI(h(),10),null===n)n=o;else{if(0==n)return;n=10*n+o}if(n>255)return;u++}c[l]=256*c[l]+n,2!=++i&&4!=i||l++}if(4!=i)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(xI(e,1,-1)),!t)return BI;this.host=t}else if(this.isSpecial()){if(e=hI(e),wI(KI,e))return BI;if(t=function(e){var t,r,i,n,o,s,a,c=LI(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(r=[],i=0;i<t;i++){if(""==(n=c[i]))return e;if(o=10,n.length>1&&"0"==RI(n,0)&&(o=wI(zI,n)?16:8,n=xI(n,8==o?1:2)),""===n)s=0;else{if(!wI(10==o?JI:8==o?$I:qI,n))return e;s=AI(n,o)}NI(r,s)}for(i=0;i<t;i++)if(s=r[i],i==t-1){if(s>=bI(256,5-t))return null}else if(s>255)return null;for(a=PI(r),i=0;i<r.length;i++)a+=r[i]*bI(256,3-i);return a}(e),null===t)return BI;this.host=t}else{if(wI(YI,e))return BI;for(t="",r=lI(e),i=0;i<r.length;i++)t+=oA(r[i],tA);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return aI(sA,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&aA(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,r=e.username,i=e.password,n=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==n?(l+="//",e.includesCredentials()&&(l+=r+(i?":"+i:"")+"@"),l+=eA(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+kI(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw II(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new NA(e.path[0]).origin}catch(Sj){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+eA(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(pI(e)+":",dA)},getUsername:function(){return this.username},setUsername:function(e){var t=lI(pI(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var r=0;r<t.length;r++)this.username+=oA(t[r],nA)}},getPassword:function(){return this.password},setPassword:function(e){var t=lI(pI(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var r=0;r<t.length;r++)this.password+=oA(t[r],nA)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?eA(e):eA(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,EA)},getHostname:function(){var e=this.host;return null===e?"":eA(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,TA)},getPort:function(){var e=this.port;return null===e?"":pI(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=pI(e))?this.port=null:this.parse(e,SA))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+kI(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,bA))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=pI(e))?this.query=null:("?"==RI(e,0)&&(e=xI(e,1)),this.query="",this.parse(e,kA)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=pI(e))?("#"==RI(e,0)&&(e=xI(e,1)),this.fragment="",this.parse(e,DA)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var NA=function(e){var t=sI(this,OA),r=fI(arguments.length,1)>1?arguments[1]:void 0,i=vI(t,new PA(e,!1,r));ZS||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},OA=NA.prototype,MA=function(e,t){return{get:function(){return yI(this)[e]()},set:t&&function(e){return yI(this)[t](e)},configurable:!0,enumerable:!0}};if(ZS&&(oI(OA,"href",MA("serialize","setHref")),oI(OA,"origin",MA("getOrigin")),oI(OA,"protocol",MA("getProtocol","setProtocol")),oI(OA,"username",MA("getUsername","setUsername")),oI(OA,"password",MA("getPassword","setPassword")),oI(OA,"host",MA("getHost","setHost")),oI(OA,"hostname",MA("getHostname","setHostname")),oI(OA,"port",MA("getPort","setPort")),oI(OA,"pathname",MA("getPathname","setPathname")),oI(OA,"search",MA("getSearch","setSearch")),oI(OA,"searchParams",MA("getSearchParams")),oI(OA,"hash",MA("getHash","setHash"))),nI(OA,"toJSON",(function(){return yI(this).serialize()}),{enumerable:!0}),nI(OA,"toString",(function(){return yI(this).serialize()}),{enumerable:!0}),SI){var LA=SI.createObjectURL,xA=SI.revokeObjectURL;LA&&nI(NA,"createObjectURL",rI(LA,SI)),xA&&nI(NA,"revokeObjectURL",rI(xA,SI))}mI(NA,"URL"),QS({global:!0,constructor:!0,forced:!eI,sham:!ZS},{URL:NA}),Pv("Float32",(function(e){return function(t,r,i){return e(this,t,r,i)}}));var VA=bs,UA="ArrayBuffer",FA=mv[UA];Vn({global:!0,constructor:!0,forced:b[UA]!==FA},{ArrayBuffer:FA}),VA(UA);var BA=Vn,jA=jh,HA=c([].reverse),WA=[1,2];BA({target:"Array",proto:!0,forced:String(WA)===String(WA.reverse())},{reverse:function(){return jA(this)&&(this.length=this.length),HA(this)}}),Pv("Int8",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Pv("Int16",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Pv("Int32",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Pv("Uint16",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Pv("Uint32",(function(e){return function(t,r,i){return e(this,t,r,i)}})),Pv("Float64",(function(e){return function(t,r,i){return e(this,t,r,i)}}));var GA=we,zA=Ts,$A=gu,JA=r,qA=b.RegExp,KA=qA.prototype,YA=GA&&JA((function(){var e=!0;try{qA(".","d")}catch(Sj){e=!1}var t={},r="",i=e?"dgimsy":"gimsy",n=function(e,i){Object.defineProperty(t,e,{get:function(){return r+=i,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var s in e&&(o.hasIndices="d"),o)n(s,o[s]);return Object.getOwnPropertyDescriptor(KA,"flags").get.call(t)!==i||r!==i}));YA&&zA(KA,"flags",{configurable:!0,get:$A}),Pv("Uint8",(function(e){return function(t,r,i){return e(this,t,r,i)}}),!0);var XA=Ye,QA=TypeError,ZA=Vn,eC=c,tC=et,rC=B,iC=Wt,nC=function(e,t){if(!delete e[t])throw QA("Cannot delete property "+XA(t)+" of "+XA(e))},oC=fu,sC=r,aC=df,cC=ip,lC=_T,dC=gT,uC=re,hC=yT,pC=[],mC=eC(pC.sort),fC=eC(pC.push),_C=sC((function(){pC.sort(void 0)})),gC=sC((function(){pC.sort(null)})),vC=cC("sort"),yC=!sC((function(){if(uC)return uC<70;if(!(lC&&lC>3)){if(dC)return!0;if(hC)return hC<603;var e,t,r,i,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:r=3;break;case 68:case 71:r=4;break;default:r=2}for(i=0;i<47;i++)pC.push({k:t+i,v:r})}for(pC.sort((function(e,t){return t.v-e.v})),i=0;i<pC.length;i++)t=pC[i].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));ZA({target:"Array",proto:!0,forced:_C||!gC||!vC||!yC},{sort:function(e){void 0!==e&&tC(e);var t=rC(this);if(yC)return void 0===e?mC(t):mC(t,e);var r,i,n=[],o=iC(t);for(i=0;i<o;i++)i in t&&fC(n,t[i]);for(aC(n,function(e){return function(t,r){return void 0===r?-1:void 0===t?1:void 0!==e?+e(t,r)||0:oC(t)>oC(r)?1:-1}}(e)),r=iC(n),i=0;i<r;)t[i]=n[i++];for(;i<o;)nC(t,i++);return t}}),(0,my.exportTypedArrayStaticMethod)("from",zy,Ty);let EC=!0,TC=!0;function SC(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function IC(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),n.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function AC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(EC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function CC(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(TC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function bC(){if("object"==typeof window){if(EC)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function RC(e,t){TC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function wC(e){return"[object Object]"===Object.prototype.toString.call(e)}function kC(e){return wC(e)?Object.keys(e).reduce((function(t,r){const i=wC(e[r]),n=i?kC(e[r]):e[r],o=i&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[r]:n})}),{}):e}function DC(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?DC(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{DC(e,e.get(t),r)}))})))}function PC(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&DC(e,r,n)}))})),n}const NC=bC;function OC(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let s=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&r.length&&t.includes("back")&&(s=r[r.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),NC("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return NC("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function MC(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function LC(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else IC(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function xC(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function VC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(n(t)))},r])})).then(r,i)}}function UC(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>PC(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),IC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>PC(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function FC(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function BC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return FC(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[r.id];if(n)n.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function jC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function HC(e,t){IC(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var WC=Object.freeze({__proto__:null,shimMediaStream:MC,shimOnTrack:LC,shimGetSendersWithDtmf:xC,shimGetStats:VC,shimSenderReceiverGetStats:UC,shimAddTrackRemoveTrackWithNative:FC,shimAddTrackRemoveTrack:BC,shimPeerConnection:jC,fixNegotiationNeeded:HC,shimGetUserMedia:OC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function GC(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){RC("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function zC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function $C(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(fR){if("TypeError"!==fR.name)throw fR;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,o)}}function JC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function qC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),IC(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function KC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){RC("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function YC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function XC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function QC(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ZC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function eb(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var tb=Object.freeze({__proto__:null,shimOnTrack:zC,shimPeerConnection:$C,shimSenderGetStats:JC,shimReceiverGetStats:qC,shimRemoveStream:KC,shimRTCDataChannel:YC,shimAddTransceiver:XC,shimGetParameters:QC,shimCreateOffer:ZC,shimCreateAnswer:eb,shimGetUserMedia:GC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function rb(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function ib(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function nb(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function ob(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(sb(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function sb(e){return e&&void 0!==e.video?Object.assign({},e,{video:kC(e.video)}):e}function ab(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(RC("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function cb(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function lb(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function db(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ub=Object.freeze({__proto__:null,shimLocalStreamsAPI:rb,shimRemoteStreamsAPI:ib,shimCallbacksAPI:nb,shimGetUserMedia:ob,shimConstraints:sb,shimRTCIceServerUrls:ab,shimTrackEventTransceiver:cb,shimCreateOfferLegacy:lb,shimAudioContext:db}),hb={};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((e=>0===e.indexOf(r)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:void 0===r[t[i]]&&(r[t[i]]=t[i+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let n=0;n<i.length;n++)r=i[n].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let o=3;o<i.length;o++){const n=i[o],s=t.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(s){const i=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+n+" ");switch(i.parameters=o.length?t.parseFmtp(o[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{n.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let n=0;return r.codecs.forEach((e=>{e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&a&&r.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,r.forEach((e=>{e.maxBitrate=d}))),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const o=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let t=0;t<i.length;t++)switch(i[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[t].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let t=0;t<r.length;t++)if(r[t].length<2||"="!==r[t].charAt(1))return!1;return!0},e.exports=t}({get exports(){return hb},set exports(e){hb=e}});var pb=hb,mb=e({__proto__:null,default:pb},[hb]);function fb(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),i=pb.parseCandidate(e.candidate);for(const e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,IC(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function _b(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||IC(e,"icecandidate",(e=>{if(e.candidate){const t=pb.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function gb(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=pb.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=pb.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=pb.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>n}),this._sctp=o}return r.apply(this,arguments)}}function vb(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},IC(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function yb(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function Eb(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function Tb(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Sb(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>r.apply(this,[e])))})}var Ib=Object.freeze({__proto__:null,shimRTCIceCandidate:fb,shimRTCIceCandidateRelayProtocol:_b,shimMaxMessageSize:gb,shimSendThrowTypeError:vb,shimConnectionState:yb,removeExtmapAllowMixed:Eb,shimAddIceCandidateNullOrEmpty:Tb,shimParameterlessSetLocalDescription:Sb});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=bC,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=SC(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=SC(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=SC(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Ib,extractVersion:SC,disableLog:AC,disableWarnings:CC,sdp:mb};switch(i.browser){case"chrome":if(!WC||!jC||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=WC,Tb(e,i),Sb(e),OC(e,i),MC(e),jC(e,i),LC(e),BC(e,i),xC(e),VC(e),UC(e),HC(e,i),fb(e),_b(e),yb(e),gb(e,i),vb(e),Eb(e,i);break;case"firefox":if(!tb||!$C||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=tb,Tb(e,i),Sb(e),GC(e,i),$C(e,i),zC(e),KC(e),JC(e),qC(e),YC(e),XC(e),QC(e),ZC(e),eb(e),fb(e),yb(e),gb(e,i),vb(e);break;case"safari":if(!ub||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=ub,Tb(e,i),Sb(e),ab(e),lb(e),nb(e),rb(e),ib(e),cb(e),ob(e),db(e),fb(e),_b(e),gb(e,i),vb(e),Eb(e,i);break;default:r("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var Ab,Cb=Object.create,bb=Object.defineProperty,Rb=Object.defineProperties,wb=Object.getOwnPropertyDescriptor,kb=Object.getOwnPropertyDescriptors,Db=Object.getOwnPropertyNames,Pb=Object.getOwnPropertySymbols,Nb=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty,Mb=Object.prototype.propertyIsEnumerable,Lb=Reflect.get,xb=Math.pow,Vb=(e,t,r)=>t in e?bb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Ub=(e,t)=>{for(var r in t||(t={}))Ob.call(t,r)&&Vb(e,r,t[r]);if(Pb)for(var r of Pb(t))Mb.call(t,r)&&Vb(e,r,t[r]);return e},Fb=(e,t)=>Rb(e,kb(t)),Bb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),jb=(e,t)=>{for(var r in t)bb(e,r,{get:t[r],enumerable:!0})},Hb=(e,t,r)=>(r=null!=e?Cb(Nb(e)):{},((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of Db(t))!Ob.call(e,n)&&n!==r&&bb(e,n,{get:()=>t[n],enumerable:!(i=wb(t,n))||i.enumerable});return e})(!t&&e&&e.__esModule?r:bb(r,"default",{value:e,enumerable:!0}),e)),Wb=(e,t,r,i)=>{for(var n,o=i>1?void 0:i?wb(t,r):t,s=e.length-1;s>=0;s--)(n=e[s])&&(o=(i?n(t,r,o):n(o))||o);return i&&o&&bb(t,r,o),o},Gb=(e,t,r)=>(Vb(e,"symbol"!=typeof t?t+"":t,r),r),zb=(e,t,r)=>Lb(Nb(e),r,t),$b=(e,t,r)=>new Promise(((i,n)=>{var o=e=>{try{a(r.next(e))}catch(gN){n(gN)}},s=e=>{try{a(r.throw(e))}catch(gN){n(gN)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(o,s);a((r=r.apply(e,t)).next())})),Jb=Bb(((e,t)=>{var r=Object.prototype.hasOwnProperty,i="~";function n(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,r,n,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,n||e,s),c=i?i+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),c.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)r.call(e,t)&&n.push(i?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},c.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,o=r.length,s=new Array(o);n<o;n++)s[n]=r[n].fn;return s},c.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},c.prototype.emit=function(e,t,r,n,o,s){var a=i?i+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,n),!0;case 5:return d.fn.call(d.context,t,r,n,o),!0;case 6:return d.fn.call(d.context,t,r,n,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,r);break;case 4:d[l].fn.call(d[l].context,t,r,n);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},c.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},c.prototype.removeListener=function(e,t,r,n){var o=i?i+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!n||s.once)&&(!r||s.context===r)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||n&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=i,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),qb=Bb(((e,t)=>{var r=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(r).forEach((function(e){r[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),Kb=Bb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:n?r[e.name]:r;(function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(r[i[o]]=t(e[o+1]))})(i.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},i=qb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,s,n)}})),t.media=o,t};var o=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}})),Yb=Bb(((e,t)=>{var r=qb(),i=/%[sdv%]/g,n=function(e){var t=1,r=arguments,n=r.length;return e.replace(i,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},o=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?i.push(r[t.name][s]):i.push(r[t.names[o]])}else i.push(r[t.name]);return n.apply(null,i)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||s,n=t.innerOrder||a,c=[];return i.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(o(t,r,e))}))}))})),e.media.forEach((function(e){c.push(o("m",r.m[0],e)),n.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(o(t,r,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),Xb=Bb((e=>{var t=Kb(),r=Yb();e.write=r,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),Qb=Bb(((e,t)=>{var r=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(r).forEach((function(e){r[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),Zb=Bb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var o=e.push?{}:n?r[e.name]:r;(function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var o=0;o<i.length;o+=1)null!=e[o+1]&&(r[i[o]]=t(e[o+1]))})(i.match(e.reg),o,e.names,e.name),e.push&&r[e.push].push(o)},i=Qb(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach((function(e){var t=e[0],n=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,s,n)}})),t.media=o,t};var o=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}}))}))}})),eR=Bb(((e,t)=>{var r=Qb(),i=/%[sdv%]/g,n=function(e){var t=1,r=arguments,n=r.length;return e.replace(i,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},o=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?i.push(r[t.name][s]):i.push(r[t.names[o]])}else i.push(r[t.name]);return n.apply(null,i)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var i=t.outerOrder||s,n=t.innerOrder||a,c=[];return i.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(o(t,r,e))}))}))})),e.media.forEach((function(e){c.push(o("m",r.m[0],e)),n.forEach((function(t){r[t].forEach((function(r){r.name in e&&null!=e[r.name]?c.push(o(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){c.push(o(t,r,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),tR=Bb((e=>{var t=Zb(),r=eR();e.write=r,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),rR=Hb(Jb()),iR=((Ab=iR||{})[Ab.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ab[Ab.INVALID_OPERATION=4097]="INVALID_OPERATION",Ab[Ab.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ab[Ab.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ab[Ab.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ab[Ab.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ab[Ab.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ab[Ab.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ab[Ab.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ab[Ab.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ab[Ab.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ab[Ab.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ab[Ab.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ab[Ab.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ab[Ab.CLIENT_BANNED=16448]="CLIENT_BANNED",Ab[Ab.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ab[Ab.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ab[Ab.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ab[Ab.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ab[Ab.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ab[Ab.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ab[Ab.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ab[Ab.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ab[Ab.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ab[Ab.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ab[Ab.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ab[Ab.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ab[Ab.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ab[Ab.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ab[Ab.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ab[Ab.UNKNOWN=65535]="UNKNOWN",Ab),nR=iR,oR=class extends Error{constructor(e){let{name:t="RtcError",message:r,code:i=nR.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in nR)if(nR[t]===e)return t;return"UNKNOWN"}(i)," 0x").concat(i.toString(16),">"),a="".concat(r).concat(o?" constraint: ".concat(o):"").concat(null!=r&&r.includes(s)?"":" ".concat(s));super(a),Gb(this,"code"),Gb(this,"extraCode"),Gb(this,"message"),Gb(this,"originMessage"),Gb(this,"name"),Gb(this,"constraint"),this.code=i,this.extraCode=n,this.name=t,this.message=a,this.constraint=o,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},sR=oR,aR=((new Date).getTime(),0),cR=function(){return(new Date).getTime()+aR},lR=function(){let e=new Date;return e.setTime(cR()),e.toLocaleString()},dR={};jb(dR,{bytes2ms:()=>vP,convertObjectNumberToInt:()=>aN,copyProperties:()=>gP,deepClone:()=>XP,deepMerge:()=>YP,delay:()=>cN,fibonacci:()=>CP,formatedTime:()=>eN,getAbilityConfigUrl:()=>oP,getConstructorName:()=>FP,getContainerFromElement:()=>ZP,getEnv:()=>lP,getInternalVersion:()=>GP,getLoggerUrl:()=>uP,getMuteStateFromFlag:()=>JP,getNetworkType:()=>pP,getNumNetworkType:()=>_P,getReconnectionTimeout:()=>bP,getStringByteLength:()=>iN,getTurnServer:()=>qP,getUint32Version:()=>sN,getValueType:()=>RP,getViewListFromView:()=>QP,glog:()=>SP,ipv4ToUint32:()=>KP,isArray:()=>MP,isAudioWorkletSupported:()=>BP,isBoolean:()=>NP,isConstructor:()=>UP,isEmpty:()=>$P,isFunction:()=>wP,isLangChinese:()=>IP,isMediaStreamTrack:()=>LP,isNumber:()=>PP,isObject:()=>OP,isOverseaSdkAppId:()=>dP,isPlainObject:()=>AP,isPortrait:()=>nN,isPromise:()=>VP,isRemoteTrack:()=>xP,isString:()=>DP,isUndefined:()=>kP,loadImage:()=>oN,ms2bytes:()=>EP,ms2samples:()=>TP,performanceNow:()=>HP,promiseAny:()=>jP,samples2ms:()=>yP,setNetworkType:()=>fP,stringify:()=>tN,stringifyIncludeValue:()=>rN,throttlePromise:()=>lN});var uR={};jb(uR,{AUDIO_MUTE_BIT:()=>XR,AUDIO_STAT_BIT:()=>YR,AUX_STAT_BIT:()=>KR,AUX_STREAM_MSID:()=>rw,BACKEND_ENV:()=>zR,BASE_DOC_URL:()=>RR,BASE_HOST:()=>IR,CAPABILITIES_KEYS:()=>Jw,CLASS_NAME:()=>Mw,CLOUD_CONSOLE_URL:()=>bR,CROSS_ROOM_BIT:()=>ew,DATA_FREEZE_TIMING:()=>Rw,DOC_URL:()=>wR,DTLS_STATE_UNKNOWN:()=>hw,ENV_NAME:()=>OR,EXCHANGE_SDP_TIMEOUT:()=>Sw,INTERVAL:()=>zw,IS_WORKER:()=>vR,IS_WORKLET:()=>yR,KIBANA_EVENT:()=>yw,LOCAL_STREAM_PUBLISH_STATE:()=>bw,LOGGER_CMD_TYPE:()=>NR,LOGGER_DOMAIN:()=>kR,LOGGER_DOMAIN_OVERSEA:()=>DR,LOG_LEVEL:()=>MR,LOG_LEVEL_NAME:()=>Fw,MAIN_STREAM_MSID:()=>tw,MAX_RTT:()=>qw,MICROPHONE_COMMUNICATIONS:()=>Uw,MICROPHONE_DEFAULT:()=>xw,MUTE_ALL_BIT:()=>ZR,NAME:()=>WR,NETWORK_TYPE:()=>VR,NOT_SUPPORTED_H264:()=>Cw,PAUSED_RETRY_COUNT:()=>Lw,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Pw,PEER_CONNECTION_STATE:()=>pw,PEER_LEAVE_REASON:()=>Bw,RAF:()=>Gw,RECOVER_CAPTURE_INTERVAL:()=>Hw,REMOTE_STREAM_TYPE_AUX:()=>nw,REMOTE_STREAM_TYPE_MAIN:()=>iw,RENDER_FREEZE_TIMING:()=>ww,RIC:()=>Ww,SCHEDULE_DOMAIN:()=>Nw,SCHEDULE_TIMEOUT:()=>Ow,SDP_SEMANTICS_PLAN_B:()=>Aw,SDP_SEMANTICS_UNIFIED_PLAN:()=>Iw,SECOND_HOST:()=>AR,SIGNAL_PING_PONG_INTERVAL:()=>xR,SIGNAL_PING_TIMEOUT:()=>LR,SIGNAL_RECONNECTION_COUNT:()=>vw,SMALL_STAT_BIT:()=>qR,SPEAKER_DEFAULT:()=>Vw,STORAGE_EXPIRES_TIME:()=>UR,STREAM_TYPE_BIG:()=>kw,STREAM_TYPE_SMALL:()=>Dw,SUBSCRIBE_SMALL_RETRY_COUNT:()=>jw,SYNC_USER_LIST_INTERVAL:()=>Ew,Scene:()=>$R,Switch:()=>FR,THIRD_HOST:()=>CR,TIMEOUT:()=>$w,TRANSPORT_DIRECTION:()=>GR,TRTC_ERROR_ASSISTANCE:()=>PR,TRTC_QUALITY_BAD:()=>lw,TRTC_QUALITY_DISCONNECTED:()=>uw,TRTC_QUALITY_EXCELLENT:()=>sw,TRTC_QUALITY_GOOD:()=>aw,TRTC_QUALITY_POOR:()=>cw,TRTC_QUALITY_UNKNOWN:()=>ow,TRTC_QUALITY_VERY_BAD:()=>dw,UPDATE_OFFER_TIMEOUT:()=>Tw,VIDEO_MUTE_BIT:()=>QR,VIDEO_STAT_BIT:()=>JR,audioProfileMap:()=>BR,getRetryCount:()=>_w,getScriptDir:()=>ER,innerVersion:()=>hR,loggerProxy:()=>TR,screenProfileMap:()=>HR,setLoggerProxy:()=>SR,setRetryCount:()=>fw,setVersion:()=>mR,version:()=>pR,videoProfileMap:()=>jR});var hR="4.15.00.1600",pR="5.0.0";function mR(e){pR=e;let[t,r,i]=e.split(".").map((e=>parseInt(e,10)));hR="".concat(t,".").concat(Math.min(15,r),".").concat(Math.min(15,i),".").concat(r.toString().padStart(2,"0")).concat(i.toString().padStart(2,"0"))}var fR,_R,gR,vR="undefined"!=typeof importScripts,yR="undefined"!=typeof registerProcessor,ER=()=>{let e=vR?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},TR="",SR=e=>TR=e,IR="web.sdk.qcloud.com",AR="web.sdk.tencent.cn",CR="web.sdk.cloud.tencent.cn",bR="https://console.cloud.tencent.com/trtc",RR="https://".concat(IR,"/trtc/webrtc/v5/doc"),wR="".concat(RR,"/zh-cn/"),kR="https://yun.tim.qq.com",DR="https://apisgp.my-imcloud.com",PR="trtc_error_assistance",NR={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},OR={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},MR=((gR=MR||{})[gR.TRACE=0]="TRACE",gR[gR.DEBUG=1]="DEBUG",gR[gR.INFO=2]="INFO",gR[gR.WARN=3]="WARN",gR[gR.ERROR=4]="ERROR",gR[gR.NONE=5]="NONE",gR),LR=18e3,xR=2e3,VR={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},UR=6048e5,FR=((_R=FR||{}).USEAINS="useAINS",_R.ENABLEDEBUG="enableDebug",_R.USEV2="useV2",_R.USEWT="useWt",_R),BR={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}},jR={"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}},HR={"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}},WR={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},GR={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},zR={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},$R=((fR=$R||{}).LIVE="live",fR.RTC="rtc",fR),JR=1,qR=2,KR=4,YR=8,XR=64,QR=16,ZR=112,ew=128,tw="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",rw="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",iw=WR.MAIN,nw=WR.AUXILIARY,ow=0,sw=1,aw=2,cw=3,lw=4,dw=5,uw=6,hw="unknown",pw={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},mw=1/0;function fw(e){mw=e}function _w(){return mw}var gw,vw=30,yw={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"},Ew=1e4,Tw=1e4,Sw=1e4,Iw="unified-plan",Aw="plan-b",Cw=1028,bw=((gw=bw||{})[gw.UNPUBLISH=-1]="UNPUBLISH",gw[gw.PUBLISHING=0]="PUBLISHING",gw[gw.PUBLISHED=1]="PUBLISHED",gw),Rw=500,ww=1e3,kw=WR.BIG,Dw=WR.SMALL,Pw=1e4,Nw={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"},Ow=2e3,Mw={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Lw=5,xw="default",Vw=xw,Uw="communications",Fw=Object.keys(MR),Bw=["normal leave","timeout leave","kick","role change"],jw=10,Hw=2e3,Ww="ric",Gw="raf",zw="interval",$w="timeout",Jw=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],qw=1e4;function Kw(e){let{url:t,body:r,method:i,timeout:n}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=n||5e3,o.open(i||"POST",t,!0),o.send(r)}))}function Yw(e){return $b(this,null,(function*(){let t=HP(),r=JSON.stringify(e);try{if(!CompressionStream||r.length<=2800)return r;let e=new Blob([r],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),i=yield(yield(yield new Response(e)).blob()).arrayBuffer();return pN.debug("compressJSON ".concat(r.length," -> ").concat(i.byteLength," ").concat(HP()-t,"ms")),i}catch(gw){return r}}))}var Xw=1e8,Qw={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"},Zw={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' is a required param when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:r,fnName:i,value:n}=e,o="".concat(t||r.name),s="";return s=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(i,"(), received type: ").concat(RP(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' cannot be '").concat(n,"' when calling ").concat(i,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:r,fnName:i,value:n}=e,o="".concat(t||r.name),s="".concat(r.instanceOf.name||r.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(i,"(), received type: ").concat(RP(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' must be one of ").concat(r.values.join("|")," when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:r,fnName:i,value:n}=e;return"the min value of ".concat(t||r.name," is ").concat(r.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:r,fnName:i,value:n}=e;return"the max value of ".concat(t||r.name," is ").concat(r.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:r}=e;return"Failed to join room - ".concat(t," code: ").concat(r)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:r,streamType:i}=e;return"failed to subscribe ".concat(r," ").concat(i," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' cannot be less than 0 when calling ").concat(i,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:r}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(r,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:r,type:i}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(r,"(), received: ").concat(i,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:r}=e;return"an error was caught in ".concat(t,".on('").concat(r,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:r,timesInSecond:i,maxSizeInSecond:n}=e;return"api ".concat(r," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):i," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},ek={};jb(ek,{ANDROID_VERSION:()=>pk,CHROME_MAJOR_VERSION:()=>fD,CHROME_VERSION:()=>_D,EDGE_VERSION:()=>Ek,EDG_MAJOR_VERSION:()=>Ik,EDG_VERSION:()=>Sk,FIREFOX_MAJOR_VERSION:()=>vk,FIREFOX_VERSION:()=>gk,HUAWEI_VERSION:()=>nD,IE_VERSION:()=>Mk,IOS_MAIN_VERSION:()=>SD,IOS_VERSION:()=>TD,IPADQQB_VERSION:()=>zk,IS_ANDROID:()=>hk,IS_ANDROID_WEBVIEW:()=>ED,IS_ANY_SAFARI:()=>vD,IS_CHROME:()=>pD,IS_CHROME_OS:()=>Kk,IS_CHROMIUM_BASE:()=>hD,IS_EDG:()=>Tk,IS_EDGE:()=>yk,IS_ELECTRON:()=>Qk,IS_FIREFOX:()=>_k,IS_HEADLESS_CHROME:()=>mD,IS_HONOR:()=>iD,IS_HUAWEI:()=>rD,IS_HUAWEIBROWSER:()=>tD,IS_IE:()=>Ok,IS_IE8:()=>Nk,IS_IOS:()=>uk,IS_IOS_13_OR_14:()=>CD,IS_IOS_15_1:()=>AD,IS_IPAD:()=>ak,IS_IPADQQB:()=>Gk,IS_IPAD_PRO:()=>ck,IS_IPHONE:()=>lk,IS_IPOD:()=>dk,IS_LINUX:()=>qk,IS_LOCAL:()=>bD,IS_MAC:()=>Jk,IS_MACQQB:()=>Hk,IS_MIBROWSER:()=>Zk,IS_MQQB:()=>Uk,IS_NATIVE_ANDROID:()=>fk,IS_OLD_ANDROID:()=>mk,IS_OPPOBROWSER:()=>aD,IS_SAFARI:()=>gD,IS_SAFARI_15_1:()=>ID,IS_SAMSUNGBROWSER:()=>oD,IS_SOGOU:()=>bk,IS_SOGOUM:()=>Ak,IS_TBS:()=>wk,IS_UCBROWSER:()=>Xk,IS_VIVOBROWSER:()=>lD,IS_WECHAT:()=>Lk,IS_WIN:()=>$k,IS_WQQB:()=>Bk,IS_WX:()=>Yk,IS_X5MQQB:()=>Vk,IS_XWEB:()=>Dk,MACQQB_VERSION:()=>Wk,MI_VERSION:()=>eD,MQQB_VERSION:()=>Fk,OPPO_VERSION:()=>cD,SAFARI_VERSION:()=>yD,SAMSUNG_VERSION:()=>sD,SOGOUM_VERSION:()=>Ck,SOGOU_VERSION:()=>Rk,TBS_VERSION:()=>kk,UA_DATA_STRING:()=>PD,USER_AGENT:()=>tk,VIVO_VERSION:()=>dD,WECHAT_VERSION:()=>xk,WQQB_VERSION:()=>jk,XWEB_VERSION:()=>Pk,browserInfo:()=>wD,getBrowserInfo:()=>kD,getChromeMajorVersion:()=>uD,getDeviceModel:()=>OD,getOSName:()=>LD,getOSNumber:()=>xD,getOSString:()=>VD,getOSType:()=>FD,getTerminalType:()=>UD,getUserAgentData:()=>ND,isLocalStorageEnabled:()=>RD});var tk="undefined"==typeof navigator?"":navigator.userAgent,rk=e=>new RegExp(e,"i").test(tk),ik=e=>{if(rk(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),r=tk.match(t);if(r&&r[1])return r[1]}return""},nk=e=>{if(rk(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),r=tk.match(t);if(r&&r[1])return parseFloat(r[1])}return NaN},ok=/AppleWebKit\/([\d.]+)/i.exec(tk),sk=ok?parseFloat(ok[1]):NaN,ak=rk("iPad"),ck="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&rk("Macintosh"),lk=rk("iPhone")&&!ak,dk=rk("iPod"),uk=lk||ak||dk||ck,hk=rk("Android"),pk=function(){if(hk){let e=tk.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),r=e[2]&&parseFloat(e[2]);if(t&&r)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),mk=hk&&rk("webkit")&&pk<2.3,fk=hk&&pk<5&&sk<537,_k=rk("Firefox"),gk=ik("Firefox"),vk=nk("Firefox"),yk=rk("Edge"),Ek=ik("Edge"),Tk=rk("Edg"),Sk=ik("Edg"),Ik=nk("Edg"),Ak=rk("SogouMobileBrowser"),Ck=ik("SogouMobileBrowser"),bk=rk("MetaSr\\s"),Rk=ik("MetaSr\\s"),wk=rk("TBS"),kk=ik("TBS"),Dk=rk("XWEB"),Pk=ik("XWEB"),Nk=rk("MSIE\\s8\\.0"),Ok=rk("MSIE\\/\\d+"),Mk=function(){if(Ok){let e=/MSIE\s(\d+)\.\d/.exec(tk),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(tk)&&/rv:11.0/.test(tk)&&(t=11),t}return NaN}(),Lk=rk("(micromessenger|webbrowser)"),xk=ik("MicroMessenger"),Vk=!wk&&rk("MQQBrowser")&&rk("COVC"),Uk=!wk&&rk("MQQBrowser")&&!rk("COVC"),Fk=Uk||Vk?ik("MQQBrowser"):"",Bk=!wk&&rk(" QQBrowser"),jk=ik(" QQBrowser"),Hk=!wk&&rk("QQBrowserLite"),Wk=ik("QQBrowserLite"),Gk=!wk&&rk("MQBHD"),zk=ik("MQBHD"),$k=rk("Windows"),Jk=!uk&&rk("MAC OS X"),qk=!hk&&rk("Linux"),Kk=rk("CrOS"),Yk=rk("MicroMessenger"),Xk=rk("UCBrowser"),Qk=rk("Electron"),Zk=rk("MiuiBrowser"),eD=ik("MiuiBrowser"),tD=rk("HuaweiBrowser"),rD=rk("Huawei")||rk("HUAWEI"),iD=rk("Honor")||rk("HONOR"),nD=ik("HuaweiBrowser"),oD=rk("SamsungBrowser"),sD=ik("SamsungBrowser"),aD=rk("HeyTapBrowser"),cD=ik("HeyTapBrowser"),lD=rk("VivoBrowser"),dD=ik("VivoBrowser"),uD=()=>nk("Chrome"),hD=rk("Chrome"),pD=!yk&&!bk&&!Ak&&!wk&&!Dk&&!Tk&&!Bk&&!Zk&&!tD&&!oD&&!aD&&!lD&&hD,mD=rk("HeadlessChrome"),fD=uD(),_D=ik("Chrome"),gD=!hD&&!Uk&&!Vk&&!Hk&&!Gk&&rk("Safari"),vD=gD||uk,yD=ik("Version"),ED=/Android.*(wv|.0.0.0)/.test(tk),TD=(()=>{if(ck)return yD;if(uk){let e=tk.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),SD=Number(TD.split(".")[0]),ID="15.1"===yD,AD="15.1"===TD,CD=(()=>{let e=Number(TD.split(".")[0]);return 14===e||13===e})(),bD="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),RD=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(yN){e=!1}return e}})(),wD=kD();function kD(){let e=new Map([[_k,["Firefox",gk]],[Tk,["Edg",Sk]],[pD,["Chrome",_D]],[gD,["Safari",yD]],[wk,["TBS",kk]],[Dk,["XWEB",Pk]],[Lk&&lk,["WeChat",xk]],[Bk,["QQ(Win)",jk]],[Uk,["QQ(Mobile)",Fk]],[Vk,["QQ(Mobile X5)",Fk]],[Hk,["QQ(Mac)",Wk]],[Gk,["QQ(iPad)",zk]],[Zk,["MI",eD]],[tD,["HW",nD]],[oD,["Samsung",sD]],[aD,["OPPO",cD]],[lD,["VIVO",dD]],[yk,["EDGE",Ek]],[Ak,["SogouMobile",Ck]],[bk,["Sogou",Rk]]]),t="unknown",r="unknown";return e.has(!0)&&([t,r]=e.get(!0)),{name:t,version:r}}var DD=null,PD="";function ND(){return $b(this,null,(function*(){if(DD)return DD;if(!navigator.userAgentData||"function"!=typeof navigator.userAgentData.getHighEntropyValues)return null;try{return(DD=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!PD&&(PD="UAData: ".concat(DD.platform,"/").concat(DD.platformVersion),DD.architecture&&DD.bitness&&(PD+=" ".concat(DD.architecture,"/").concat(DD.bitness)),DD.mobile&&(PD+=" mobile"),DD.model&&(PD+=" model: ".concat(DD.model)),DD.fullVersionList&&(PD+=" ".concat(DD.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(",")))),DD}catch(gx){return null}}))}function OD(){return(null==DD?void 0:DD.model)||""}var MD=new Map([[hk,"Android"],[uk,"iOS"],[$k,"Windows"],[Jk,"MacOS"],[qk,"Linux"],[Kk,"ChromeOS"]]),LD=function(){return MD.get(!0)?MD.get(!0):DD?DD.platform:"unknown"};function xD(){return $k?1:hk?2:Jk?3:uk?4:qk?5:Kk?6:0}var VD=()=>{let e=LD();return e+="/".concat(wD.name,"/").concat(gD?wD.version:wD.version.split(".")[0]),null!=DD&&DD.platformVersion&&(e+="/".concat(DD.platformVersion)),null!=DD&&DD.architecture&&(e+="/".concat(DD.architecture)),e};function UD(){return hk?4:lk?2:ak?3:Jk?12:$k?5:qk?13:1}function FD(){return hk?"Android":lk?"iPhone":ak?"iPad":Jk?"Mac":$k?"Windows":qk?"Linux":"unknown"}var BD=(e,t)=>t?"".concat(RR,"/").concat(e,"/").concat(t):"".concat(RR,"/").concat(e,"/index.html"),jD=()=>{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(PR);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let r=window.TRTC_ERROR_INFO,i=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:i}}return{}};function HD(e){let{key:t,data:r,link:i,addDocLink:n=!0}=e,o="",s="",a="";wP(Zw[t])?o=Zw[t](r):DP(Zw[t])&&(o=Zw[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=jD();i?a="".concat(i.className,".html#").concat(i.fnName):l&&l[t]&&(wP(l[t])?a=l[t](r):DP(l[t])&&(a=l[t]));let d=o;return IP()&&(c&&c[t]&&(wP(c[t])?s=c[t](r):DP(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(BD("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(BD("en",a),"\n")),d}var WD=Object.prototype.hasOwnProperty,GD=e=>"function"==typeof e,zD=e=>void 0===e;function $D(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 r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)}(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(WD.call(e,t))return!1;return!0}return!1}var JD,qD=function(e){let{retryFunction:t,settings:r,onError:i,onRetrying:n,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=r,h=0,p=-1,m=0,f=(e,r)=>$b(this,null,(function*(){let l=a||this;try{let r=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(r)}catch(_){let t=()=>{clearTimeout(p),h=0,m=2,r(_)},s=()=>{2!==m&&h<(GD(d)?d():d)?(h++,m=1,GD(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,f(e,r)}),GD(u)?u(h):u)):(t(),GD(o)&&o.call(this,_))};GD(i)?i.call(this,{error:_,retry:s,reject:r,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(f)}},KD=new(Hb(Jb(),1).default),YD=((JD=YD||{}).ROOM_DESTROY="1",JD.JOIN_START="21",JD.JOIN_SCHEDULE_SUCCESS="22",JD.JOIN_SIGNAL_CONNECTION_START="23",JD.JOIN_SIGNAL_CONNECTION_END="24",JD.JOIN_SEND_CMD="25",JD.JOIN_RECEIVED_CMD_RES="26",JD.JOIN_SUCCESS="27",JD.JOIN_FAILED="28",JD.LEAVE_START="51",JD.LEAVE_SEND_CMD="52",JD.LEAVE_SUCCESS="53",JD.PUBLISH_START="61",JD.SEND_FIRST_VIDEO_FRAME="62",JD.PUBLISH_FAILED="63",JD.SUBSCRIBE_START="81",JD.SUBSCRIBE_SUCCESS="82",JD.SUBSCRIBE_FAILED="84",JD.UNSUBSCRIBE_SUCCESS="83",JD.LOCAL_TRACK_CAPTURE_START="101",JD.LOCAL_TRACK_CAPTURE_SUCCESS="102",JD.LOCAL_TRACK_CAPTURE_FAILED="103",JD.LOCAL_TRACK_PUBLISHED="104",JD.LOCAL_TRACK_UNPUBLISHED="105",JD.LOCAL_TRACK_REPLACED="106",JD.SWITCH_DEVICE_SUCCESS="107",JD.TRACK_MUTED="108",JD.TRACK_UNMUTED="109",JD.REMOTE_TRACK_SUBSCRIBED="110",JD.REMOTE_TRACK_UNSUBSCRIBED="111",JD.LOCAL_TRACK_RECAPTURE="112",JD.PLAY_TRACK_START="151",JD.PLAYER_STATE_CHANGED="152",JD.VIDEO_LOADED_DATA="153",JD.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",JD.SIGNAL_CONNECTION_STATE_CHANGED="201",JD.PEER_CONNECTION_STATE_CHANGED="202",JD.SINGLE_CONNECTION_STAT="203",JD.SPC_RECONNECTED="204",JD.HEARTBEAT_REPORT="251",JD.RECEIVED_PUBLISHED_USER_LIST="252",JD.REMOTE_PUBLISH_STATE_CHANGED="253",JD.AUDIO_LEVEL_INTERVAL="260",JD.NETWORK_QUALITY="261",JD.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",JD.QUALITY_LIMITATION_CHANGED="263",JD.LOG="264",JD),XD=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:pR,env:OR.QCLOUD,browserVersion:wD.name+wD.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:r,userId:i,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=r,this._configs.userId=i,this._roomIdMap.set(i,String(n))}logSuccessEvent(e){bD||!pN.isAbleToUpload||this._configs.env===OR.QCLOUD&&this.uploadEventToKibana(Fb(Ub({},e),{result:"success"}))}logFailedEvent(e){if(bD||!pN.isAbleToUpload)return;let{eventType:t,code:r,error:i,userId:n}=e,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:r||(null==i?void 0:i.extraCode)||(null==i?void 0:i.code)||nR.UNKNOWN};this._configs.env===OR.QCLOUD&&this.uploadEventToKibana(Fb(Ub({},o),{error:i}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:r,error:i}=e,n={timestamp:lR(),sdkAppId:this._configs.sdkAppId,userId:r||this._configs.userId,version:pR,log:t};i&&(n.errorInfo=i.message,i.stack&&(n.errorInfo+="\n".concat(i.stack))),this.sendRequest(uP(this._configs.sdkAppId,NR.LOG),n)}sendRequest(e,t){pN.isAbleToUpload?Kw({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},QD=null,ZD=!0;function eP(e){NP(e)&&e!==ZD&&(ZD=e,pN.info("setIsNeedToSchedule ".concat(e)))}function tP(e){return $b(this,arguments,(function(e){let{userId:t,sdkAppId:r,useStringRoomId:i,roomId:n,userSig:o,version:s,frameWorkType:a,role:c,latencyLevel:l}=e;return function*(){if(!ZD&&QD)return{isCached:!0,result:QD};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let d=new FormData;d.append("userId",String(t)),d.append("sdkAppId",String(r)),d.append("isStrGroupId",String(i)),d.append("groupId",String(n)),d.append("sdkVersion",s),d.append("userSig",String(o)),c&&d.append("role",String(c)),l&&d.append("latencyLevel",String(l)),a&&d.append("frameWorkType",String(a));let u=HP(),h=yield function(e,t,r){return new Promise(((i,n)=>{let o=null;jP([cP((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=i.message,o||(s>=1&&(a[0]=nP(r,WR.MAIN,!0)),n())}))(nP(r,WR.MAIN),e,{get timeout(){return 1e3*CP(2+t.count[0])}}),cP((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[1]=i.message,o||(s>=2&&(a[0]=nP(r,WR.BACKUP,!0)),n())}))(nP(r,WR.BACKUP),e,{get timeout(){return 1e3*CP(2+t.count[1])}})]).then((e=>{o=e,i(o)})).catch(n)}))}(d,e,r);h.config&&(h.config.loggerDomain&&SR(h.config.loggerDomain),NP(h.config.scheduleCache)&&eP(!h.config.scheduleCache)),e.delta=HP()-u;let p=function(e,t,r){let i={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let n=performance.getEntriesByType("resource"),o=nP(e,WR.MAIN),s=nP(e,WR.BACKUP);for(let e of n)if(e.startTime>=r&&(e.name===o||e.name===s)&&e.transferSize>0){let r=e.name===o?WR.MAIN:WR.BACKUP,n=Math.round(e.duration),s=Math.round(e.domainLookupStart-e.startTime),a=e.redirectStart>0?Math.round(e.redirectEnd-e.redirectStart):0,c=e.fetchStart>0?Math.round(e.domainLookupStart-e.fetchStart):0,l=Math.round(e.domainLookupEnd-e.domainLookupStart),d=Math.round(e.requestStart-e.secureConnectionStart),u=Math.round(e.secureConnectionStart-e.connectStart),h=Math.round(e.responseStart-e.requestStart),p=Math.round(e.responseEnd-e.responseStart),m=[l,d,u,h,p];XD.uploadEvent({log:"stat-schedule-net:".concat(n,"(").concat(s,"(").concat(a,"->").concat(c,")->").concat(m.join("->"),") ").concat(r),userId:t}),i=Fb(Ub({},i),{totalCost:n,local:s,dns:l,tcp:u,tls:d,request:h,response:p});break}}catch(o){pN.error("getScheduleDetailCost error",o)}return i}(Number(r),t,u);return QD=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=MP(d)?d[0]:d,t=PP(e.code)?e.code:0,r="schedule failed".concat(e.message?": ".concat(e.message):""),i=new sR({code:nR.SCHEDULE_FAILED,extraCode:t,message:HD({key:Qw.JOIN_ROOM_FAILED,data:{error:r,code:t}})});throw pN.error(r,t),i}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(Nw).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),KD.on("28",(()=>eP(!0))),KD.on("63",(()=>eP(!0))),KD.on("84",(()=>eP(!0))),KD.on("201",(e=>{"RECONNECTING"===e.state&&eP(!0)})),KD.on("202",(e=>{"RECONNECTING"===e.state&&eP(!0)}));var rP={main:"",backup:""};function iP(e){MP(e)?(rP.main=e[0],rP.backup=e[1]):rP.main=e}function nP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WR.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(rP[t]||sP(e,t,r),"/api/v1/config")}function oP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WR.MAIN;return"https://".concat(rP[t]||sP(e,t),"/api/v1/trtcAutoConf")}function sP(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WR.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t=dP(e)?i?r===WR.MAIN?Nw.MAIN_OVERSEA_BACKUP:Nw.BACKUP_OVERSEA:r===WR.MAIN?Nw.MAIN_OVERSEA:Nw.BACKUP_OVERSEA:r===WR.MAIN?Nw.MAIN:Nw.BACKUP,t}function aP(e,t,r){return new Promise(((i,n)=>{Kw({url:e,body:t,timeout:r.timeout}).then((e=>{0===e.data.code?i(e.data.data):n({code:e.data.code,message:e.data.msg})})).catch(n)}))}var cP=(e,t)=>qD({retryFunction:aP,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var lP=function(){return new URLSearchParams(location.search).get("trtc_env")||""},dP=e=>Number(e)<14e8,uP=function(e,t){let r;r=TR||(dP(e)?DR:kR);let i=Math.floor(Math.random()*xb(2,31));return"".concat(r,"/v5/AVQualityReportSvc/C2S?random=").concat(i,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},hP="unknown";function pP(){if("unknown"!==hP)return hP;let{userAgent:e,connection:t}=navigator,r=(e.match(/NetType\/\S+/)||[])[0]||"";r=r.toLowerCase().replace("nettype/",""),"3gnet"===r&&(r="3g");let i=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===n&&(n="2g"),i&&(hP=mP(i,n)),hP}function mP(e,t){if(VR[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function fP(e){hP=mP(e)}function _P(){return VR[pP()]}function gP(e,t){for(let r of Reflect.ownKeys(t))if("constructor"!==r&&"prototype"!==r&&"name"!==r){let i=Object.getOwnPropertyDescriptor(t,r)||"";Object.defineProperty(e,r,i)}return e}function vP(e){return yP(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function yP(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function EP(e){return 4*TP(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function TP(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var SP="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},IP=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},AP=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);if(null===t)return!0;let r=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function CP(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:CP(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function bP(e){return e>8?3e4:1e3*CP(e)}function RP(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var wP=e=>"function"==typeof e,kP=e=>void 0===e,DP=e=>"string"==typeof e,PP=e=>"number"==typeof e,NP=e=>"boolean"==typeof e,OP=e=>"object"===RP(e),MP=e=>"array"===RP(e),LP=e=>RP(e)==="MediaStreamTrack".toLowerCase(),xP=e=>e.isRemote,VP=e=>"promise"===RP(e),UP=e=>wP(e)&&e.prototype.constructor===e,FP=e=>UP(e)?e.prototype.constructor.name:"",BP="undefined"!=typeof AudioWorkletNode;function jP(e){return new Promise(((t,r)=>{let i=[];e.forEach((n=>{n.then(t).catch((t=>{i.push(t),i.length===e.length&&r(i)}))}))}))}function HP(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var WP=e=>+e<10?"0".concat(e):e,GP=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let r=t.split("."),i=WP(r[1])+WP(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),"".concat(r.join("."),".").concat(i)},zP=Object.prototype.hasOwnProperty;function $P(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(AP(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(zP.call(e,t))return!1;return!0}return!1}function JP(e,t){return{userId:t,hasAudio:!!(e&YR),hasVideo:!!(e&JR),hasAuxiliary:!!(e&KR),hasSmall:!!(e&qR),audioMuted:!!(e&XR),videoMuted:!!(e&QR),audioAvailable:!(!(e&YR)||e&XR),videoAvailable:!(!(e&JR)||e&QR)}}function qP(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!kP(e.username)&&!kP(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",kP(e.credentialType)||(t.credentialType=e.credentialType)),t}function KP(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!DP(e))return 0;let r=e.split(".");return t?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var YP=function(e,t,r,i){if(!OP(e)||!OP(t))return 0;let n,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(kP(t[n])||r&&r.includes(n)))if(OP(e[n])&&OP(t[n]))o+=YP(e[n],t[n],r,i);else{if(i&&i.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=XP(t[n]),o+=1)}return o};function XP(e){if(MP(e)){let t=[];return e.forEach(((e,r)=>{t[r]=XP(e)})),t}if(OP(e)){let t={};return Object.keys(e).forEach((r=>{t[r]=XP(e[r])})),t}return e}var QP=e=>{let t=[];if(MP(e))t=[...e];else if(DP(e)){let r=document.getElementById(e);r&&t.push(r)}else e&&t.push(e);return t},ZP=e=>DP(e)?document.getElementById(e):e,eN=()=>(e=>{let t=e=>e<10?"0".concat(e):"".concat(e),r=e.getFullYear(),i=e.getMonth()+1,n=e.getDate(),o=t(e.getHours()),s=t(e.getMinutes()),a=t(e.getSeconds());return"".concat(r,"/").concat(i,"/").concat(n," ").concat(o,":").concat(s,":").concat(a)})(new Date);function tN(e,t){let{keysToInclude:r,keysToExclude:i}=t;try{if(MP(e))return"[".concat(e.map((e=>tN(e,{keysToInclude:r,keysToExclude:i}))).join(","),"]");if(!AP(e)||!MP(r)&&!MP(i))return JSON.stringify(e);let t={},n=new Set(r),o=new Set(i);return Object.keys(e).forEach((s=>{(0===o.size&&n.has(s)||0===n.size&&!o.has(s))&&(t[s]=AP(e[s])||MP(e[s])?JSON.parse(tN(e[s],{keysToExclude:i,keysToInclude:r})):e[s])})),JSON.stringify(t)}catch(gw){return"{}"}}function rN(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=[];return Object.keys(e).forEach((i=>{t===e[i]&&r.push(i)})),tN(e,{keysToInclude:r})}function iN(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var nN=()=>{var e,t,r,i;return null!=(e=window.screen)&&e.orientation?!(null==(i=null==(r=null==(t=window.screen)?void 0:t.orientation)?void 0:r.type)||!i.includes("portrait")):0===window.orientation||180===window.orientation},oN=e=>$b(void 0,null,(function*(){return new Promise(((t,r)=>{let i;if(DP(e))i=new Image,i.crossOrigin="anonymous",i.src=e;else if(i=e,i.complete)return void t(i);i.onload=()=>t(i),i.onerror=()=>{r(new sR({code:nR.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}}))})),sN=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},aN=e=>(Object.keys(e).forEach((t=>{PP(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(AP(e[t])||MP(e[t]))&&aN(e[t])})),e);function cN(e,t){return new Promise((r=>{let i=setTimeout(r,e);t&&t(i)}))}var lN=(e,t)=>{let r=null;return function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];return r||(r=e.apply(t||this,n),r.finally((()=>r=null)),r)}},dN=class{constructor(e){Gb(this,"userId"),Gb(this,"remoteUserId"),Gb(this,"id"),Gb(this,"sdkAppId"),Gb(this,"type"),Gb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal="boolean"!=typeof e.isLocal||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){let r=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(r?"|".concat(r):"","]")),pN.log(e,t,zD(this.userId)||$D(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(2,t)}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(1,t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(4,t)}},uN=YD,hN=!(uk||hk||mD),pN=new class{constructor(){Gb(this,"_isEnableUploadLog",!0),Gb(this,"_localJoinedUser",new Map),Gb(this,"_queue",[]),Gb(this,"_timeoutId",-1),Gb(this,"_logLevel",1),Gb(this,"_logLevelToUpload",2),!vR&&!yR&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){KD.on(uN.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var r;(null==(r=null==t?void 0:t.config)?void 0:r.logLevelToUpload)&&MR[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),KD.on(uN.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),KD.once(uN.JOIN_FAILED,(()=>{this.startUpload()})),KD.on(uN.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let r=this._queue[t];if(r.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:i,sdkAppId:n}=t;e.map.has(i)?e.map.get(i).logs.push(r):e.map.set(i,{userId:i,sdkAppId:n,logs:[r]})}));else if(DP(r.userId)&&PP(r.sdkAppId)){let{userId:t,sdkAppId:i}=r;e.map.has(t)?e.map.get(t).logs.push(r):e.map.set(t,{userId:t,sdkAppId:i,logs:[r]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return $b(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:r,sdkAppId:i,logs:n}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:lR(),sdkAppId:String(i),userId:r,version:pR,log:n.map((e=>e.log)).join("\n")}),i),n.forEach((e=>e.uploaded=!0))}}catch(_R){}let r=t.filter((e=>!e.uploaded));r.length>0&&(this._queue=r.concat(this._queue))}))}uploadLogWithRetry(e,t){return qD({retryFunction:()=>Kw({url:uP(t,NR.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(cR());let r=String(t.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(r,"] <").concat(MR[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){kP(MR[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(DP(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(fR){return""}}log(e,t){let r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;var o;t.unshift(this.getPrefix(e));let s={log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:i,sdkAppId:n,forAllJoinedClients:r};if(KD.emit(uN.LOG,{log:s}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(s),e<this._logLevel)return;let a=(null==(o=MR[e])?void 0:o.toLowerCase())||"info";hN?console[a]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[a](...t)}debug(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.log(4,t)}createLogger(e){return new dN(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;MR[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},mN=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)}))},fN=new class{constructor(){Gb(this,"_prefix","TRTC"),Gb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){RD()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let r=JSON.parse(t);if(r&&r.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(RD())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(yN){pN.warn(yN)}}getItem(e){if(!RD())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let r=JSON.parse(t);return r&&r.expiresIn>=Date.now()?r.value:null}catch(fR){pN.warn(fR)}}setItem(e,t){if(RD())try{let r={expiresIn:Date.now()+UR,value:t};this._queue.set(this.getRealKey(e),r)}catch(gw){pN.warn(gw)}}deleteItem(e){if(!RD())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(fR){return pN.warn(fR),!1}}clear(){if(RD())try{localStorage.clear()}catch(yN){pN.warn(yN)}}},_N={};jb(_N,{HTTPS_API:()=>$N,IS_GET_CAPABILITIES_SUPPORTED:()=>uO,IS_GET_SETTINGS_SUPPORTED:()=>dO,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>lO,IS_INSERTABLE_STREAM_SUPPORTED:()=>hO,IS_RTC_RTP_SENDER_SUPPORTED:()=>sO,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>pO,IS_SEI_SUPPORTED:()=>mO,IS_SPC_SUPPORTED:()=>nO,basis:()=>EO,checkSystemRequirementsInternal:()=>HN,decodeSupportStatus:()=>jN,encodeSupportStatus:()=>BN,getBrowserInfo:()=>ON,getDisplayResolution:()=>qN,isAddTransceiverSupported:()=>iO,isBrowserSupported:()=>MN,isGetReceiversSupported:()=>eO,isGetSendersSupported:()=>tO,isGetTransceiversSupported:()=>rO,isGetUserMediaSupported:()=>KN,isMediaDevicesSupported:()=>xN,isMediaSessionSupported:()=>gO,isMediaStreamTrackProcessorSupported:()=>FN,isReplaceTrackSupported:()=>aO,isRequestVideoFrameCallbackSupported:()=>SO,isSIMDSupported:()=>yO,isScreenCaptureApiAvailable:()=>GN,isSelectedCandidatePair:()=>JN,isSetParametersSupported:()=>cO,isSmallStreamAPISupported:()=>XN,isSmallStreamSupported:()=>QN,isStopTransceiverSupported:()=>oO,isTRTCSupported:()=>WN,isUnifiedPlanDefault:()=>ZN,isUsedInHttpProtocol:()=>UN,isWebAudioSupported:()=>YN,isWebCodecSupported:()=>_O,isWebCodecsSupported:()=>LN,isWebRTCSupported:()=>fO,isWebTransportSupported:()=>vO});var gN,vN,yN,EN=Hb(Xb(),1),TN=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=pN.createLogger({id:"kv"}),e&&(KD.on("102",(e=>{let{track:t,cost:r}=e;this.addSuccessEvent({key:t.kind===WR.AUDIO?bN.START_MICROPHONE:RN.START_CAMERA,cost:r})})),KD.on("103",(e=>{let{track:t,error:r}=e;this.addFailedEvent({key:t.kind===WR.AUDIO?bN.START_MICROPHONE:RN.START_CAMERA,error:r})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:sN(this.version||pR),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map((e=>{let[t,r]=e;return{uint32_key:t,uint32_count:r}})),stats_distribution:[...this.distributionMap.entries()].map((e=>{let[t,r]=e;return{uint32_key:t,distribution_items:[...r.entries()].map((e=>{let[t,r]=e;return{uint32_item_key:t,uint32_item_value:r}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:r=!1}=e;this.isCountKey(t)?r&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:r,useUV:i=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(i&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=(null==(n=this.distributionMap)?void 0:n.get(t))||new Map;o.set(r,(o.get(r)||0)+1),this.distributionMap.set(t,o)}addNumber(e){let{key:t,value:r,split:i=100,useUV:n=!1}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=(null==(o=this.distributionMap)?void 0:o.get(t))||new Map,a=0;if(PP(i))a=Math.floor(r/i);else for(let c=i.length-1;c>0;c--)if(r>i[c]){a=c;break}s.set(a,(s.get(a)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent(e){let{key:t,cost:r,timeKey:i,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),r)){let e=+String(t).slice(-3);e<800&&e>=700?this.addNumber({key:i||t+100,value:r,split:n}):i||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:r}=e;if(!t)return;let i=nR.UNKNOWN;r&&(PP(r)?i=r:(!kP(r.extraCode)||!kP(r.code))&&(i=r.extraCode||r.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:i,useUV:!1})}},SN=((vN=SN||{})[vN.enterRoom=500700]="enterRoom",vN[vN.exitRoom=500701]="exitRoom",vN[vN.switchRole=500702]="switchRole",vN[vN.destroy=500703]="destroy",vN[vN.startLocalAudio=500704]="startLocalAudio",vN[vN.updateLocalAudio=500705]="updateLocalAudio",vN[vN.stopLocalAudio=500706]="stopLocalAudio",vN[vN.startLocalVideo=500707]="startLocalVideo",vN[vN.updateLocalVideo=500708]="updateLocalVideo",vN[vN.stopLocalVideo=500709]="stopLocalVideo",vN[vN.startScreenShare=500710]="startScreenShare",vN[vN.updateScreenShare=500711]="updateScreenShare",vN[vN.stopScreenShare=500712]="stopScreenShare",vN[vN.startRemoteVideo=500713]="startRemoteVideo",vN[vN.updateRemoteVideo=500714]="updateRemoteVideo",vN[vN.stopRemoteVideo=500715]="stopRemoteVideo",vN[vN.muteRemoteAudio=500716]="muteRemoteAudio",vN[vN.setRemoteAudioVolume=500717]="setRemoteAudioVolume",vN[vN.use=500718]="use",vN[vN.sendSEIMessage=5e5]="sendSEIMessage",vN[vN.sendCustomMessage=500001]="sendCustomMessage",vN),IN=((gN=IN||{})[gN.AudioMixer=550700]="AudioMixer",gN[gN.AIDenoiser=551700]="AIDenoiser",gN[gN.VirtualBackground=570700]="VirtualBackground",gN[gN.Beauty=571700]="Beauty",gN[gN.Watermark=572700]="Watermark",gN[gN.BasicBeauty=574700]="BasicBeauty",gN[gN.CDNStreaming=590700]="CDNStreaming",gN[gN.DeviceDetector=591700]="DeviceDetector",gN[gN.Debug=592700]="Debug",gN),AN=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e))(AN||{}),CN=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e))(CN||{}),bN=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(bN||{}),RN=((yN=RN||{})[yN.START_CAMERA=511700]="START_CAMERA",yN),wN=new TN(!0),kN=new TN(!1),DN=wN,PN={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},NN=new Map([[_k,["Firefox",gk]],[Tk,["Edg",Sk]],[pD,["Chrome",_D]],[gD,["Safari",yD]],[wk,["TBS",kk]],[Dk,["XWEB",Pk]],[Lk&&lk,["WeChat",xk]],[Bk,["QQ(Win)",jk]],[Uk,["QQ(Mobile)",Fk]],[Vk,["QQ(Mobile X5)",Fk]],[Hk,["QQ(Mac)",Wk]],[Gk,["QQ(iPad)",zk]],[Zk,["MI",eD]],[tD,["HW",nD]],[oD,["Samsung",sD]],[aD,["OPPO",cD]],[lD,["VIVO",dD]],[yk,["EDGE",Ek]],[Ak,["SogouMobile",Ck]],[bk,["Sogou",Rk]]]);function ON(){let e=NN.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var MN=function(){return!(Xk||yk||Tk&&Ik<80||_k&&vk<56)},LN=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},xN=function(){if(!navigator.mediaDevices)return UN()||pN.error(Zw.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},VN=!1;function UN(){return"http:"===location.protocol&&!bD&&(VN||pN.error(HD({key:Qw.NOT_SUPPORTED_HTTP})),VN=!0,!0)}var FN=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},BN=function(){return $b(this,null,(function*(){if(PN.detail.isH264EncodeSupported&&PN.detail.isVp8EncodeSupported)return{isH264EncodeSupported:PN.detail.isH264EncodeSupported,isVp8EncodeSupported:PN.detail.isVp8EncodeSupported};let e,t=!1,r=!1;try{let i=new RTCPeerConnection,n=document.createElement(WR.CANVAS);n.getContext("2d");let o=n.captureStream(0);return i.addTrack(o.getVideoTracks()[0],o),e=yield i.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(r=!0),i.close(),PN.detail.isH264EncodeSupported=t,PN.detail.isVp8EncodeSupported=r,{isH264EncodeSupported:PN.detail.isH264EncodeSupported,isVp8EncodeSupported:PN.detail.isVp8EncodeSupported}}catch(gw){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},jN=function(){return $b(this,null,(function*(){if(PN.detail.isH264DecodeSupported&&PN.detail.isVp8DecodeSupported)return{isH264DecodeSupported:PN.detail.isH264DecodeSupported,isVp8DecodeSupported:PN.detail.isVp8DecodeSupported};let e,t=!1,r=!1;try{let i=new RTCPeerConnection;return e=yield i.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(r=!0),i.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:r}}catch(gw){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},HN=lN((()=>$b(void 0,null,(function*(){if(PN.result&&PN.detail.isH264EncodeSupported&&PN.detail.isVp8EncodeSupported&&PN.detail.isH264DecodeSupported&&PN.detail.isVp8DecodeSupported)return PN;let e=Date.now(),t=MN(),r=fO(),i=LN(),n=xN(),{isH264EncodeSupported:o,isVp8EncodeSupported:s}=yield BN(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield jN();if(!o||!s){let e=yield BN();pN.warn("detect encode again h264:".concat(o," vp8:").concat(s," result: ").concat(JSON.stringify(e))),o=e.isH264EncodeSupported,s=e.isVp8EncodeSupported}if(o&&a&&(aD||lD||ED)&&!wk&&uD()<79){let{encode:e,decode:t}=yield function(){return $b(this,null,(function*(){return zN||(zN=new Promise((e=>$b(this,null,(function*(){let t={encode:!1,decode:!1},r=()=>{};try{pN.warn("detectH264Supported start");let i=document.createElement("canvas"),n=i.getContext("2d");i.width=320,i.height=240;let o=setInterval((()=>{n.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,a=-1;r=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{r(),e(t)}),2e3);let c=i.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>d.addIceCandidate(e.candidate))),d.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield d.setRemoteDescription(u);let h=yield d.createAnswer(),p=EN.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=EN.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>$b(this,null,(function*(){t.encode&&t.decode&&(r(),e(t));let i=yield l.getSenders()[0].getStats(),n=yield d.getReceivers()[0].getStats();t.encode||i.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===WR.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===WR.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}))),100)}catch(i){r(),pN.warn(i),e(t)}})))).then((e=>((!e.encode||!e.decode)&&pN.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(PD)),e))),zN)}))}();o=e,a=t}return PN.result=t&&r&&n&&(o||s)&&(a||c),PN.detail.isBrowserSupported=t,PN.detail.isWebRTCSupported=r,PN.detail.isWebCodecsSupported=i,PN.detail.isMediaDevicesSupported=n,PN.detail.isScreenShareSupported=GN(),PN.detail.isSmallStreamSupported=QN(),PN.detail.isH264EncodeSupported=o,PN.detail.isVp8EncodeSupported=s,PN.detail.isH264DecodeSupported=a,PN.detail.isVp8DecodeSupported=c,PN.result||pN.error("".concat(navigator.userAgent," ").concat(rN(PN.detail,!1))),fN.setItem(TO,{ua:navigator.userAgent,checkResult:PN}),DN.addNumber({key:523800,value:Date.now()-e}),PN})))),WN=function(){return PN.result},GN=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},zN=null;var $N=(e,t,r)=>{"http:"===location.protocol&&!bD&&(e[t]=()=>{throw new sR({code:nR.INVALID_OPERATION,message:Zw.NOT_SUPPORTED_HTTP})})},JN=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(NP(e.selected)&&!e.selected)};function qN(){let e="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",r=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(r)}return e}function KN(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function YN(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r<t.length;r++)if(t[r]in window){e.isSupported=!0;break}return e.isSupported}function XN(){return"captureStream"in HTMLCanvasElement.prototype}function QN(){return!(Lk||uk||fD&&fD<63)&&!(!MN()||!XN())}var ZN=function(){if(kP(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Iw}),e.addTransceiver(WR.AUDIO),t=!0}catch(fR){}return null==e||e.close(),t};function eO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function tO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function rO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function iO(){return 11!==SD&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var nO=!(!iO()||hD&&fD<86);function oO(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var sO="RTCRtpSender"in window;function aO(){return sO&&"replaceTrack"in window.RTCRtpSender.prototype}function cO(){return sO&&"setParameters"in window.RTCRtpSender.prototype&&tO()}var lO="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,dO=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,uO=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,hO=sO&&"createEncodedStreams"in window.RTCRtpSender.prototype&&uD()>=86,pO="RTCRtpScriptTransform"in window,mO=sO&&(hO||pO),fO=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function _O(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return kP(window.AudioDecoder)||(e.AudioDecoder=!0),kP(window.AudioEncoder)||(e.AudioEncoder=!0),kP(window.VideoDecoder)||(e.VideoDecoder=!0),kP(window.VideoEncoder)||(e.VideoEncoder=!0),kP(window.ImageDecoder)||(e.ImageDecoder=!0),e}function gO(){return"mediaSession"in navigator&&!kP(navigator.mediaSession.setActionHandler)}function vO(){return!kP(window.WebTransport)}function yO(){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 EO(){let e={browser:"".concat(wD.name,"/").concat(wD.version),os:LD(),displayResolution:qN(),isScreenShareSupported:GN(),isWebRTCSupported:fO(),isGetUserMediaSupported:KN(),isWebAudioSupported:YN(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:_O(),isMediaSessionSupported:gO(),isWebTransportSupported:vO()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var TO="checkResult";function SO(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}!function(){UN();let e=fN.getItem(TO);e&&e.ua===navigator.userAgent&&(PN=e.checkResult),HN()}();var IO=Hb(Jb(),1),AO=Symbol("instance"),CO=Symbol("cacheResult"),bO=class{constructor(e,t,r){this.oldState=e,this.newState=t,this.action=r,this.aborted=!1}abort(e){this.aborted=!0,PO.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},RO=class extends Error{constructor(e,t,r){super(t),this.state=e,this.message=t,this.cause=r}};var wO=new Map;function kO(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(i,n,o)=>{let s=r.action||n;if(!r.context){let r=wO.get(i)||[];wO.has(i)||wO.set(i,r),r.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let i=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(r.context&&(i=NO.get("function"==typeof r.context?r.context.call(this,...o):r.context)),i.state===t)return r.sync?i[CO]:Promise.resolve(i[CO]);i.state instanceof bO&&i.state.action==r.abortAction&&i.state.abort(i);let l=null;Array.isArray(e)?0==e.length?i.state instanceof bO&&i.state.abort(i):("string"!=typeof i.state||!e.includes(i.state))&&(l=new RO(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e.join("|")))):e!==i.state&&(l=new RO(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e)));let d=e=>{if(r.fail&&r.fail.call(this,e),r.sync){if(r.ignoreError)return e;throw e}return r.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=i.state,h=new bO(u,t,s);PO.call(i,h);let p=e=>{var n;return i[CO]=e,h.aborted||(PO.call(i,t),null===(n=r.success)||void 0===n||n.call(this,i[CO])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return PO.call(i,u,e),d(new RO(i._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):r.sync?p(e):Promise.resolve(p(e))}catch(f){return m(f)}}}}var DO="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 PO(e,t){let r=this._state;this._state=e;let i=e.toString();e&&this.emit(i,r),this.emit(NO.STATECHANGED,e,r,t),this.updateDevTools({value:e,old:r,err:t instanceof Error?t.message:String(t)})}var NO=class extends IO.default{constructor(e,t,r){super(),this.name=e,this.groupName=t,this._state=NO.INIT,e||(e=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let i=r[AO];i?this.name=i.name+"-"+i.count++:r[AO]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=wO.get(e)||[],r=new Set,i=[],n=[],o=new Set,s=Object.getPrototypeOf(e);wO.has(s)&&(s.stateDiagram.forEach((e=>r.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:r,action:o}=e;"string"==typeof t?i.push({from:t,to:r,action:o}):t.length?t.forEach((e=>{i.push({from:e,to:r,action:o})})):n.push({to:r,action:o})})),i.forEach((e=>{let{from:t,to:i,action:n}=e;o.add(t),o.add(i),o.add(n+"ing"),r.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),r.add("".concat(n,"ing --\x3e ").concat(i," : ").concat(n," 🟢")),r.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:i}=e;r.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🟢")),o.forEach((e=>{e!==t&&r.add("".concat(e," --\x3e ").concat(i,"ing : ").concat(i))}))}));let a=[...r];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=NO.instances.get(e),t||NO.instances.set(e,t=new NO(e,void 0,Object.create(NO.prototype)))):(t=NO.instances2.get(e),t||NO.instances2.set(e,t=new NO(e.constructor.name,void 0,Object.create(NO.prototype)))),t}static getState(e){var t;return null===(t=NO.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};DO(NO.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){PO.call(this,e)}};NO.STATECHANGED="stateChanged",NO.UPDATEAFSM="updateAFSM",NO.INIT="[*]",NO.ON="on",NO.OFF="off",NO.instances=new Map,NO.instances2=new WeakMap;var OO=(null==window?void 0:window.requestIdleCallback)||function(e){let t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},MO=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},LO=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),xO=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$w,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0;r=Ub(e===zw?{delay:2e3,count:0,backgroundTask:!0}:e===Ww?{delay:1e4,count:0}:e===Gw?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},r),OP(t)&&(r=Ub(Ub({},r),t)),wP(e)&&(t=e,e=$w);let i=Ub({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},r);return this.taskMap.set(i.taskID,i),this[e](i),i.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")],{type:"application/javascript"})));t.onmessage=r=>{"tick"===r.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,r=HP(),i=()=>{if(t=HP()-r,t>=e.delay&&(r=HP()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=OO(i,{timeout:e.delay})};return e.ricID=OO(i,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,r=HP(),i=()=>document.hidden&&e.backgroundTask?(t=HP()-r,r=HP(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(i,e.delay-Math.floor(t%e.delay))):(t=HP()-r,t>=e.delay&&(r=HP()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(i));if(e.rafID=requestAnimationFrame(i),e.backgroundTask){let t=()=>{if(document.hidden){let t=HP()-r;t>=e.delay?i():e.timeoutID=setTimeout(i,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:r,rafID:i,ricID:n,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),r&&clearTimeout(r),i&&LO(i),n&&MO(n),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};xO.taskMap=new Map,xO.currentTaskID=1;var VO=xO;WR.SEI_MESSAGE;var UO={LOADED_DATA:WR.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},FO={};jb(FO,{create:()=>jO,remove:()=>HO});var BO=new WeakMap;function jO(e,t){BO.has(e)||BO.set(e,[]);let r=BO.get(e),i={add:(e,n)=>("addEventListener"in t?(r.push(t.removeEventListener.bind(t,e,n)),t.addEventListener(e,n)):(r.push(t.off.bind(t,e,n)),t.on(e,n)),i)};return i}function HO(e){let t=BO.get(e);t&&(t.forEach((e=>e())),BO.delete(e))}var WO=new WeakMap;function GO(e){let{settings:t={retries:5,timeout:2e3},onError:r,onRetrying:i,onRetryFailed:n}=e;return function(e,o,s){let a=qD({retryFunction:s.value,settings:t,onError(t){let{error:i,retry:n,reject:s,retryFuncArgs:a}=t;var c;r?r.call(this,i,(()=>{var t;null!=(t=WO.get(e))&&t.has(o)?n():s(i)}),s,a):null!=(c=WO.get(e))&&c.has(o)?n():s(i)},onRetrying(t,r){var n;GD(i)&&i.call(this,t,r),null!=(n=WO.get(e))&&n.has(o)&&(WO.get(e).get(o).stopRetry=r)},onRetryFailed:n});return s.value=function(){let t=WO.get(e);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return t?t.set(o,{args:i}):WO.set(e,new Map([[o,{args:i}]])),a.apply(this,i).finally((()=>{var t;return null==(t=WO.get(e))?void 0:t.delete(o)}))},s}}function zO(e){let{fnName:t,callback:r,validateArgs:i=!0}=e;return function(e,n,o){let s=o.value;return o.value=function(){for(var n,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(n=WO.get(e))&&n.has(t)){let{stopRetry:n,args:s}=WO.get(e).get(t),a=!0;if(i)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(r&&r.apply(this,c),n&&n(),null==(o=WO.get(e))||o.delete(t))}return s.apply(this,c)},o}}var $O=class extends NO{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,Gb(this,"id"),Gb(this,"element",null),Gb(this,"track"),Gb(this,"url"),Gb(this,"attr"),Gb(this,"muted"),Gb(this,"_log"),Gb(this,"_pausedRetryCount"),Gb(this,"_isElementPlayingFired",!1),Gb(this,"_interval"),Gb(this,"_delayDestroyTimeoutId",0),Gb(this,"_playSuccessResolve"),Gb(this,"_isReplayByRecreateMediaStreamCalled",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Lw,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)||this.track&&"live"===this.track.readyState&&!this.track.muted)}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 $b(this,null,(function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(fR){let t=HD({key:Qw.PLAY_FAILED,data:{media:this.kind,error:fR}});if(this.track&&!this.track.muted&&this._log.warn(fR),t.includes("NotAllowedError"))throw new sR({code:nR.PLAY_NOT_ALLOWED,message:t})}}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(WR.ENDED),this._interval>0&&VO.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():AD?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 jO(this.element,this.element).add(WR.PLAYING,e).add(WR.ENDED,e).add(WR.PAUSE,e).add(WR.ERROR,e).add(WR.LOADEDDATA,e)}}bindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);null==FO||FO.create(e,e).add(WR.ENDED,t).add(WR.MUTE,t).add(WR.UNMUTE,t),e.readyState===WR.ENDED&&this.handleTrackEvent({type:WR.ENDED}),e.muted&&this.handleTrackEvent({type:WR.MUTE})}}bindAutoPlayEvent(){KD.on(uN.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&HO(e)}unbindEvents(){this.element&&HO(this.element),this.unbindTrackEvents(),KD.off(uN.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case WR.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(WR.PLAYING),this._interval&&(VO.clearTask(this._interval),this._interval=-1);break;case WR.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(WR.ENDED);break;case WR.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(WR.PAUSE),uk&&(this._interval=VO.run($w,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case WR.ERROR:if(this.element&&this.element.error){this.handlePaused(WR.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)),XD.uploadEvent({log:"stat-".concat(this.kind,"-").concat(yw.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),iD||rD?this.emit(UO.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case WR.LOADEDDATA:this.kind===WR.VIDEO&&this.emit(UO.LOADED_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),XD.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),DN.addSuccessEvent({key:this.kind===WR.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),XD.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),DN.addFailedEvent({key:this.kind===WR.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(UO.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise(((t,r)=>{cN(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,i;this._log.warn("element onerror ".concat(null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code," fired after recreated mediaStream")),r(null==(i=this.element)?void 0:i.error)}),cN(5e3).then((()=>{var e,i;(!this.isPlaying||(null==(e=this.element)?void 0:e.error))&&r(null==(i=this.element)?void 0:i.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}handleTrackEvent(e){switch(e.type){case WR.ENDED:this.handleStopped(WR.ENDED);break;case WR.MUTE:this.handlePaused(WR.MUTE);break;case WR.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(WR.UNMUTE)}}handlePlaying(e){var t;null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(UO.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(UO.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(UO.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};Wb([GO({settings:{retries:2,timeout:0},onError(e,t,r,i){i[0]=(i[0]||1e3)+1e3,t()}})],$O.prototype,"doReplayByRecreateMediaStream",1),Wb([kO([],"PLAYING",{sync:!0})],$O.prototype,"handlePlaying",1),Wb([kO("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],$O.prototype,"handlePaused",1),Wb([kO([],"STOPPED",{sync:!0})],$O.prototype,"handleStopped",1);var JO,qO="trtc_autoplay",KO="".concat(qO,"_mask"),YO="".concat(qO,"_wrapper"),XO="".concat(qO,"_header"),QO="".concat(qO,"_content"),ZO="".concat(qO,"_action_wrapper"),eM="".concat(qO,"_question"),tM="".concat(qO,"_collapse"),rM="".concat(qO,"_action_confirm"),iM="".concat(qO,"_detail"),nM="#2473E8",oM="dialog",sM="".concat(oM,"-show"),aM="".concat(oM,"-1"),cM="".concat(oM,"-2"),lM=!1,dM=()=>!!document.querySelector(".".concat(YO)),uM="".concat(RR,"/").concat(IP()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),hM="<br><a href='".concat(uM,"' target='_blank'>").concat(IP()?"其他方案?":"Any other solution?","</a>"),pM="".concat(IP()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(hM):"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(hM)),mM=class{constructor(){if(Gb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Gb(this,"_dialogNode",null),Gb(this,"_bodyPosition",""),Gb(this,"_showDetail",!1),Gb(this,"_isCollapseClicked",!1),Gb(this,"_isQuestionClicked",!1),IP()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!lM){let e=document.createElement("style");e.innerHTML=".".concat(KO,"{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(KO," div:not(.").concat(ZO,"){display:block !important;}.").concat(YO,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(YO," a{color:").concat(nM,";}.").concat(XO,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(QO,"{margin:8px 0;}.").concat(ZO,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(tM,"{margin-right:auto;cursor:pointer}.").concat(eM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(rM,"{margin-left:8px;color:#fff;background:").concat(nM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(rM,":hover{opacity:0.9;}.").concat(tM,",.").concat(rM,",.").concat(QO,",.").concat(eM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(YO,"{width:80vw;}}"),document.head.appendChild(e),lM=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(KO,"\"><div class='").concat(YO,"'><div class='").concat(XO,"'>").concat(location.host,"</div><div class='").concat(QO,"'>").concat(this.content,"</div><div class='").concat(iM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(pM,"</div><div class='").concat(ZO,"'></div></div></div>").trim();let t=document.createElement("button");t.className=rM,t.innerText=IP()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=eM,r.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',r.onclick=this.onQuestionClick.bind(this);let i=document.createElement("div");i.className=tM,i.innerText="".concat(IP()?"详情 >":"Detail >"),i.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(ZO));return o.appendChild(i),o.appendChild(r),o.appendChild(t),n}addDiaLog(){dM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(YO)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",pN.info("show autoplay dialog"),XD.uploadEvent({log:sM}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){pN.warn("confirm clicked, try resume stream"),KD.emit(uN.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(iM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||XD.uploadEvent({log:aM}),this._isCollapseClicked=!0}onQuestionClick(){window.open(uM,"_blank"),this._isQuestionClicked||XD.uploadEvent({log:cM}),this._isQuestionClicked=!0}},fM=class extends $O{constructor(e){super(e,WR.VIDEO),Gb(this,"stat",{}),Gb(this,"_calculateTimeout",-1),Gb(this,"viewMirror",!1),Gb(this,"objectFit"),Gb(this,"container"),Gb(this,"canvas"),Gb(this,"source"),this.source=e.source,this.container=e.container,this.canvas=e.canvas,kP(e.viewMirror)||(this.viewMirror=e.viewMirror),kP(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(WR.VIDEO);this.source?t.src=URL.createObjectURL(this.source):this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(WR.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(WR.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){super.handleTrackEvent(e),e.type===WR.MUTE&&this.stat.fps&&(this.stat.fps=0)}handleElementEvent(e){var t;super.handleElementEvent(e);let r=e.type;if(r===WR.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this._pausedRetryCount>0&&!dM()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let e=this.element.style.transform;r===WR.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):r===WR.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,r,i,n;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e?(null==(r=this.element)||r.remove(),null==(i=this.container)||i.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}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;var t;super.stop(e),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.canvas?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(UO.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&!this.canvas&&(this.source?this.element.src=URL.createObjectURL(this.source):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(SO()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(i,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(i-e)*1e3)),e=i,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(r)}),2e3))};this.element.requestVideoFrameCallback(r)}}catch(fR){this._log.warn("init stat failed",fR)}}};function _M(e,t){return $b(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),pN.info("worklet addModule success")}catch(fR){throw pN.info("worklet addModule catch error. ".concat(fR.message)),fR}}))}"undefined"!=typeof AudioContext?JO=AudioContext:"undefined"!=typeof webkitAudioContext?JO=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(JO=mozAudioContext);var gM,vM=-1;!function e(){try{if(gM)return;(gM=new JO({sampleRate:48e3})).onstatechange=()=>{pN.info("context state: ".concat(gM.state)),yM()},clearTimeout(vM)}catch(gx){pN.error("initAudioContext failed: ".concat(gx," typeof AudioContextClass: ").concat(typeof JO)),vM=setTimeout(e,1e3)}}();var yM=()=>{"suspended"===gM.state?(gM.resume(),document.addEventListener("click",yM)):"interrupted"===gM.state?gM.resume().catch((e=>{pN.warn("resume failed: ".concat(e)),document.addEventListener("visibilitychange",yM)})):(document.removeEventListener("visibilitychange",yM),document.removeEventListener("click",yM))};document.addEventListener("click",yM);var EM=e=>gM,TM=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set,this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.node&&(this.node.channelCount=e),this.next.forEach((t=>t.channelCount=e))}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),DN.addSuccessEvent({key:502701})}catch(gw){pN.error(gw),DN.addFailedEvent({key:502701,error:gw})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),DN.addSuccessEvent({key:502702})}catch(fR){pN.error(fR),DN.addFailedEvent({key:502702,error:fR})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>e._connect(t.node)||t.connectNext(e)))}_connect(e){return!(!this.node||!e)&&(this.node.connect(e),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.forEach((e=>{this.next.add(e),e.pre.add(this)})),this}},SM=class extends TM{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;super(),this.fftSize=e,this.dataArray=new Uint8Array(0)}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,r=0,i="M".concat(t,",").concat(r);for(let n=0;n<e.length;n++)r=e[n]/128*100/2,i+="L".concat(t,",").concat(r),t+=1;return i}},IM=class{constructor(){this.source=new TM,this.gain=new TM,this.destination=new TM}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(RM(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},AM=class extends IM{constructor(e){super(),this.context=e,this.denoiser=new TM,this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){!this.context.inputs.has(this)||(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.source.deleteNode(),this.disconnect()}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()}},CM=class{constructor(){this.audioContext=EM(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0}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]}},bM=new WeakMap;function RM(e){let t=bM.get(e);if(t)return t;let r=EM();if(e instanceof HTMLAudioElement)t=r.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=r.createMediaStreamSource(new MediaStream([e]))}return bM.set(e,t),t}var wM=class{constructor(e){this._volume=0,this._scriptProcessorNode=null,this._audioWorkletNode=null,this._interval=200,this.ready=this.preload();let{log:t}=e;this._log=t,KD.on(uN.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-wM.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!wM.workletReady){let e='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,e){t=t[0],e=e[0];if(t||e){if(this.isStop)return!1;var s=e?e[0].length:0,i=this.cache.length,h=(s<i?(e[0].set(this.cache.slice(0,s)),this.cache=this.cache.slice(s)):this.unmute&&e[0].set(t[0]),(s<i?e:t)[0]);if(h){let e=0;for(let t=0;t<h.length;++t)e=Math.max(Math.abs(h[t]),e);this.volume=e,this.tick-=h.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,cacheLen:i,outputLen:s}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';wM.workletReady=_M(wM.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return wM.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(wM.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{wM.lastMessageTime=Date.now(),this._volume=t.data.volume||0,!e&&t.data.cacheLen&&t.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(yN){this._log.error("volumeMeter init audio worklet error: ".concat(yN)),XD.logFailedEvent({userId:this._log.userId,eventType:yw.LOAD_WORKLET,error:yN}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=EM("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{wM.lastMessageTime=Date.now();let t=e.inputBuffer.getChannelData(0),r=0;for(let i=0;i<t.length;++i)r+=t[i]*t[i];this._volume=Math.sqrt(r/t.length)||0}}catch(yN){this._log.error("volumeMeter init script processor error: ".concat(yN))}}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,KD.off(uN.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(e){var t;let{interval:r}=e;this._interval=r,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:r})}},kM=wM;kM.lastMessageTime=0,kM.audioContext=EM();var DM=class extends TM{constructor(e){super(),this._volumeMeter=new kM(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return $b(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},PM=kM,NM=Hb(Jb(),1),OM=e=>t=>t.deviceId===e,MM=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";Gb(this,"kind"),Gb(this,"type"),Gb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let r=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&VM(this.devices[0])||t&&(r.forEach((e=>{if(e.deviceId&&!this.devices.find(OM(e.deviceId))){let r="".concat(this.kind).concat(this.type,"Added");pN.warn("".concat(r,": ").concat(JSON.stringify(e))),t.emit(r,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!r.find(OM(e.deviceId))){let r="".concat(this.kind).concat(this.type,"Removed");pN.warn("".concat(r,": ").concat(JSON.stringify(e))),t.emit(r,e)}}))),this.devices=r}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},LM=class extends NM.EventEmitter{constructor(){super(),Gb(this,"audioInputs",new MM(WR.AUDIO)),Gb(this,"videoInputs",new MM(WR.VIDEO)),Gb(this,"audioOutputs",new MM(WR.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||VO.run(zw,(()=>{this.update()}),{delay:1e4}))}init(){UM().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let r=yield UM(t);return e.audioInputs.update(r,e),e.videoInputs.update(r,e),e.audioOutputs.update(r,e),e}()}))}},xM=yR||vR?null:new LM;function VM(e){return e.deviceId===e.groupId&&""===e.groupId}function UM(){return $b(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(UN()||!xN())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let r={audio:!1,video:!1};if(t.forEach((e=>{VM(e)&&(e.kind===WR.AUDIO_INPUT?r.audio=!0:e.kind===WR.VIDEO_INPUT&&(r.video=!0))})),2===e&&(r.audio=!1),1===e&&(r.video=!1),r.audio||r.video){let e;try{e=yield navigator.mediaDevices.getUserMedia(r)}catch(_R){pN.debug("capture before getDevices failed: ",_R)}t=yield navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&WM.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r}))}()}))}function FM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xM.update(e?1:0).then((e=>e.audioInputs.devices))}function BM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return xM.update(e?2:0).then((e=>e.videoInputs.devices))}var jM=!1;function HM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return $b(this,null,(function*(){return xM.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var WM=new Set;function GM(e,t){return $b(this,null,(function*(){let r=(yield FM()).find((e=>e.deviceId===xw));return!t&&(null==r?void 0:r.groupId)===e||(null==r?void 0:r.groupId)===e&&r.label===t}))}var zM,$M=class extends IM{constructor(e){super(),this.log=e,Gb(this,"volumeMeter"),Gb(this,"volumeDestination"),Gb(this,"analyser",new SM),this.volumeMeter=new DM({log:this.log}),this.volumeDestination=new TM,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},JM=class extends $O{constructor(e){super(e,WR.AUDIO),Gb(this,"_outputDeviceId"),Gb(this,"_volume",1),Gb(this,"_destination",EM().createMediaStreamDestination()),Gb(this,"pipeline"),Gb(this,"volumeMeterMode","worklet"),this.pipeline=new $M(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===TD||"15.3"===TD||"15.4"===TD)&&this.muted)return void this._log.info("audioElement is muted.");let t=zM||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,PP(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===zM&&(zM=void 0),this.bindElementEvents()}play(e){return $b(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==e?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(EM().createAnalyser()),function(){$b(this,null,(function*(){try{jM||(jM=!0,pN.info("speakers:".concat((yield HM()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(gx){}}))}(),zb(JM.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setSinkId(e){return $b(this,null,(function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield null==(r=(t=this.element).setSinkId)?void 0:r.call(t,e))}))}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},qM=class extends JM{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(UO.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.source.channelCount=(null==(t=e.getSettings())?void 0:t.channelCount)||1,this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},KM=class extends JM{constructor(e){super(e),Gb(this,"_sourceElement"),Gb(this,"_output",new TM),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this._output.setNode(EM().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,i;(null==(r=null==(t=this.element)?void 0:t.error)?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(UO.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(i=e.getSettings())?void 0:i.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),HO(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&vD&&(zM=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},YM=class extends NO{constructor(e){let{userId:t,sdkAppId:r,mediaType:i,room:n,PlayerClass:o=(1===i?KM:fM)}=e;var s;super(),Gb(this,"id",mN()),Gb(this,"userId",""),Gb(this,"isRemote"),Gb(this,"mediaType"),Gb(this,"room"),Gb(this,"user"),Gb(this,"_log"),Gb(this,"_inputTrack"),Gb(this,"_outputTrack"),Gb(this,"isPlayCalled"),Gb(this,"container",null),Gb(this,"player"),Gb(this,"subVideoPlayerMap"),Gb(this,"muted",!1),Gb(this,"abortCtrl"),Gb(this,"objectFit","cover"),Gb(this,"mirror"),Gb(this,"isScreen",!1),Gb(this,"manager"),Gb(this,"trackSettings"),this.userId=t||"",this.mediaType=i,this._log=pN.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof gL?void 0:this.userId,sdkAppId:r,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof gL}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(UO.PLAYER_STATE_CHANGED,(e=>{KD.emit(uN.PLAYER_STATE_CHANGED,Ub({track:this},e)),this.emit("player-state-changed",e)})),this.kind===WR.VIDEO&&(this.player.on(UO.LOADED_DATA,(()=>{KD.emit(uN.VIDEO_LOADED_DATA,{track:this})})),this.player.on(UO.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(UO.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||pN}get kind(){return 1===this.mediaType?WR.AUDIO:WR.VIDEO}get strMediaType(){return 4===this.mediaType?WR.VIDEO:2===this.mediaType?WR.SCREEN:WR.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 $b(this,null,(function*(){let r=MP(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!kP(t.muted)&&this.setPlayerMute(t.muted),t&&!kP(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof fM&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),MP(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!kP(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===WR.VIDEO)&&this.setPlayerMute(!0),t&&!kP(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof fM&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof fM&&this.player.setContainer(r)),KD.emit(uN.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),MP(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(i){throw this.handleAutoPlayFailed(),this.emit("error",i),i}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==WR.VIDEO||kP(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let i=this.manager;if(NP(this.mirror))return r.setViewMirror(this.mirror),void(i&&(i.mirror=!1));switch(this.mirror){case"view":i&&(i.mirror=!1),r.setViewMirror(!0);break;case"publish":i&&(i.mirror=!0),r.setViewMirror(!0);break;case"both":i&&(i.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return $b(this,null,(function*(){if(!this._outputTrack||this.kind===WR.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,r)=>{var i;e.find((e=>r===e))||(t.stop(),null==(i=this.subVideoPlayerMap)||i.delete(r))}));for(let[i,n]of e.entries()){let e=this.subVideoPlayerMap.get(n);e?t&&(kP(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new fM({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(i+1)})}))}let r=[...this.subVideoPlayerMap.values()];for(let e of r)e.setViewMirror(this.player.mirror),yield e.play()}))}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(xP(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return $b(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),KD.emit(e?uN.TRACK_MUTED:uN.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){jO(e,e).add(WR.MUTE,this.onTrackMuted).add(WR.UNMUTE,this.onTrackUnmuted).add(WR.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===WR.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){HO(e)}setInputMediaStreamTrack(e){var t;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(xP(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(){if(this.room&&this.room.enableAutoPlayDialog)new mM;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof fM?this.player.getVideoFrame():""}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"))}};Wb([kO([],NO.INIT,{sync:!0})],YM.prototype,"close",1);var XM=Object.prototype.hasOwnProperty;var QM=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(AP(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(XM.call(e,t))return!1;return!0}return!1},ZM=qD({retryFunction:function(e){return $b(this,null,(function*(){let t=function(e){return{audio:tL(e),video:rL(e)}}(e);pN.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let r=[],i=[],n=["label","deviceId"];t.audio&&(r=yield FM(),pN.info("microphones: ".concat(tN(r,{keysToInclude:n})))),t.video&&(i=yield BM(),pN.info("cameras: ".concat(tN(i,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return uO&&e.getTracks().forEach((e=>{pN.info("".concat(e.kind," capabilities: ").concat(tN(e.getCapabilities(),{keysToInclude:Jw})))})),e}catch(o){let{message:t}=o;throw"NotFoundError"===o.name&&(e.video&&i&&0===i.length&&(t=HD({key:Qw.CAMERA_NOT_FOUND})),e.audio&&r&&0===r.length&&(t=HD({key:Qw.MICROPHONE_NOT_FOUND}))),new sR({code:nR.INITIALIZE_FAILED,name:o.name,message:t,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:r,reject:i,retryFuncArgs:n,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?(n[0].video&&(n[0].maxResolution=!1,(!gD||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),r()):i(t),n[0].microphoneId&&eL(n[0].microphoneId,!1),n[0].cameraId&&eL(n[0].cameraId,!0)},onRetrying:e=>{pN.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{XD.logFailedEvent({eventType:yw.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{XD.logSuccessEvent({eventType:yw.GET_USER_MEDIA_RETRY}),XD.uploadEvent({log:"stat-".concat(yw.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function eL(e,t){return $b(this,null,(function*(){let r=(t?yield BM():yield FM()).find((t=>t.deviceId===e));r&&wP(r.getCapabilities)&&pN.warn(tN(r.getCapabilities(),{keysToInclude:Jw}))}))}function tL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!QM(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(PP(e.channelCount)&&(t.channelCount=e.channelCount),NP(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),NP(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),NP(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!QM(t)||t)}function rL(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,r={};return e.cameraId?r.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(r.facingMode=e.facingMode),e.useDeviceIdOnly&&!QM(r)?r:(e.width&&(r.width={ideal:e.width},t&&!_k&&(r.width.max=e.width)),e.height&&(r.height={ideal:e.height},t&&!_k&&(r.height.max=e.height)),_k&&Jk&&e.width&&e.height&&e.width*e.height<101376&&(r.width=e.width,r.height=e.height),e.frameRate&&(r.frameRate=e.frameRate),!!QM(r)||r)}var iL=ZM;function nL(e){return sL(((t,r)=>function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return $b(this,null,(function*(){return yield e.apply(this,i),t.apply(this,i)}))}))}function oL(e){return sL(((t,r)=>function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return $b(this,null,(function*(){let r=yield t.apply(this,i);return yield e.call(this,...i),r}))}))}function sL(e){return function(t,r,i){return i.value=e(i.value,r),i}}var aL=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&pN.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{pN.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),cL=0,lL=class{constructor(){this.log=pN.createLogger({id:"fq".concat(++cL)}),this.isRunning=!1,this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var r,i;let n=Ub({},e),o=new Promise(((e,t)=>{n.resolve=e,n.reject=t}));return n.promise=o,t?this.length<=1?this.queue.push(n):null==(i=null==(r=this.lastQueueItem)?void 0:r.promise)||i.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),o}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);let{fn:e,args:t,context:r,resolve:i,reject:n}=this.queue[0];this.isRunning=!0,e.apply(r,t).then(i,n).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},dL=new WeakMap,uL=new WeakMap;function hL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,r,i){let n=i.value;return i.value=function(){let t=dL.get(this)||new lL;for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];return dL.set(this,t),t.push({fn:n,args:i,context:this},e)},i}}function pL(e){return function(t,r,i){let n=i.value;return i.value=function(){var t,r,i;let o=[];for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return null==(r=null==(t=dL.get(this))?void 0:t.queue)||r.forEach((e=>o.push(e))),null==(i=uL.get(this))||i.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new sR({code:nR.API_CALL_ABORTED,message:e}))})),dL.delete(this),uL.delete(this),n.apply(this,a)},i}}function mL(e){return function(t,r,i){let n=i.value,o=t=>e(...t);return i.value=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];let i=uL.get(this)||new Map,s=i.get(o(t))||new lL;return i.set(o(t),s),uL.set(this,i),s.push({fn:n,args:t,context:this})},i}}function fL(e,t){return sL(((r,i)=>function(){let i=e;try{for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let e=r.apply(this,o),a=HP();return VP(e)?e.then((e=>(t?DN.addSuccessEvent({key:i,cost:HP()-a}):DN.addSuccessEvent({key:i}),e))).catch((e=>{throw DN.addFailedEvent({key:i,error:e}),e})):(DN.addSuccessEvent({key:i}),e)}catch(gR){throw DN.addFailedEvent({key:i,error:gR}),gR}}))}var _L=class extends YM{constructor(e,t){super({mediaType:e,PlayerClass:t}),Gb(this,"isRemote",!1),Gb(this,"deviceId"),Gb(this,"groupId",""),Gb(this,"label",""),Gb(this,"_isRecapturing",!1),Gb(this,"_lastRecaptureTime",0),Gb(this,"_onMuteTimeoutId",-1),Gb(this,"_encodeCheckTimeoutId",-1),Gb(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){jO(e,e).add(WR.MUTE,this.onTrackMuted).add(WR.UNMUTE,this.onTrackUnmuted).add(WR.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===WR.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){HO(e)}setStateToCapture(){}capture(e){return $b(this,null,(function*(){var t;try{let r,i=HP();KD.emit(uN.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),r=yield iL(e));let n=r.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),KD.emit(uN.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:HP()-i}),r}catch(_R){throw KD.emit(uN.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:_R}),this.log.error("getUserMedia error observed ".concat(_R)),_R}}))}setInputMediaStreamTrack(e){return this.state===NO.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),KD.emit(uN.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return $b(this,null,(function*(){if(this.mediaTrack&&dO){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield function(e){return $b(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:r,oldGroupId:i,oldLabel:n,kind:o}=e;return function*(){return t===r&&(o!==WR.AUDIO||t!==xw||(yield GM(i,n)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),UM().then((t=>{let r=t.find((t=>t.deviceId===e));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.mediaTrack||this.kind===WR.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let r="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(WR.AUDIO_INPUT);return!!WM.has(r)}(this.mediaTrack)||this.kind===WR.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(WR.VIDEO_INPUT);return!!WM.has(r)}(this.mediaTrack)||this._isRecapturing||e&&Jk&&gD)}onTrackMuted(){if(super.onTrackMuted(),aL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Hw)return void setTimeout((()=>this.onTrackMuted()),Hw);this._onMuteTimeoutId=setTimeout((()=>$b(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((uk||hk)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return $b(this,null,(function*(){if(zb(_L.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Hw)return void setTimeout((()=>this.onTrackEnded()),Hw);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return $b(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if("user"===e||"environment"===e)r.facingMode=e;else{let t;("audio"===this.kind?yield FM():yield BM()).find((t=>t.deviceId===e))&&(t=e),r.deviceId=t}return this.capture(r).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),KD.emit(uN.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e),KD.emit(uN.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}))}getRecoverCaptureDeviceId(){return $b(this,null,(function*(){let e=this instanceof SL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(vL.get(t)||0)+1;if(vL.set(t,r),r>=3){let i=e?(yield BM()).find((e=>!vL.has(e.deviceId))):(yield FM()).find((e=>!vL.has(e.deviceId)));i&&(this.log.warn("".concat(t," capture fail ").concat(r," times, change new ").concat(i.deviceId)),t=i.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}},gL=_L;Wb([kO(NO.INIT,"capture",{ignoreError:!0,sync:!0})],gL.prototype,"setStateToCapture",1),Wb([hL()],gL.prototype,"capture",1),Wb([kO("capture","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),KD.emit(uN.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let e=this.kind===WR.AUDIO,t=this.stat.bytesSent>0;DN[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(DN.addEnum({key:e?503701:513703,value:xD()}),XD.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(OD()||VD()),userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error",r=e.cause;r.message.includes("timeout")?t="timeout":r.code===nR.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r})}}),fL(521714,!1)],gL.prototype,"publish",1),Wb([sL((e=>function(){return $b(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)}))})),kO([],"capture",{sync:!0})],gL.prototype,"unpublish",1);var vL=new Map;KD.on(uN.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&vL.delete(e.track.deviceId)}));var yL=class extends gL{constructor(e){super(1,qM),Gb(this,"mediaType",1),Gb(this,"volume",0),Gb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Gb(this,"playerMuted",!0),Gb(this,"pipeline"),Gb(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),this.manager=e,this.pipeline=new AM(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return $b(this,null,(function*(){let t=this.trackSettings||{};DN.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),DN.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),DN.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:i}=t;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:i}))),this.pipeline.source.channelCount=i||1,this.pipeline.replaceSource(e),yield zb(yL.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:r,useExactDeviceId:i=!0,retryWhenExactFailed:n=!0}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:i,retryWhenExactFailed:n,customSource:r})}switchDevice(e){return $b(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==xw)return;if(yield GM(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),KD.emit(uN.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(gw){throw this.log.error("switch microphone failed ".concat(gw)),this.deviceId&&this.recapture(this.deviceId),gw}}}))}listenDeviceChange(){xM&&!xM.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&xM.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return $b(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),Vx(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield FM();t[0]?this.recapture(t[0].deviceId):xM.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return $b(this,arguments,(function(e){var t=this;let{echoCancellation:r,noiseSuppression:i,autoGainControl:n}=e;return function*(){let e=!1;!kP(r)&&r!==t.profile.echoCancellation&&(t.profile.echoCancellation=r,e=!0),!kP(i)&&i!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=i,e=!0),!kP(n)&&n!==t.profile.autoGainControl&&(t.profile.autoGainControl=n,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&DN.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch((t=>this._log.warn("".concat(e?"enable":"disable"," ANS failed "),t)))}addDenoiser(e){var t;fD<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(DN.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1))}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),xM.off("audioInputAdded",this.handleMicrophoneAdded,this),xM.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return $b(this,null,(function*(){try{yield zb(yL.prototype,this,"recapture").call(this,e)}catch(gw){let r=(yield FM()).find((t=>t.deviceId!==e));if(!r)throw gw;yield zb(yL.prototype,this,"recapture").call(this,r.deviceId)}}))}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e}):e),e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}},EL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,r=[],i=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===i&&(r.push(3),i=0),0==e?i++:i=0,r.push(e);break;default:i=0,r.push(e)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...r]).buffer);this.dataView=n}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,r=[],i=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:i++,r.push(this.dataView.getInt8(o));break;case 3:2!==i&&r.push(this.dataView.getInt8(o)),i=0;break;default:r.push(this.dataView.getInt8(o)),i=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...r]).buffer);this.dataView=n}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let n=6;n<this.dataView.buffer.byteLength;n++){let r=this.dataView.getUint8(n);if(t++,255!==r){e+=r;break}e+=255}let r=new ArrayBuffer(e),i=new DataView(r);for(let n=0;n<r.byteLength;n++,t++)i.setInt8(n,this.dataView.getInt8(t));return i}},TL=class{constructor(){Gb(this,"_seiMessageList",[]),Gb(this,"_smallSeiMessageList",[]),Gb(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,r=parseInt(String(t/255),10),i=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<r;s++)n.push(255);n.push(i);let o=new DataView(e);return n.push(...new Uint8Array(o.buffer)),n.push(128),new EL(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}getNaluCount(e){let t=0,r=0,i=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(i.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&r++,t=0;break;default:t=0}return r}encode(e,t){let r=t?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&e.data.byteLength>0){let t=9-this.getNaluCount(e.data);if(t<=0)return 0;let i=r.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),n=i.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(n+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<i.length;e++)for(let t=0;t<i[e].dataView.byteLength;t++)s.setInt8(c++,i[e].dataView.getInt8(t));for(let r=0;r<e.data.byteLength;r++)s.setInt8(c++,a.getInt8(r));return e.data=o,i.length}return 0}},SL=class extends gL{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,fM),Gb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),Gb(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),Gb(this,"small"),Gb(this,"isNeedToSetBandwidth"),Gb(this,"muteImage"),Gb(this,"manager"),Gb(this,"_seiCodec",new TL),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(Fb(Ub({},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(dO&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}setMute(e){return $b(this,null,(function*(){var t,r,i;if(DP(e)){if(this.muteImage===e)return;yield null==(t=this.manager)?void 0:t.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:e}),this.muteImage=e,zb(SL.prototype,this,"setMute").call(this,!1)}else yield null==(i=this.manager)?void 0:i.deleteWatermark("mute"),this.muteImage=void 0,zb(SL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:r,useExactDeviceId:i=!0,customSource:n,retryWhenExactFailed:o=!0}=e;return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:i,retryWhenExactFailed:o,customSource:n})}setProfile(e){let t=Ub({},e),r=t.width>t.height;t.width*t.height<=19200&&hk&&hD&&(this.log.warn("resolution is ".concat(t.width,"*").concat(t.height,", fallback to 240*180")),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&CD&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Fb(Ub({},this.profile),{width:1920,height:1080})))}applyProfile(){return $b(this,null,(function*(){var e;if(!this.mediaTrack)return;let t=this.settings;return(t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate)&&this.deviceId&&(16===SD?yield this.recapture(this.deviceId):(yield null==(e=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,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:WR.VIDEO,videoType:WR.BIG})):void 0}))}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return dO&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:nN()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return $b(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),KD.emit(uN.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(gw){throw this.log.error("switch camera failed ".concat(gw)),this.deviceId&&this.recapture(this.deviceId),gw}}))}listenDeviceChange(){xM&&!xM.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&xM.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return $b(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),Vx(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield BM();t[0]?this.recapture(t[0].deviceId):xM.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return $b(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduce(((e,t)=>t?t({frame:e,mediaType:r}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return $b(this,null,(function*(){return kP(this.mirror)&&!this.isScreen&&this.setMirror("view"),zb(SL.prototype,this,"play").call(this,e,t)}))}close(){xM.off("videoInputAdded",this.handleCameraAdded,this),xM.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return $b(this,null,(function*(){try{yield zb(SL.prototype,this,"recapture").call(this,e)}catch(gw){let r=(yield BM()).find((t=>t.deviceId!==e));if(!r)throw gw;yield zb(SL.prototype,this,"recapture").call(this,r.deviceId)}}))}},IL=mN();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:IL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(gx){}var AL,CL=function(e){return $b(this,null,(function*(){let t=null,r=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},r={width:gD?{max:e.width}:{ideal:e.width,max:e.width},height:gD?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=r,e.systemAudio){let{echoCancellation:r=!0,noiseSuppression:i=!1,autoGainControl:n=!1}=e;t.audio={echoCancellation:r,noiseSuppression:i,autoGainControl:n,sampleRate:48e3}}return t}(e);pN.info("getDisplayMedia with constraints: ".concat(JSON.stringify(r)));let i=yield navigator.mediaDevices.getDisplayMedia(r);e.systemAudio&&0===i.getAudioTracks().length&&(pD&&fD<74||gD||_k)&&pN.warn("Your browser not support capture system audio");let n=i.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(o){pN.warn("screen applyConstraints failed: ".concat(o))}e.captureElement&&(yield function(e,t){return $b(this,null,(function*(){var r;if("CropTarget"in window&&"fromElement"in CropTarget&&wP(e.cropTo))try{if((null==(r=e.getCaptureHandle())?void 0:r.handle)!==IL)return;let i=yield CropTarget.fromElement(t);yield e.cropTo(i)}catch(i){pN.warn("cropTo target failed ".concat(i))}}))}(n,e.captureElement))}if(e.audio){let r=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return kP(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);pN.info("getUserMedia with constraints: ".concat(JSON.stringify(r))),t=yield navigator.mediaDevices.getUserMedia(r),i.addTrack(t.getAudioTracks()[0])}return i}))},bL=class extends SL{constructor(e){super(e,2),Gb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Gb(this,"objectFit","contain"),Gb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return $b(this,arguments,(function(e){var t=this;let{systemAudio:r=!1,autoGainControl:i,echoCancellation:n,noiseSuppression:o,audioTrack:s,videoTrack:a,captureElement:c,preferDisplaySurface:l}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield CL({audio:!1,systemAudio:r,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:i,echoCancellation:n,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof sR?e:new sR({code:nR.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return $b(this,null,(function*(){throw new Error("Method not implemented.")}))}},RL=class extends yL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},wL="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});";function kL(e){return $b(this,null,(function*(){let t=EM();AL||(AL=_M(t,URL.createObjectURL(new Blob([wL],{type:"application/javascript"})))),yield AL;let r=new AudioWorkletNode(t,"dumper",{numberOfInputs:e.length,numberOfOutputs:0});return e.forEach(((e,t)=>e.connect(r,0,t))),new ReadableStream({start(e){r.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){e.forEach((e=>e.disconnect(r))),r.port.close()}})}))}var DL=class extends CM{constructor(e){super(),this.room=e,Gb(this,"_localAudioTrack"),Gb(this,"_localScreenAudioTrack"),Gb(this,"log",pN.createLogger({id:"am"})),Gb(this,"denoiser"),Gb(this,"mixChangedDebounce"),Gb(this,"encodePipeline",[]),Gb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,r;if(!this._localAudioTrack)return;let i=[],n=[];null!=(t=this._localAudioPipline)&&t.source.node&&(i.push(this._localAudioPipline.source.node),n.push("mic")),null!=(r=this._localAudioPipline)&&r.denoiser.node&&(i.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(i.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let o=new AbortController,s=[],a=setTimeout((()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),c=()=>{for(let e=0;e<n.length;e++){let t=URL.createObjectURL(new Blob(s[e])),r=document.createElement("a");r.href=t,r.download="".concat(n[e],".pcm"),r.style.display="none",document.body.appendChild(r),r.click(),URL.revokeObjectURL(t),r.remove()}clearTimeout(a),o.abort("download")},l=kL(i).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>s[t]=s[t]?s[t].concat(e[0]):[e[0]]))}}),o).catch((e=>c))));return{then:l.then.bind(l),download:c}}getPCM(e){var t;if(kP(WritableStream))return void this.log.warn("getPCM failed: browser not support WritableStream");if(null==(t=this._localAudioPipline)||!t.source.node)return void this.log.warn("getPCM failed: no local audio track");this.log.warn("getPCM");let r=new Float32Array(1920),i=0,n=new AbortController;return kL([this._localAudioPipline.source.node]).then((t=>t.pipeTo(new WritableStream({write(t){!t[0][0]||(r.set(t[0][0],i),i+=t[0][0].length,i>=1920&&(i=0,e(r),r=new Float32Array(1920)))}}),n).catch((e=>this.log.warn("stop getPCM reason:".concat(e)))))),n}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){return e instanceof RL?(this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange()):e instanceof yL?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange()):e instanceof ML?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}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 RL?delete this._localScreenAudioTrack:e instanceof yL&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}destroy(){this.close()}addEncodeProcessor(e){let{processor:t,type:r}=e;var i;this.encodePipeline.includes(t)||(this.encodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:r}=e;var i;this.decodePipeline.includes(t)||(this.decodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};function PL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return sL(((r,i)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];return new Promise(((n,s)=>{let a=setTimeout((()=>{let r=new sR({code:nR.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(i,"() timeout ").concat(e,"s")});pN.warn(r),2===t?s(r):1===t&&n()}),1e3*e);r.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var NL=class extends YM{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e}),this.room=e,this.user=t,Gb(this,"tinyId"),Gb(this,"isRemote",!0),Gb(this,"jitterBufferDelay",0),Gb(this,"_decodeCheckTimeoutId",-1),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===NL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===WR.AUDIO;DN[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(DN.addEnum({key:r?504701:514703,value:xD()}),XD.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(OD()||VD()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===WR.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," hasFlag: ").concat(this.hasFlag," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},OL=NL;Gb(OL,"STATE_SUBSCRIBE","subscribe"),Wb([PL(5,1)],OL.prototype,"waitHasMediaTrack",1),Wb([kO(NO.INIT,OL.STATE_SUBSCRIBE,{success(){var e,t;this.log.info("subscribed"),KD.emit(uN.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&(this._decodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let e=this.kind===WR.AUDIO,t=this.player.isPlaying||(e?this.getAudioLevel()>0:this.stat.framesDecoded>0);DN[t?"addSuccessEvent":"addFailedEvent"]({key:e?504700:514702}),t||(DN.addEnum({key:e?504701:514703,value:xD()}),XD.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(OD()||VD()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===WR.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed"))}}),5e3),this.player.once(UO.ERROR,(e=>{e.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))})))},ignoreError:!0}),fL(521716,!1)],OL.prototype,"subscribe",1),Wb([kO(OL.STATE_SUBSCRIBE,NO.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),KD.emit(uN.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],OL.prototype,"unsubscribe",1);var ML=class extends OL{constructor(e,t){super(e,t,1),Gb(this,"volume",0),Gb(this,"mediaType",1),Gb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},LL=[-1,-1,1,-1,-1,1,1,1],xL=[0,0,1,0,0,1,1,1],VL=class extends NO{constructor(e,t){if(super(),this.context=e,Gb(this,"name"),Gb(this,"input"),Gb(this,"output"),Gb(this,"texture"),Gb(this,"ctx2d",null),Gb(this,"fbo"),Gb(this,"width",0),Gb(this,"height",0),Gb(this,"x",0),Gb(this,"y",0),Gb(this,"program"),Gb(this,"vertexShader"),Gb(this,"fragmentShader"),Gb(this,"totalFrames",0),Gb(this,"dropFrames",0),Gb(this,"matchInputSize",!0),Gb(this,"texCoordBuffer"),Gb(this,"positionBuffer"),Gb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Gb(this,"cost",0),Gb(this,"_canvas",null),Gb(this,"_image"),Gb(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 Ox)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==SD?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(xL),this.positionBuffer=this.createBuffer(LL),!1!==t.createTexture&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(_R){this.context.destroy(new sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(_R.message||_R)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return e.addInput(this,...r),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof Nx&&this.render(e)||this.context instanceof Ox&&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(e){var t;null==(t=this.output)||t.update(e)}disconnect(){for(var e,t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];null==(e=this.output)||e.removeInput(this,...r),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof Nx){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];r.forEach(((t,r)=>{t&&(e.activeTexture(e.TEXTURE0+r),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];r.forEach(((t,r)=>{e.enableVertexAttribArray(r),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,i,n){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):this.ctx2d.drawImage(e,t,r,i,n),!0)}getInfo(){var e;let{totalFrames:t,x:r,y:i,width:n,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:r,y:i,width:n,height:o,timestamp:c,fps:l,name:s,cost:a},Ub({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};function UL(){}Wb([kO(NO.INIT,"connected",{sync:!0})],VL.prototype,"connect",1),Wb([kO("connected",NO.INIT,{ignoreError:!0,sync:!0})],VL.prototype,"disconnect",1),Wb([kO([],"closed",{sync:!0})],VL.prototype,"close",1);var FL=e=>e();function BL(){this.dispose()}var jL=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,HL=1,WL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new XL(e,this,this.streamId++);return QL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},GL=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=UL,this.error=UL,this.next=UL,this.dispose=UL,this.subscribe=UL,this.doDefer()}subscribe(e){return e instanceof WL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(FL),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}},zL=class extends GL{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)}},$L=class extends GL{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:UL,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:UL,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:UL;if(super(),this._next=t,this._error=r,this._complete=i,this.then=UL,e instanceof WL){let n={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{QL.defer(n,0)})),QL.create(n),QL.pipe(n),this.sourceId=n.id,this.subscribe(e),QL.subscribe({id:n.id,end:!0}),t==UL?this._next=e=>QL.next(n,0,e):this.next=e=>{QL.next(n,0,e),t(e)},i==UL?this._complete=()=>QL.complete(n,0):this.complete=()=>{this.dispose(),QL.complete(n,0),i()},r==UL?this._error=e=>QL.complete(n,0,e):this.error=e=>{this.dispose(),QL.complete(n,0,e),r()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function JL(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return r.reduce(((e,t)=>t(e)),e)}function qL(e,t,r){if(jL()){let i=Object.defineProperties(Object.setPrototypeOf(e,WL.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:r,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});QL.create(i);for(let e=0;e<r.length;e++){let t=r[e];"function"==typeof t&&t instanceof WL&&QL.addSource(i,t)}return i}return e}function KL(e,t){return function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return r=>{if(r instanceof WL){let n=qL((t=>{let o=new e(t,...i);o.sourceId=n.id,o.subscribe(r)}),t,arguments);return n.source=r,QL.pipe(n),n}return t=>r(new e(t,...i))}}}function YL(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var XL=class extends zL{constructor(e,t,r){super(e),this.source=t,this.id=r,this.sourceId=e.sourceId,this.defer((()=>{QL.defer(this.source,this.id)}))}next(e){QL.next(this.source,this.id,e),this.sink.next(e)}complete(){QL.complete(this.source,this.id),this.sink.complete()}error(e){QL.complete(this.source,this.id,e),this.sink.error(e)}},QL={addSource(e,t){YL("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,r){YL("next",{id:e.id,streamId:t,data:r&&r.toString()})},subscribe(e,t){let{id:r,end:i}=e;YL("subscribe",{id:r,end:i,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,r){YL("complete",{id:e.id,streamId:t,err:r?r.toString():null})},defer(e,t){YL("defer",{id:e.id,streamId:t})},pipe(e){YL("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){YL("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=HL++),YL("create",{name:e.toString(),id:e.id})}},ZL=class extends GL{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 ex(){return e=>{let t=new ZL(e);if(e instanceof WL){let r=qL((e=>{t.add(e)}),"share",arguments);return t.sourceId=r.id,r.source=e,QL.pipe(r),r}return qL(t.add.bind(t),"share",arguments)}}function tx(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return e=>qL((function(r){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.length;for(;i<n&&!r.disposed;)r.next(t[i++]);r.disposed||r.subscribe(e)}),"startWith",arguments)}function rx(e){let t=arguments,r=ex()(qL((t=>{r.next=e=>t.next(e),r.complete=()=>t.complete(),r.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return r.next=UL,r.complete=UL,r.error=UL,r}function ix(e,t){return r=>{let i=e=>r.next(e);r.defer((()=>t(i))),e(i)}}function nx(e,t){if("on"in e&&"off"in e)return qL(ix((r=>e.on(t,r)),(r=>e.off(t,r))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return qL(ix((r=>e.addListener(t,r)),(r=>e.removeListener(t,r))),"fromEvent",arguments);if("addEventListener"in e)return qL(ix((r=>e.addEventListener(t,r)),(r=>e.removeEventListener(t,r))),"fromEvent",arguments);throw"target is not a EventDispachter"}function ox(){return qL((e=>e.complete()),"empty",arguments)}var sx=KL(class extends zL{constructor(e,t,r){super(e),this.filter=t,this.thisArg=r}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),ax=KL(class extends zL{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},"take"),cx=KL(class extends zL{constructor(e,t){super(e);let r=new zL(e);r.next=()=>e.complete(),r.complete=BL,r.subscribe(t)}},"takeUntil"),lx=KL(class extends zL{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),dx=KL(class extends zL{constructor(e,t,r){super(e),this.f=t,void 0===r?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),ux=KL(class extends zL{constructor(e,t,r){super(e),this.mapper=t,this.thisArg=r}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map"),hx=class extends zL{constructor(e,t,r){super(e),this.data=t,this.context=r}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},px=class extends zL{constructor(e,t,r){super(e),this.makeSource=t,this.combineResults=r,this.index=0}subInner(e,t){let r=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},mx=class extends hx{},fx=class extends px{next(e){this.subInner(e,mx),this.next=e=>{this.currentSink.dispose(),this.subInner(e,mx)}}},_x=KL(fx,"switchMap");var gx,vx=(gx=KL(fx,"switchMapTo"),(e,t)=>gx((()=>e),t)),yx=KL(class extends zL{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),Ex=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:UL,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:UL,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:UL;return i=>new $L(i,e,t,r)},Tx=JL(function(e){return qL((t=>{let r=0,i=setInterval((()=>t.next(r++)),e);return t.defer((()=>{clearInterval(i)})),"interval"}),"interval",arguments)}(250),ux((()=>performance.now())),ex()),Sx=[0,1,1,1,0,0,1,0],Ix=class extends VL{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),this._intervalId=0,this._sequence=0,this.checkGLError=!1,e instanceof Ox?this.ctx2d=e.ctx||null:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Sx)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),VO.clearTask(this._intervalId),this._intervalId=VO.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(VO.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Nx){let e=this.context.ctx.getError();e&&this.context.destroy(new sR({code:nR.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(),!0)}addInput(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];super.addInput(e,...r),this.start(this.context.frameRate)}update(e){if(this._intervalId&&(VO.clearTask(this._intervalId),this._intervalId=0,1===e)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),VO.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),VO.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Ax=class extends Ix{constructor(e,t){super(e,t),this._closedOb=nx(this,"closed"),Number(yD)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=nx(this._videoTrack,"mute"),JL(nx(this._videoTrack,"ended"),cx(this._closedOb),Ex((()=>{this.context.destroy(new sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=JL(this._muteOb,cx(this._closedOb),vx((e=>t=>{let r=performance.now();JL(Tx,lx((t=>t-r<e)),ax(1))(t)})(5e3)),Ex((()=>{var e;null==(e=this._videoTrack)||!e.muted||this.context.destroy(new sR({code:nR.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()}},Cx=class extends Ax{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},bx=class extends Ax{constructor(e,t,r){super(e,{name:"smallDestination",logger:r}),this.resolution=t}resize(e,t){let r,i=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),i>n?r=i/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),r=i/19200),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}},Rx=class extends VL{constructor(e,t){super(e,Ub({name:"imageSource"},t)),Gb(this,"_lastImage"),Gb(this,"_totalFrames",0),Gb(this,"_autoResize",!1),Gb(this,"_canvasRendered"),Gb(this,"_videoCallbackId",0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===SD&&(this._canvasRendered=rx(),JL(this._canvasRendered,tx(this._image),_x((e=>e instanceof HTMLCanvasElement?nx(e,"rendered"):ox())),cx(nx(this,"closed")),Ex((()=>{this.update(0)}))))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),SO()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var r;let{width:i,height:n}=this,{image:o}=this;if(o instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(o),({videoWidth:i,videoHeight:n}=o),!i||!n)return!1;o.width=i,o.height=n}else if(o instanceof HTMLImageElement||o instanceof ImageData||o instanceof ImageBitmap){if(({width:i,height:n}=o),o!==this._lastImage)this._lastImage=o;else if(i===this.width&&n===this.height)return!1}else o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?(({width:i,height:n}=o),this._lastImage=o):"undefined"!=typeof VideoFrame&&o instanceof VideoFrame&&(({displayWidth:i,displayHeight:n}=o),null==(r=this._lastImage)||r.close(),this._lastImage=o);if(!this._autoResize)return!0;if(this.width===i&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,o)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)}this.resize(i,n)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},wx=class extends Rx{constructor(e,t,r){super(e,r),this._player=t,this.name="videoPlayerSource",JL(nx(this._player,UO.PLAYER_STATE_CHANGED),cx(nx(this,"closed")),sx((e=>{let{state:t}=e;return"PLAYING"===t})),Ex((()=>{this.tryVideoFrameCallback(this._player.element)})))}get image(){return this._player.element}},kx=class extends wx{constructor(e,t,r){super(e,new fM({id:r.name,track:t,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},Dx=class extends NO{constructor(e){super(),this.hasAlpha=!1,this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new kx(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Ax(this,e)}createVideoImageSource(e,t){return new Rx(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new wx(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};Dx._ids=0;var Px={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Nx=class extends Dx{create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Dx._ids++)),this.ctx=this._canvas.getContext("webgl2",Px),!this.ctx)throw new sR({code:nR.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 sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,DN.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}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;null==(r=this.ctx)||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,i=r.createShader(e);return r.shaderSource(i,t),r.compileShader(i),i}createProgram(e,t){let r=this.ctx,i=r.createProgram();return r.attachShader(i,e),r.attachShader(i,t),r.linkProgram(i),r.getProgramParameter(i,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(i)),i}};Nx.UNAVAILABLE="unavailable",Wb([kO(NO.INIT,"created",{sync:!0,fail(e){DN.addFailedEvent({key:512700,error:e.cause})},success(){DN.addSuccessEvent({key:512700})}})],Nx.prototype,"create",1),Wb([kO("created",NO.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Nx.UNAVAILABLE,e),this.removeAllListeners()}})],Nx.prototype,"destroy",1);var Ox=class extends Dx{create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Dx._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,DN.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(),DN.addSuccessEvent({key:512703})}};Wb([kO(NO.INIT,"created",{sync:!0,fail(e){DN.addFailedEvent({key:512701,error:e.cause})},success(){DN.addSuccessEvent({key:512701})}})],Ox.prototype,"create",1),Wb([kO("created",NO.INIT,{ignoreError:!0,sync:!0})],Ox.prototype,"destroy",1);var Mx=class extends OL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),Gb(this,"mediaType",4),Gb(this,"source"),Gb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}play(e,t){return $b(this,null,(function*(){return(NP(null==t?void 0:t.canvasRender)?t.canvasRender:17===SD)&&!this.source&&this.useCanvasPlayer(),zb(Mx.prototype,this,"play").call(this,e,t).then((()=>{this.player.calculateStat()}))}))}useCanvasPlayer(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new Ox({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Ix(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),SO()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=function(e){return[15,30,45,60].reduce(((t,r)=>Math.abs(r-e)<Math.abs(t-e)?r:t))}(t);!PP(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):r!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(r,", current: ").concat(e.frameRate)),e.frameRate=r):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(r," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=(null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((e=>e.msg_user_info.str_identifier===this.userId)))||{},r=2===this.mediaType?7:this.isSmall?3:2;if(!t||0===t.length)return 0;let i=t.find((e=>e.uint32_video_stream_type===r));return(null==i?void 0:i.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},Lx=class extends Mx{constructor(e,t){super(e,t,2),Gb(this,"mediaType",2),Gb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}},xx=new Map;function Vx(e,t){let r=Fb(Ub({},t),{timestamp:cR()});xx.has(e)?xx.get(e).push(r):xx.set(e,[r])}KD.on(uN.JOIN_SUCCESS,(e=>{let{room:t}=e;Vx(t.userId,{eventId:32788})})),KD.on(uN.LEAVE_START,(e=>{let{room:t}=e;Vx(t.userId,{eventId:32789})})),KD.on(uN.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),Vx(t.room.userId,{eventId:e})}})),KD.on(uN.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),Vx(t.room.userId,{eventId:e})}})),KD.on(uN.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===WR.AUDIO?Vx(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):Vx(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),KD.on(uN.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===WR.AUDIO?Vx(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):Vx(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),KD.on(uN.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&Vx(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&Vx(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&Vx(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),KD.on(uN.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&Vx(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&Vx(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&Vx(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),KD.on(uN.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&Vx(t.room.userId,{eventId:t.kind===WR.VIDEO?32780:32781})})),KD.on(uN.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&Vx(t.room.userId,{eventId:t.kind===WR.VIDEO?32782:32783})})),KD.on(uN.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,{room:r,prevState:i,state:n}=e;switch(n){case"CONNECTED":t="RECONNECTING"===i?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===i?32796:32790;break;case"RECONNECTING":t=32794}t&&Vx(r.userId,{eventId:t})})),KD.on(uN.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,{room:r,prevState:i,state:n,remoteUserId:o}=e,s=!!o;switch(n){case"CONNECTED":t="RECONNECTING"===i?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===i&&(t=s?32802:32799);break;case"RECONNECTING":t=s?32800:32797}t&&Vx(r.userId,{eventId:t,remoteUserId:o})})),KD.on(uN.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(e=>{let{implementation:t,userId:r,remoteUserId:i,codec:n,isHWCodec:o,prevImplementation:s,streamType:a}=e,c=o?1:0;s||(c=o?3:2);let l="h264"===n?0:2,d={eventId:4004,param1:c,param2:l,streamType:a||2};i&&(d.remoteUserId=i,d.eventId=4005),Vx(r,d),DN.addEnum({key:i?514701:513701,value:c}),DN.addEnum({key:i?514700:513700,value:l})})),KD.on(uN.LOCAL_TRACK_RECAPTURE,(e=>{let{track:t,error:r}=e;if(t.userId){let e={eventId:2003,param1:0};t.kind===WR.AUDIO?(e.streamType=1,r&&(e.param1=2)):(e.streamType="auxiliary"===t.streamType?7:2,r&&(e.param1=8)),Vx(t.userId,e)}}));var Ux=Hb(Jb(),1),Fx=class extends Ux.EventEmitter{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=r,Gb(this,"userMap",new Map),Gb(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find((e=>e.isRobot))}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:i,role:n}=e;if(this.userMap.has(t))return;let o={userId:r,tinyId:i,role:20===n?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let i="peer leave [".concat(e,"]");kP(t)||(i+=":".concat(Bw[t])),this._log.info(i);let n=this.remotePublishedUserMap.get(e);if(n){let t=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let r=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(r,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let r=e[this.key];if(r===this.mySelfId)return;let{flag:i,userId:n,tinyId:o}=e,s=JP(i,n),a=null==(t=this.remotePublishedUserMap.get(r))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(r);e&&e.flag!==i&&(e.flag=i,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:i}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:JP(0,n),muteState:s,flag:i})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Bx(e){let{timesInSecond:t,maxSizeInSecond:r,getSize:i}=e;return sL(((e,n)=>{let o=new WeakMap;return KD.on(uN.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),i&&(s.totalSizeInSecond+=i(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>r))throw new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>r,name:n,timesInSecond:t,maxSizeInSecond:r}})});s.callCountInSecond++,e.call(this,...c)}}))}var jx,Hx=!0,Wx={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"},Gx={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},zx=((jx=zx||{})[jx.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",jx[jx.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",jx[jx.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",jx[jx.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",jx[jx.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",jx[jx.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",jx[jx.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",jx[jx.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",jx[jx.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",jx[jx.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",jx[jx.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",jx[jx.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",jx[jx.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",jx[jx.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",jx[jx.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",jx[jx.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",jx[jx.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",jx[jx.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",jx[jx.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",jx[jx.INVALID_OPERATION=5100]="INVALID_OPERATION",jx[jx.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",jx[jx.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",jx[jx.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",jx[jx.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",jx[jx.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",jx[jx.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",jx[jx.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",jx[jx.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",jx[jx.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",jx[jx.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",jx[jx.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",jx[jx.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",jx[jx.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",jx[jx.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",jx[jx.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",jx[jx.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",jx[jx.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",jx[jx.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",jx[jx.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",jx[jx.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",jx[jx.DEVICE_ERROR=5300]="DEVICE_ERROR",jx[jx.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",jx[jx.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",jx[jx.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",jx[jx.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",jx[jx.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",jx[jx.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",jx[jx.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",jx[jx.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",jx[jx.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",jx[jx.SERVER_ERROR=5400]="SERVER_ERROR",jx[jx.NEED_TO_BUY=5401]="NEED_TO_BUY",jx[jx.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",jx[jx.OPERATION_FAILED=5500]="OPERATION_FAILED",jx[jx.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",jx[jx.REJOIN_FAILED=5502]="REJOIN_FAILED",jx[jx.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",jx[jx.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",jx[jx.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",jx[jx.OPERATION_ABORT=5998]="OPERATION_ABORT",jx[jx.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",jx);var $x=Fb(Ub({},Zw),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' is a required param when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:r,fnName:i,value:n}=e,o="".concat(t||r.name),s="";return s=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(i,"(), received type: ").concat(RP(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' cannot be '").concat(n,"' when calling ").concat(i,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:r,fnName:i,value:n}=e,o="".concat(t||r.name),s="".concat(r.instanceOf.name||r.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(i,"(), received type: ").concat(RP(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:r,fnName:i,value:n}=e;return"'".concat(t||r.name,"' must be one of ").concat(r.values.join("|")," when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:r,fnName:i}=e;return"'".concat(t||r.name,"' cannot be less than 0 when calling ").concat(i,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:r,value:i}=e;return"the min value of ".concat(t||r.name," is ").concat(r.min,", received: ").concat(i,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:r,value:i}=e;return"the max value of ".concat(t||r.name," is ").concat(r.max,", received: ").concat(i,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:r}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(r,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:r,type:i}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(r,"(), received: ").concat(i,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:r}=e;return"cannot ".concat(t," because remote user(userId: ").concat(r.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:r}=e;return"cannot ".concat(t," because remote user(userId: ").concat(r.userId,") does not publishing ").concat(r.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone 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: '".concat("audience","' cannot call this api."),INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:r}=e;return"'".concat(t,"' got device exception").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"NotFoundError, no ".concat(r," detected, please check your device and the configuration on '").concat(t,"'").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"NotAllowedError, you have disabled ".concat(r," access, please allow the current application to use the ").concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"NotReadableError, the ".concat(r," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(r,", and it is recommended to turn on the ").concat(r," after the user interacts with the page").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:r=Jx(t),error:i}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(i?" error: ".concat(i.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:r}=e;return"'".concat(t,"' failed, reason: ").concat(null==r?void 0:r.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:r}=e;return"video context error ".concat(t," ").concat((null==r?void 0:r.name)||""," ").concat((null==r?void 0:r.message)||"")},SERVER_ERROR(e){let{fnName:t,error:r}=e;return"'".concat(t,"' got server error: ").concat(null==r?void 0:r.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:r}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(r)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:r}=e;return"'".concat(t,"' throw unknown exception").concat(r?", error: ".concat(r.toString(),"."):".")}});function Jx(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var qx=class extends Error{constructor(e){let{code:t,extraCode:r,message:i="",messageParams:n,fnName:o="",originError:s}=e;var a;let c;c=i||function(e){let t,{code:r,params:i,enableDocLink:n=!1}=e,s="",a=zx[r];try{t=$x[a]}catch(o){t=$x.UNKNOWN_ERROR}return wP(t)?s=t(i):DP(t)&&(s=t),i.fnName&&!s.includes(i.fnName)&&("."!==s[s.length-1]&&(s+="."),s+=" thrown from ".concat(i.fnName,"()")),n&&(s+=" doc:"),s}({code:t===Gx.SERVER_ERROR?t:r||t,params:Ub({fnName:o,error:s},n)}),super(c),Gb(this,"name","RtcError"),Gb(this,"code"),Gb(this,"extraCode"),Gb(this,"functionName"),Gb(this,"message"),Gb(this,"handler"),Gb(this,"originError"),this.name=zx[t],this.code=t,this.extraCode=r,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes("system"))&&(this.handler=()=>{let e=document.createElement("a");$k?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(e,t,r){let i=e;if(e instanceof sR){let{stack:n}=e,o={code:Gx.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case nR.INVALID_PARAMETER:o.code=Gx.INVALID_PARAMETER,o.message=e.message;break;case nR.INVALID_OPERATION:o.code=Gx.INVALID_OPERATION;break;case nR.NOT_SUPPORTED:case nR.NOT_SUPPORTED_H264:o.code=Gx.ENV_NOT_SUPPORTED,e.getCode()===nR.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(Zw.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case nR.JOIN_ROOM_FAILED:o.messageParams={fnParams:r};case nR.SERVER_TIMEOUT:case nR.SWITCH_ROLE_FAILED:o.code=Gx.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case nR.API_CALL_ABORTED:o.code=Gx.OPERATION_ABORT;break;case nR.DEVICE_NOT_FOUND:case nR.DEVICE_AUTO_RECOVER_FAILED:case nR.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){let t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case nR.UNKNOWN:break;default:o.code=Gx.OPERATION_FAILED}i=new qx(o),n&&(i.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof qx)return e;i=new qx({code:Gx.UNKNOWN_ERROR,fnName:t,originError:e})}return i}};var Kx=qx,Yx={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Xx={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}}},Qx={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,r){if(DP(e)&&!document.getElementById(e))throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5009,fnName:r,messageParams:{key:t}})}},Zx={name:"userId",required:!0,type:"string"},eV={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Wx.AUDIO_PROFILE_STANDARD,Wx.AUDIO_PROFILE_STANDARD_STEREO,Wx.AUDIO_PROFILE_HIGH,Wx.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function tV(e,t){if(!e)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5101,fnName:t})}function rV(e,t,r){if(!e)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:r}})}var iV={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(e,t,r){if(this._room.isJoined)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5104,fnName:r});if(e.roomId){if(DP(e.roomId))throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5016,fnName:r,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5013,fnName:r,messageParams:{key:t}})}else{if(!e.strRoomId)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5015,fnName:r});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5012,fnName:r,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Qx,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Yx},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&UN())throw new Kx({code:Gx.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Fb(Ub({},Qx),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Yx}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:eV},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&UN())throw new Kx({code:Gx.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:eV}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Qx,publish:{type:"boolean"},option:Xx},validate(e,t,r,i,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&UN())throw new Kx({code:Gx.ENV_NOT_SUPPORTED,extraCode:5201});if(!GN())throw new Kx({code:Gx.ENV_NOT_SUPPORTED,fnName:r,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Qx,publish:{type:"boolean"},option:Xx}},muteRemoteAudio:[Zx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Zx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Qx,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,r){tV(this._room.isJoined,r);let i=this._room.remotePublishedUserMap.get(e.userId);if(rV(!!i,r,e),i&&("main"===e.streamType&&!i.muteState.videoAvailable||"sub"===e.streamType&&!i.muteState.hasAuxiliary))throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5103,fnName:r,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Fb(Ub({},Qx),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(e,t,r){tV(this._room.isJoined,r);let i=this._room.remotePublishedUserMap.get(e.userId);if(rV(!!i,r,e),i&&("main"===e.streamType&&!i.muteState.videoAvailable||"sub"===e.streamType&&!i.muteState.hasAuxiliary))throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5103,fnName:r,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,r){if("*"!==e.userId&&kP(e.streamType))throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5014,fnName:r})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,r){tV(this._room.isJoining||this._room.isJoined,r)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,r,i){if(!mO)throw new Kx({code:Gx.ENV_NOT_SUPPORTED,fnName:r,extraCode:5207});if(!this._room.enableSEI)throw new Kx({code:Gx.INVALID_OPERATION,fnName:r,extraCode:5108});if(e.byteLength>1e3)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5018,fnName:r});if(0===e.byteLength)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:r});tV(this._room.isJoined,r)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,r){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:r})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,r,i){if(e.byteLength>1e3)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5018,fnName:r});if(0===e.byteLength)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5017,fnName:r,messageParams:{key:t}})}}},validate(e,t,r){if(tV(this._room.isJoined,r),"live"===this._room.scene&&"audience"===this._room.role)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5107,fnName:r,messageParams:{key:t}})}}},nV={TRTC:iV},oV=class extends Error{};function sV(e,t){let r=XP(e);for(let i=0;i<t.length;i++)YP(r[i],t[i]);return r}function aV(e){this._resolve=Promise.resolve(e)}function cV(e){this._reject=Promise.reject(e)}var lV=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=sV;let r=lV.instances.get(e);r?r.set(t,this):lV.instances.set(e,new Map([[t,this]]))}static get(e,t){if(!t)return;let r=lV.instances.get(e);return r&&r.get(t)||new lV(e,t)}static gets(e,t){let r=lV.instances.get(e),i=[];return r&&r.forEach(((e,r)=>{t.test(r)&&i.push(e)})),i}action(e,t,r){let i=t=>{var r;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(r=this.currentOp)||r.action(),t},n=t=>{var r,i;throw this.ops.shift(),0===e&&2===(null==(r=this.currentOp)?void 0:r.type)&&this.ops.shift().reject(new oV("start failed")),null==(i=this.currentOp)||i.action(),t},o={type:e,action:()=>t(...o.args).then(i,n),args:r,resolve:aV,reject:cV};try{switch(this.state){case 1:if(0===e)throw new oV("already started");break;case 4:if(2===e)throw new oV("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(i,n)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new oV("already start");break;case 3:switch(e.type){case 2:throw new oV("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new oV("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new oV("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 oV("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new oV("start not allowed after update");case 0:throw new oV("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new oV("keep start")),new oV("already start")}}e.promise=new Promise(((t,r)=>{e._resolve?e._resolve.then(t):e.resolve=t,e._reject?e._reject.catch(r):e.reject=r}));let{action:t}=e;return e.action=()=>t().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},dV=lV;dV.instances=new WeakMap;var uV=new WeakMap,hV=(e,t)=>{if(t instanceof oV){let{stack:r}=t;t=new Kx({code:Gx.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),r&&(t.stack+=r.substr(r.indexOf("\n")))}throw t};function pV(e,t){return sL(((r,i)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=dV.get(this,"string"==typeof e?e:e.call(this,...o));return a?(t&&(a.startSame=t.bind(this)),a.action(0,r.bind(this),o).catch(hV.bind(null,i))):r.apply(this,o)}))}function mV(e,t){let{merge:r,debounce:i}=t||{};return sL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=dV.get(this,"string"==typeof e?e:e.call(this,...s));if(!c)return t.apply(this,s);if(r&&(c.mergeUpdate=r.bind(this)),i&&i.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:r}=i;return new Promise(((i,o)=>{var a,l;let d=null==(a=uV.get(this))?void 0:a.get(r(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return i();c.action(2,t.bind(this),s).catch(hV.bind(null,n)).then(i,o)}),e);uV.has(this)?null==(l=uV.get(this))||l.set(r(...s),{timeoutId:u,resolve:i}):uV.set(this,new Map([[r(...s),{timeoutId:u,resolve:i}]]))}))}return c.action(2,t.bind(this),s).catch(hV.bind(null,n))}))}function fV(e){return sL(((t,r)=>function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];let s="function"==typeof e?e.call(this,...n):e;if(s instanceof RegExp)return Promise.all(dV.gets(this,s).map((e=>e.action(3,(()=>Promise.resolve()),n)))).then((()=>t.call(this,...n)));let a=dV.get(this,s);return a?a.action(3,t.bind(this),n).catch(hV.bind(null,r)):t.apply(this,n)}))}var _V={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"},gV=new Set([_V.ERROR,_V.AUTOPLAY_FAILED,_V.KICKED_OUT,_V.REMOTE_USER_ENTER,_V.REMOTE_USER_EXIT,_V.REMOTE_AUDIO_AVAILABLE,_V.REMOTE_AUDIO_UNAVAILABLE,_V.REMOTE_VIDEO_AVAILABLE,_V.REMOTE_VIDEO_UNAVAILABLE,_V.CONNECTION_STATE_CHANGED,_V.PUBLISH_STATE_CHANGED,_V.SCREEN_SHARE_STOPPED,_V.DEVICE_CHANGED]);function vV(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function yV(e){return e===Wx.QOS_PREFERENCE_CLEAR?"detail":e===Wx.QOS_PREFERENCE_SMOOTH?"motion":""}var EV=class{constructor(){Gb(this,"_log"),this._log=pN.createLogger({id:"fd"})}download(e,t){return $b(this,null,(function*(){let{type:r="blob"}=t||{};try{let t,i=HP();if(t=wP(fetch)?yield this.downloadWithFetch(e,r):yield this.downloadWithXHR(e,r),!t||!t.data)throw new Error("data is empty");let n=HP()-i;return this._log.info("downloaded: ".concat(e,", return type: ").concat(r,", cost: ").concat(n,"ms")),DN.addSuccessEvent({key:522700,cost:HP()-i}),t.data}catch(_R){throw this._log.error("failed to download: ".concat(e,", error: ").concat(_R)),DN.addFailedEvent({key:522700,error:_R}),_R}}))}downloadWithFetch(e,t){return $b(this,null,(function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let r,i=yield fetch(e);if(!i.ok)throw new Error("network response was not ok");return r="arraybuffer"===t?yield i.arrayBuffer():yield i.blob(),{data:r}}catch(gw){throw gw}}))}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise(((r,i)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{200===n.status||0===n.status&&n.response?r({data:n.response}):i(new Error("XHR failed"))},n.onerror=i,n.send(null)}))}loadWasm(e,t){return $b(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let r=HP(),i=null,n=null;if(wP(WebAssembly.instantiateStreaming)&&!(e=>e.startsWith("data:application/octet-stream;base64,"))(e)&&!(e=>e.startsWith("file://"))(e)&&wP(fetch))try{let r=fetch(e);i=(yield WebAssembly.instantiateStreaming(r,t)).instance}catch(gR){n=gR}if(!i)try{let r=yield this.download(e,{type:"arraybuffer"});i=(yield WebAssembly.instantiate(r,t)).instance}catch(gR){n=gR}if(i){let t=HP()-r;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),DN.addSuccessEvent({key:522701,cost:t}),i}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),DN.addFailedEvent({key:522701,error:n}),n}))}};Wb([GO({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],EV.prototype,"download",1);var TV=new EV;function SV(e){let{TRTC:t,room:r,errorModule:i,assetsPath:n}=e;return{TRTC:t,room:r,assetsPath:n,fileDownloader:TV,innerEmitter:KD,constants:uR,environment:ek,utils:dR,eventLogger:XD,log:this.room.getLogger(),loggerManager:pN,errorModule:i,kvStatManager:DN,rtcDectection:_N,trtc:this,clearStarted:(e,t)=>{let r=e.getAlias(),i=dV.instances.get(this);if(i)if(t){let e=i.get(r+t);if(!e)return;e.started=!1}else i.forEach(((e,t)=>{t.startsWith(r)&&(e.started=!1)}))},startGetPCM:kL,createAudioNode:RM}}var IV=new WeakMap;function AV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return sL(((e,r)=>function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];try{bV.call(this,t,n,r,this._name)}catch(_R){return Promise.reject(_R)}return e.apply(this,n)}))}function CV(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return sL(((e,r)=>function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];try{bV.call(this,t,n,r,this._name)}catch(_R){throw _R}return e.apply(this,n)}))}function bV(e,t,r,i){if(MP(e))for(let n=0;n<e.length;n++)RV.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:r,className:i});else RV.call(this,{rule:e,value:t[0],key:e.name,fnName:r,className:i})}function RV(e){let{rule:t,value:r,key:i,fnName:n,className:o}=e;function s(e){return{code:Gx.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:i,rule:t,value:r}}}if(kP(r)){if(t.required)throw new Kx(s(5001));if(kP(t.defaultValue))return void(wP(t.validate)&&t.validate.call(this,r,i,n,o,this));r=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let i=0;i<t.type.length;i++)null===t.type[i]&&null===r&&(e=!0),wP(t.type[i])&&r instanceof t.type[i]&&(e=!0),DP(t.type[i])&&RP(r)===t.type[i].toLowerCase()&&(e=!0);if(!e)throw new Kx({code:Gx.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:i,rule:{type:t.type.map((e=>UP(e)?FP(e):DP(e)?e:RP(e)))},value:r}})}else if(!kP(t.type)&&RP(r)!==t.type)throw new Kx(s(5002));if(!1===t.allowEmpty){let e=PP(r)&&(0===r||Number.isNaN(r)),t=DP(r)&&""===r.trim();if(e||t)throw new Kx(s(5003))}if(t.notLessThanZero&&PP(r)&&r<0)throw new Kx(s(5006));if(!kP(t.min)&&PP(r)&&r<t.min)throw new Kx(s(5007));if(!kP(t.max)&&PP(r)&&r>t.max)throw new Kx(s(5008));if(DP(t.instanceOf)){if(!r||r._name!==t.instanceOf)throw new Kx(s(5004))}else if(wP(t.instanceOf)&&!(r instanceof t.instanceOf))throw new Kx(s(5004));if(Array.isArray(t.values)&&!t.values.includes(r))throw new Kx(s(5005));let{properties:a}=t;AP(a)&&OP(r)&&Object.keys(a).forEach((e=>{RV.call(this,{rule:a[e],value:r&&r[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;AP(c)&&MP(r)&&r.forEach(((e,t)=>{RV.call(this,{rule:c,value:e,key:"".concat(i,"[").concat(t,"]"),fnName:n,className:o})})),wP(t.validate)&&t.validate.call(this,r,i,n,o,this)}function wV(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:r,getKVReportKey:i,ignoreLog:n}=e;return sL(((e,o)=>function(){for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];var l;function d(e,t,i){if(i&&i.includes(e))return"hided";if(r){let e=r(...a);if(a[e.argIndex]===t)return e.value}if(t===a||e in a)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(RP(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(RP(t))}}let u=this._log||pN;if(null!=n&&n(...a))return e.apply(this,a);a.length>0?u.info("".concat(o,"() ").concat(JSON.stringify(a,((e,t)=>d(e,t,["userSig","privateMapKey"]))))):u.info("".concat(o,"()"));let h=i?i(...a):SN[o];try{let r=e.apply(this,a),i=HP();return VP(r)?r.then((e=>(u.info("".concat(o,"() success ").concat(t.call(this,...a))),DN.addSuccessEvent({key:h,cost:HP()-i}),e))).catch((e=>{var r;let i=(e=Kx.convertFrom.call(this,e,o,1===a.length?a[0]:a)).extraCode||e.code,n=null!=(r=e.message)&&r.includes(i)?"":" code:".concat(i);throw u.error("".concat(o,"() failed ").concat(t.call(this,...a)," ").concat(e).concat(n," params: ").concat(JSON.stringify(a,d))),DN.addFailedEvent({key:h,error:e}),e})):(DN.addSuccessEvent({key:h}),r)}catch(p){let e=(p=Kx.convertFrom.call(this,p,o)).extraCode||p.code,t=null!=(l=p.message)&&l.includes(e)?"":" code:".concat(e);throw u.error("".concat(o,"() failed ").concat(p).concat(t," params: ").concat(JSON.stringify(a,d))),DN.addFailedEvent({key:h,error:p}),p}}))}var kV=e=>sL(((t,r)=>function(i,n){return $b(this,null,(function*(){let o=this._plugins.get(i);if(!o)throw this._log.error("plugin ".concat(String(i)," is not found")),new Kx({code:Gx.OPERATION_ABORT,message:"plugin ".concat(String(i)," is not found"),fnName:r});if(wP(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error("plugin ".concat(String(i)," is not supported")),new Kx({code:Gx.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(i)," is not supported"),extraCode:5210,fnName:r});return bV.call(this,o.getValidateRule(e),[n],r,"TRTC"),t.call(this,o,n)}))})),DV=0,PV=class{constructor(e,t){Gb(this,"player"),Gb(this,"publisher"),Gb(this,"mixInput"),this.mixInput=new AM(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||(kP(e.volume)||(this.volume=e.volume),kP(e.loop)||(this.loop=e.loop),kP(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=e=>{t(e.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{t(r.currentTime,r.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function NV(e,t){if(t&&"function"!=typeof t)throw new Kx({code:Gx.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var OV=class{constructor(e){this.core=e,Gb(this,"log"),Gb(this,"mixedMusicMap",new Map),Gb(this,"cacheMusicMap",new Map),DV+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(DV)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(DV)),this.core=e}getName(){return OV.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return OV.startValidateRule;case"update":return OV.updateValidateRule;case"stop":return OV.stopValidateRule}}start(e){return $b(this,null,(function*(){let{room:t}=this.core;this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:r,url:i}=e;if(this.mixedMusicMap.has(r))return;let n=this.cacheMusicMap.get(r);n?e.url?n.reset():(n.mixInput.replaceSource(e.track),n.mixInput.connect()):(n=new PV(e,t.audioManager),this.cacheMusicMap.set(r,n)),n.updateListener(e),n.updateSettings(e),yield n.play(),this.mixedMusicMap.set(r,n),this.log.info("start mix audio track ".concat(r," success.")),DN.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return $b(this,null,(function*(){let{id:t,operation:r,seekFrom:i,playbackRate:n}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let o=this.mixedMusicMap.get(t);o?(o.updateSettings(e),o.updateListener(e),kP(r)||o.setOperation(r),kP(i)||o.seek(i),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return $b(this,arguments,(function(e){var t=this;let{id:r}=e;return function*(){var e;t.mixedMusicMap.has(r)&&(t.log.info("remove music source, music id: ".concat(r)),null==(e=t.mixedMusicMap.get(r))||e.stop(),t.mixedMusicMap.delete(r)),"*"===r&&t.destroyAllMusic()}()}))}kvUpload(e){let{track:t,loop:r,volume:i,playbackRate:n,operation:o,seekFrom:s,onTimeUpdate:a,onDurationChange:c,onEnded:l}=e;t&&DN.addCount({key:502711}),r&&DN.addCount({key:502703}),i&&DN.addCount({key:502704}),n&&DN.addCount({key:502705}),o&&DN.addCount({key:502706}),s&&DN.addCount({key:502707}),"function"!=typeof a&&DN.addCount({key:502709}),"function"!=typeof l&&DN.addCount({key:502710}),"function"!=typeof c&&DN.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},MV=OV;Gb(MV,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,r){if(e.url&&"*"!==e.url){let t=e.url.split("?")[0],i=["mp3","ogg","wav","flac"],n=t.split(".").pop(),o=i.indexOf(n)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new Kx({code:Gx.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!e.url&&!e.track)throw new Kx({code:Gx.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});NV("onTimeUpdate",e.onTimeUpdate),NV("onEnded",e.onEnded),NV("onDurationChange",e.onDurationChange)}}),Gb(MV,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(e,t,r){NV("onTimeUpdate",e.onTimeUpdate),NV("onEnded",e.onEnded),NV("onDurationChange",e.onDurationChange)}}),Gb(MV,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Gb(MV,"Name","AudioMixer");var LV,xV=0,VV=class{constructor(e){this.core=e,Gb(this,"log"),Gb(this,"audioContext",EM()),Gb(this,"workletNode"),xV+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(xV)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(xV)),e.assetsPath&&this.preload("".concat(e.assetsPath,"/denoiser-wasm.js"))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,r,i,n){if(!e.room.audioManager.hasAudioTrack)throw new Kx({code:Gx.INVALID_OPERATION,extraCode:5106,fnName:i})}}}preload(e){return LV||(LV=this.doPreload(e)),LV}doPreload(e){return $b(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),r=URL.createObjectURL(t);try{yield _M(this.audioContext,r)}finally{URL.revokeObjectURL(r)}}))}getName(){return VV.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return VV.startValidateRule(this.core);case"update":return VV.updateValidateRule;case"stop":return VV.stopValidateRule}}start(e){return $b(this,null,(function*(){let{room:t}=this.core;if(yield this.preload("".concat(e.assetsPath,"/denoiser-wasm.js")),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:i,status:n,message:o}=yield function(e){return $b(this,arguments,(function(e){let{sdkAppId:t,userId:r,userSig:i,timestamp:n}=e;return function*(){let e="".concat(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:WR.MAIN;return"https://".concat(rP[t]||sP(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(r,"&userSig=").concat(i,"×tamp=").concat(n),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}(Fb(Ub({},e),{timestamp:t}));if(!r)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(r,". Message: ").concat(o)),new Kx({code:Gx.INVALID_PARAMETER,message:o});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:i,status:n}}),this.workletNode.port.onmessage=e=>{let{data:t}=e;"cost"===t.type&&this.log.debug("[RTCAIDenoiser] ".concat(t.value))}}this.workletNode.port.postMessage({type:"enable"}),t.audioManager.addDenoiser(this.workletNode),t.sendAbilityStatus({ai_denoise:1})}))}update(){return $b(this,null,(function*(){}))}stop(){return $b(this,null,(function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)}))}destroy(){!this.workletNode||(this.workletNode.port.onmessage=null)}},UV=VV;Gb(UV,"updateValidateRule",{type:"object"}),Gb(UV,"stopValidateRule",{type:"object"}),Gb(UV,"Name","AIDenoiser");var FV=Hb(Jb(),1),BV=class extends FV.EventEmitter{constructor(){super(),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 $b(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&!hk&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(fR){XD.uploadEvent({log:"stat-pressure-detector-start-failed",error:fR})}}))}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&pN.info("".concat(r.source,": ").concat(r.state)),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(gw){XD.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:gw})}}},jV=new BV;function HV(e){let[t,r]=e,i=r.byteLength,n=parseInt(String(i/255),10),o=i%255,s=[];s.push(0,0,0,1,6,t);for(let c=0;c<n;c++)s.push(255);s.push(o);let a=new DataView(r);return s.push(...new Uint8Array(a.buffer)),s.push(128),new EL(new DataView(new Uint8Array(s).buffer),!0)}function WV(e){return"empty"===e.type||0===e.data.byteLength}function GV(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function zV(e){let t=0,r=0,i=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(i.getUint8(n)){case 0:t++;break;case 1:(2===t||3===t)&&r++,t=0;break;default:t=0}return r}function $V(e){let{frame:t,seiMessageList:r}=e;if(!r||0===r.length||0===t.data.byteLength)return t;let i=9-zV(t.data);if(i<=0)return t;let n=r.splice(0,i).reverse().map(HV),o=n.reduce(((e,t)=>e+t.dataView.byteLength),0),s=new ArrayBuffer(o+t.data.byteLength),a=new DataView(s),c=new DataView(t.data),l=0;for(let d=0;d<n.length;d++)for(let e=0;e<n[d].dataView.byteLength;e++)a.setInt8(l++,n[d].dataView.getInt8(e));for(let d=0;d<t.data.byteLength;d++)a.setInt8(l++,c.getInt8(d));return t.data=s,t}function JV(e){let{frame:t,onSEI:r}=e;try{let e=new DataView(t.data);if(WV(t)||!GV(e))return t;let i=[],n=0,o=-1,s=-1;for(let r=0;r<t.data.byteLength;r++){let a=e.getUint8(r);if(0===a)n++;else if(1===a){if(2===n||3===n){let a=r-n;if(-1===o?o=a:-1===s&&(s=a,i.push(new EL(new DataView(e.buffer.slice(o,s)))),o=a,s=-1),6!==e.getUint8(r+1)){t.data=e.buffer.slice(a);break}}n=0}else n=0}null==r||r(i.reverse())}catch(fR){}return t}var qV=0,KV=class{constructor(e){this.core=e,Gb(this,"log"),Gb(this,"_seiMessageList",[]),Gb(this,"_smallSeiMessageList",[]),Gb(this,"_subStreamSeiMessageList",[]),qV++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(qV)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(qV)),this.core=e,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:t,mediaType:r}=e;try{return $V({frame:t,seiMessageList:8===r?this._smallSeiMessageList:2===r?this._subStreamSeiMessageList:this._seiMessageList})}catch(gw){this.log.warn(gw)}return t}decode(e){let{frame:t,track:r}=e;return JV({frame:t,onSEI:e=>{e.forEach((e=>{this.core.trtc.emit(_V.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:r.userId,streamType:2===r.mediaType?"sub":"main"})}))}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:hO?this.encode:$V,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:hO?this.decode:JV,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update(e){let{buffer:t,options:r}=e;var i;let n=[r.seiPayloadType,t],o=!!r.small;r.toSubStream?this._subStreamSeiMessageList.push(n):(this._seiMessageList.push(n),o&&this._smallSeiMessageList.push(n)),null==(i=this.core.room.scriptTransformWorker)||i.postMessage({type:"sei",data:n,isMain:!r.toSubStream,small:o})}getName(){return KV.Name}getAlias(){return"sei"}getGroup(){return"sei"}},YV=KV;Gb(YV,"autoStart",!0),Gb(YV,"Name","SEI");var XV=Hb(Jb(),1),QV=Symbol("instance"),ZV=Symbol("cacheResult"),eU=class{constructor(e,t,r){this.oldState=e,this.newState=t,this.action=r,this.aborted=!1}abort(e){this.aborted=!0,sU.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},tU=class extends Error{constructor(e,t,r){super(t),this.state=e,this.message=t,this.cause=r}};var rU=new Map;function iU(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(i,n,o)=>{let s=r.action||n;if(!r.context){let r=rU.get(i)||[];rU.has(i)||rU.set(i,r),r.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let i=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(r.context&&(i=aU.get("function"==typeof r.context?r.context.call(this,...o):r.context)),i.state===t)return r.sync?i[ZV]:Promise.resolve(i[ZV]);i.state instanceof eU&&i.state.action==r.abortAction&&i.state.abort(i);let l=null;Array.isArray(e)?0==e.length?i.state instanceof eU&&i.state.abort(i):("string"!=typeof i.state||!e.includes(i.state))&&(l=new tU(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e.join("|")))):e!==i.state&&(l=new tU(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e)));let d=e=>{if(r.fail&&r.fail.call(this,e),r.sync){if(r.ignoreError)return e;throw e}return r.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=i.state,h=new eU(u,t,s);sU.call(i,h);let p=e=>{var n;return i[ZV]=e,h.aborted||(sU.call(i,t),null===(n=r.success)||void 0===n||n.call(this,i[ZV])),e},m=e=>(sU.call(i,u,e),d(e));try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):r.sync?p(e):Promise.resolve(p(e))}catch(f){return m(f)}}}}function nU(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return(e,r,i)=>{let n=i.value,o=r;i.value=function(){if(!t.includes(this.state.toString()))throw new tU(this.state,"".concat(this.name," ").concat(o," failed: current state ").concat(this.state," not in ").concat(t));for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];return n.apply(this,r)}}}var oU="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 sU(e,t){let r=this._state;this._state=e;let i=e.toString();e&&this.emit(i,r),this.emit(aU.STATECHANGED,e,r,t),this.updateDevTools({value:e,old:r,err:t instanceof Error?t.message:String(t)})}var aU=class extends XV.default{constructor(e,t,r){super(),this.name=e,this.groupName=t,this._state=aU.INIT,e||(e=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let i=r[QV];i?this.name=i.name+"-"+i.count++:r[QV]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=rU.get(e)||[],r=new Set,i=[],n=[],o=new Set,s=Object.getPrototypeOf(e);rU.has(s)&&(s.stateDiagram.forEach((e=>r.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:r,action:o}=e;"string"==typeof t?i.push({from:t,to:r,action:o}):t.length?t.forEach((e=>{i.push({from:e,to:r,action:o})})):n.push({to:r,action:o})})),i.forEach((e=>{let{from:t,to:i,action:n}=e;o.add(t),o.add(i),o.add(n+"ing"),r.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),r.add("".concat(n,"ing --\x3e ").concat(i," : ").concat(n," 🟢")),r.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:i}=e;r.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🟢")),o.forEach((e=>{e!==t&&r.add("".concat(e," --\x3e ").concat(i,"ing : ").concat(i))}))}));let a=[...r];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=aU.instances.get(e),t||aU.instances.set(e,t=new aU(e,void 0,Object.create(aU.prototype)))):(t=aU.instances2.get(e),t||aU.instances2.set(e,t=new aU(e.constructor.name,void 0,Object.create(aU.prototype)))),t}static getState(e){var t;return null===(t=aU.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};oU(aU.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){sU.call(this,e)}};function cU(){var e;self.onmessage=t=>{if("init"===t.data.type){let{canvas:r,wasmScript:i,wasmBinary:n}=t.data,o=null==r?void 0:r.getContext("2d"),s=0,a=0,c={wasmBinary:n,postRun:()=>{e=new c.VideoDecoder({videoInfo(e,t){s=e,a=t,console.log("video info",e,t)},yuvData(e,t){let i=s*a,n=i>>2,l=c.HEAPU32[e>>2],d=c.HEAPU32[1+(e>>2)],u=c.HEAPU32[2+(e>>2)],h=c.HEAPU8.subarray(l,l+i),p=c.HEAPU8.subarray(d,d+n),m=c.HEAPU8.subarray(u,u+n),f=new Uint8Array(i+n+n);f.set(h),f.set(p,i),f.set(m,i+n);let _=new VideoFrame(f,{codedWidth:s,codedHeight:a,format:"I420",timestamp:t});r?(null==o||o.drawImage(_,0,0,r.width,r.height),null==o||o.commit()):self.postMessage({type:"yuvData",videoFrame:_},[_])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+i)()(c)}else if("decode"===t.data.type){let{packet:r}=t.data;null==e||e.decode(r.data,"key"==r.type,r.timestamp)}else if("setCodec"===t.data.type){let{codec:r,format:i,description:n}=t.data;null==e||e.setCodec(r,i,null!=n?n:"")}}}aU.STATECHANGED="stateChanged",aU.UPDATEAFSM="updateAFSM",aU.INIT="[*]",aU.ON="on",aU.OFF="off",aU.instances=new Map,aU.instances2=new WeakMap;var lU=class extends aU{constructor(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.createModule=e,this.wasmBinary=t,this.workerMode=r,this.canvas=i,this.yuvMode=n,this.module={},this.width=0,this.height=0}initialize(e){return $b(this,null,(function*(){var t;if(this.workerMode){let e=new RegExp("\\{(.+)\\}","s").exec(cU.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([e],{type:"text/javascript"})));let r=null==(t=this.canvas)?void 0:t.transferControlToOffscreen(),i=yield this.wasmBinary;return console.warn("worker mode",i),this.worker.postMessage({type:"init",canvas:r,wasmScript:this.createModule.toString(),wasmBinary:i},r?[r,i]:[i]),new Promise((e=>{this.worker.onmessage=t=>{if("ready"===t.data.type)delete this.wasmBinary,e(),console.warn("worker mode initialize success");else if("yuvData"===t.data.type){let{videoFrame:e}=t.data;this.emit("videoFrame",e)}}}))}let r=this.module;return this.wasmBinary&&(r.wasmBinary=yield this.wasmBinary),r.print=e=>console.log(e),r.printErr=e=>console.log("[JS] ERROR: ".concat(e)),r.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise((t=>{r.postRun=e=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),t()},e&&Object.assign(r,e),this.createModule(r)}))}))}configure(e){var t,r,i;this.config=e,null==(r=this.decoder)||r.setCodec(this.config.codec,this.config.description?"avcc":"annexb",null!=(t=this.config.description)?t:""),null==(i=this.worker)||i.postMessage({type:"setCodec",codec:this.config.codec,format:this.config.description?"avcc":"annexb",description:this.config.description})}decode(e){var t,r;null==(t=this.decoder)||t.decode(e.data,"key"==e.type,e.timestamp),"configured"===this.state&&(null==(r=this.worker)||r.postMessage({type:"decode",packet:e}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(e,t){this.width=e,this.height=t;let r={width:e,height:t};this.emit("videoCodecInfo",r)}yuvData(e,t){if(!this.module)return;let r=this.width*this.height,i=r>>2,n=this.module.HEAPU32[e>>2],o=this.module.HEAPU32[1+(e>>2)],s=this.module.HEAPU32[2+(e>>2)],a=this.module.HEAPU8.subarray(n,n+r),c=this.module.HEAPU8.subarray(o,o+i),l=this.module.HEAPU8.subarray(s,s+i);if(this.yuvMode)return void this.emit("videoFrame",[a,c,l]);let d=new Uint8Array(r+i+i);d.set(a),d.set(c,r),d.set(l,r+i),this.emit("videoFrame",new VideoFrame(d,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(e){let t={errMsg:e};this.emit("error",t)}};Wb([iU([aU.INIT,"closed"],"initialized")],lU.prototype,"initialize",1),Wb([iU("initialized","configured")],lU.prototype,"configure",1),Wb([iU([],aU.INIT)],lU.prototype,"reset",1),Wb([iU([],"closed")],lU.prototype,"close",1);var dU=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var r,i,n=t;n.ready=new Promise(((e,t)=>{r=e,i=t}));var o=Object.assign({},n),s="./this.program",a="object"==typeof window,c="function"==typeof importScripts;"object"==typeof process&&"object"==typeof process.versions&&process.versions.node;var l,d,u,h="";(a||c)&&(c?h=self.location.href:"undefined"!=typeof document&&document.currentScript&&(h=document.currentScript.src),e&&(h=e),h=0!==h.indexOf("blob:")?h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):"",l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},c&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),d=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var p,m=n.print||console.log.bind(console),f=n.printErr||console.error.bind(console);Object.assign(n,o),o=null,n.arguments&&n.arguments,n.thisProgram&&(s=n.thisProgram),n.quit&&n.quit,n.wasmBinary&&(p=n.wasmBinary),n.noExitRuntime,"object"!=typeof WebAssembly&&L("no native wasm support detected");var _,g,v,y,E,T,S,I,A,C,b=!1;var R,w=[],k=[],D=[];var P=0,N=null;function O(e){P++,n.monitorRunDependencies&&n.monitorRunDependencies(P)}function M(e){if(P--,n.monitorRunDependencies&&n.monitorRunDependencies(P),0==P&&N){var t=N;N=null,t()}}function L(e){n.onAbort&&n.onAbort(e),f(e="Aborted("+e+")"),b=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}var x,V,U="data:application/octet-stream;base64,";function F(e){return e.startsWith(U)}function B(e){if(e==x&&p)return new Uint8Array(p);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}function j(e,t,r){return function(e){return p||!a&&!c||"function"!=typeof fetch?Promise.resolve().then((()=>B(e))):fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>B(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(r,(e=>{f("failed to asynchronously prepare wasm: "+e),L(e)}))}F(x="videodec.wasm")||(V=x,x=n.locateFile?n.locateFile(V,h):h+V);var H,W,G=e=>{for(;e.length>0;)e.shift()(n)};function z(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){I[this.ptr+4>>2]=e},this.get_type=function(){return I[this.ptr+4>>2]},this.set_destructor=function(e){I[this.ptr+8>>2]=e},this.get_destructor=function(){return I[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,v[this.ptr+12|0]=e},this.get_caught=function(){return 0!=v[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,v[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=v[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){I[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return I[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Kt(this.get_type()))return I[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var $={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=$.isAbs(e),r="/"===e.substr(-1);return!(e=$.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))&&!t&&(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=$.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=$.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return $.normalize(e.join("/"))},join2:(e,t)=>$.normalize(e+"/"+t)},J=e=>(J=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);L("initRandomDevice")})())(e),q={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:ae.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=$.isAbs(i)}return(t?"/":"")+(e=$.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=q.resolve(e).substr(1),t=q.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),o=Math.min(i.length,n.length),s=o,a=0;a<o;a++)if(i[a]!==n[a]){s=a;break}var c=[];for(a=s;a<i.length;a++)c.push("..");return(c=c.concat(n.slice(s))).join("/")}},K="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,Y=(e,t,r)=>{for(var i=t+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&K)return K.decode(e.subarray(t,n));for(var o="";t<n;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var c=63&e[t++];if((s=224==(240&s)?(15&s)<<12|a<<6|c:(7&s)<<18|a<<12|c<<6|63&e[t++])<65536)o+=String.fromCharCode(s);else{var l=s-65536;o+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else o+=String.fromCharCode((31&s)<<6|a)}else o+=String.fromCharCode(s)}return o},X=[],Q=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i<=127?t++:i<=2047?t+=2:i>=55296&&i<=57343?(t+=4,++r):t+=3}return t},Z=(e,t,r,i)=>{if(!(i>0))return 0;for(var n=r,o=r+i-1,s=0;s<e.length;++s){var a=e.charCodeAt(s);if(a>=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&e.charCodeAt(++s);if(a<=127){if(r>=o)break;t[r++]=a}else if(a<=2047){if(r+1>=o)break;t[r++]=192|a>>6,t[r++]=128|63&a}else if(a<=65535){if(r+2>=o)break;t[r++]=224|a>>12,t[r++]=128|a>>6&63,t[r++]=128|63&a}else{if(r+3>=o)break;t[r++]=240|a>>18,t[r++]=128|a>>12&63,t[r++]=128|a>>6&63,t[r++]=128|63&a}}return t[r]=0,r-n};function ee(e,t,r){var i=r>0?r:Q(e)+1,n=new Array(i),o=Z(e,n,0,n.length);return t&&(n.length=o),n}var te={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){te.ttys[e]={input:[],output:[],ops:t},ae.registerDevice(e,te.stream_ops)},stream_ops:{open:function(e){var t=te.ttys[e.node.rdev];if(!t)throw new ae.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,r,i,n){if(!e.tty||!e.tty.ops.get_char)throw new ae.ErrnoError(60);for(var o=0,s=0;s<i;s++){var a;try{a=e.tty.ops.get_char(e.tty)}catch(c){throw new ae.ErrnoError(29)}if(void 0===a&&0===o)throw new ae.ErrnoError(6);if(null==a)break;o++,t[r+s]=a}return o&&(e.node.timestamp=Date.now()),o},write:function(e,t,r,i,n){if(!e.tty||!e.tty.ops.put_char)throw new ae.ErrnoError(60);try{for(var o=0;o<i;o++)e.tty.ops.put_char(e.tty,t[r+o])}catch(s){throw new ae.ErrnoError(29)}return i&&(e.node.timestamp=Date.now()),o}},default_tty_ops:{get_char:function(e){return(()=>{if(!X.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;X=ee(e,!0)}return X.shift()})()},put_char:function(e,t){null===t||10===t?(m(Y(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(m(Y(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,r){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(f(Y(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(f(Y(e.output,0)),e.output=[])}}},re=e=>{L()},ie={ops_table:null,mount:e=>ie.createNode(null,"/",16895,0),createNode(e,t,r,i){if(ae.isBlkdev(r)||ae.isFIFO(r))throw new ae.ErrnoError(63);ie.ops_table||(ie.ops_table={dir:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,lookup:ie.node_ops.lookup,mknod:ie.node_ops.mknod,rename:ie.node_ops.rename,unlink:ie.node_ops.unlink,rmdir:ie.node_ops.rmdir,readdir:ie.node_ops.readdir,symlink:ie.node_ops.symlink},stream:{llseek:ie.stream_ops.llseek}},file:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:{llseek:ie.stream_ops.llseek,read:ie.stream_ops.read,write:ie.stream_ops.write,allocate:ie.stream_ops.allocate,mmap:ie.stream_ops.mmap,msync:ie.stream_ops.msync}},link:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,readlink:ie.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:ae.chrdev_stream_ops}});var n=ae.createNode(e,t,r,i);return ae.isDir(n.mode)?(n.node_ops=ie.ops_table.dir.node,n.stream_ops=ie.ops_table.dir.stream,n.contents={}):ae.isFile(n.mode)?(n.node_ops=ie.ops_table.file.node,n.stream_ops=ie.ops_table.file.stream,n.usedBytes=0,n.contents=null):ae.isLink(n.mode)?(n.node_ops=ie.ops_table.link.node,n.stream_ops=ie.ops_table.link.stream):ae.isChrdev(n.mode)&&(n.node_ops=ie.ops_table.chrdev.node,n.stream_ops=ie.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=ae.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,ae.isDir(e.mode)?t.size=4096:ae.isFile(e.mode)?t.size=e.usedBytes:ae.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&&ie.resizeFileStorage(e,t.size)},lookup(e,t){throw ae.genericErrors[44]},mknod:(e,t,r,i)=>ie.createNode(e,t,r,i),rename(e,t,r){if(ae.isDir(e.mode)){var i;try{i=ae.lookupNode(t,r)}catch(o){}if(i)for(var n in i.contents)throw new ae.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=ae.lookupNode(e,t);for(var i in r.contents)throw new ae.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)!e.contents.hasOwnProperty(r)||t.push(r);return t},symlink(e,t,r){var i=ie.createNode(e,t,41471,0);return i.link=r,i},readlink(e){if(!ae.isLink(e.mode))throw new ae.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,i,n){var o=e.node.contents;if(n>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-n,i);if(s>8&&o.subarray)t.set(o.subarray(n,n+s),r);else for(var a=0;a<s;a++)t[r+a]=o[n+a];return s},write(e,t,r,i,n,o){if(!i)return 0;var s=e.node;if(s.timestamp=Date.now(),t.subarray&&(!s.contents||s.contents.subarray)){if(o)return s.contents=t.subarray(r,r+i),s.usedBytes=i,i;if(0===s.usedBytes&&0===n)return s.contents=t.slice(r,r+i),s.usedBytes=i,i;if(n+i<=s.usedBytes)return s.contents.set(t.subarray(r,r+i),n),i}if(ie.expandFileStorage(s,n+i),s.contents.subarray&&t.subarray)s.contents.set(t.subarray(r,r+i),n);else for(var a=0;a<i;a++)s.contents[n+a]=t[r+a];return s.usedBytes=Math.max(s.usedBytes,n+i),i},llseek(e,t,r){var i=t;if(1===r?i+=e.position:2===r&&ae.isFile(e.node.mode)&&(i+=e.node.usedBytes),i<0)throw new ae.ErrnoError(28);return i},allocate(e,t,r){ie.expandFileStorage(e.node,t+r),e.node.usedBytes=Math.max(e.node.usedBytes,t+r)},mmap(e,t,r,i,n){if(!ae.isFile(e.node.mode))throw new ae.ErrnoError(43);var o,s,a=e.node.contents;if(2&n||a.buffer!==v.buffer){if((r>0||r+t<a.length)&&(a=a.subarray?a.subarray(r,r+t):Array.prototype.slice.call(a,r,r+t)),s=!0,!(o=re()))throw new ae.ErrnoError(48);v.set(a,o)}else s=!1,o=a.byteOffset;return{ptr:o,allocated:s}},msync:(e,t,r,i,n)=>(ie.stream_ops.write(e,t,0,i,r,!1),0)}},ne=(e,t,r,i)=>{var n=i?"":"al ".concat(e);d(e,(r=>{(function(e,t){e||L(t)})(r,'Loading data file "'.concat(e,'" failed (no arrayBuffer).')),t(new Uint8Array(r)),n&&M()}),(t=>{if(!r)throw'Loading data file "'.concat(e,'" failed.');r()})),n&&O()},oe=n.preloadPlugins||[];function se(e,t){var r=0;return e&&(r|=365),t&&(r|=146),r}var ae={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=q.resolve(e)))return{path:"",node:null};if(t=Object.assign({follow_mount:!0,recurse_count:0},t),t.recurse_count>8)throw new ae.ErrnoError(32);for(var r=e.split("/").filter((e=>!!e)),i=ae.root,n="/",o=0;o<r.length;o++){var s=o===r.length-1;if(s&&t.parent)break;if(i=ae.lookupNode(i,r[o]),n=$.join2(n,r[o]),ae.isMountpoint(i)&&(!s||s&&t.follow_mount)&&(i=i.mounted.root),!s||t.follow)for(var a=0;ae.isLink(i.mode);){var c=ae.readlink(n);if(n=q.resolve($.dirname(n),c),i=ae.lookupPath(n,{recurse_count:t.recurse_count+1}).node,a++>40)throw new ae.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(ae.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?"".concat(r,"/").concat(t):r+t:r}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i)|0;return(e+r>>>0)%ae.nameTable.length},hashAddNode:e=>{var t=ae.hashName(e.parent.id,e.name);e.name_next=ae.nameTable[t],ae.nameTable[t]=e},hashRemoveNode:e=>{var t=ae.hashName(e.parent.id,e.name);if(ae.nameTable[t]===e)ae.nameTable[t]=e.name_next;else for(var r=ae.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=ae.mayLookup(e);if(r)throw new ae.ErrnoError(r,e);for(var i=ae.hashName(e.id,t),n=ae.nameTable[i];n;n=n.name_next){var o=n.name;if(n.parent.id===e.id&&o===t)return n}return ae.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new ae.FSNode(e,t,r,i);return ae.hashAddNode(n),n},destroyNode:e=>{ae.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)=>ae.ignorePermissions?0:t.includes("r")&&!(292&e.mode)||t.includes("w")&&!(146&e.mode)||t.includes("x")&&!(73&e.mode)?2:0,mayLookup:e=>ae.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{ae.lookupNode(e,t);return 20}catch(r){}return ae.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=ae.lookupNode(e,t)}catch(o){return o.errno}var n=ae.nodePermissions(e,"wx");if(n)return n;if(r){if(!ae.isDir(i.mode))return 54;if(ae.isRoot(i)||ae.getPath(i)===ae.cwd())return 10}else if(ae.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?ae.isLink(e.mode)?32:ae.isDir(e.mode)&&("r"!==ae.flagsToPermissionString(t)||512&t)?31:ae.nodePermissions(e,ae.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=ae.MAX_OPEN_FDS;e++)if(!ae.streams[e])return e;throw new ae.ErrnoError(33)},getStreamChecked:e=>{var t=ae.getStream(e);if(!t)throw new ae.ErrnoError(8);return t},getStream:e=>ae.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ae.FSStream||(ae.FSStream=function(){this.shared={}},ae.FSStream.prototype={},Object.defineProperties(ae.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 ae.FSStream,e),-1==t&&(t=ae.nextfd()),e.fd=t,ae.streams[t]=e,e},closeStream:e=>{ae.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=ae.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new ae.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{ae.devices[e]={stream_ops:t}},getDevice:e=>ae.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),ae.syncFSRequests++,ae.syncFSRequests>1&&f("warning: ".concat(ae.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var r=ae.getMounts(ae.root.mount),i=0;function n(e){return ae.syncFSRequests--,t(e)}function o(e){if(e)return o.errored?void 0:(o.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return o(null);t.type.syncfs(t,e,o)}))},mount:(e,t,r)=>{var i,n="/"===r,o=!r;if(n&&ae.root)throw new ae.ErrnoError(10);if(!n&&!o){var s=ae.lookupPath(r,{follow_mount:!1});if(r=s.path,i=s.node,ae.isMountpoint(i))throw new ae.ErrnoError(10);if(!ae.isDir(i.mode))throw new ae.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?ae.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=ae.lookupPath(e,{follow_mount:!1});if(!ae.isMountpoint(t.node))throw new ae.ErrnoError(28);var r=t.node,i=r.mounted,n=ae.getMounts(i);Object.keys(ae.nameTable).forEach((e=>{for(var t=ae.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&ae.destroyNode(t),t=r}})),r.mounted=null;var o=r.mount.mounts.indexOf(i);r.mount.mounts.splice(o,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=ae.lookupPath(e,{parent:!0}).node,n=$.basename(e);if(!n||"."===n||".."===n)throw new ae.ErrnoError(28);var o=ae.mayCreate(i,n);if(o)throw new ae.ErrnoError(o);if(!i.node_ops.mknod)throw new ae.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,ae.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,ae.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n<r.length;++n)if(r[n]){i+="/"+r[n];try{ae.mkdir(i,t)}catch(o){if(20!=o.errno)throw o}}},mkdev:(e,t,r)=>(void 0===r&&(r=t,t=438),t|=8192,ae.mknod(e,t,r)),symlink:(e,t)=>{if(!q.resolve(e))throw new ae.ErrnoError(44);var r=ae.lookupPath(t,{parent:!0}).node;if(!r)throw new ae.ErrnoError(44);var i=$.basename(t),n=ae.mayCreate(r,i);if(n)throw new ae.ErrnoError(n);if(!r.node_ops.symlink)throw new ae.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=$.dirname(e),o=$.dirname(t),s=$.basename(e),a=$.basename(t);if(r=ae.lookupPath(e,{parent:!0}).node,i=ae.lookupPath(t,{parent:!0}).node,!r||!i)throw new ae.ErrnoError(44);if(r.mount!==i.mount)throw new ae.ErrnoError(75);var c,l=ae.lookupNode(r,s),d=q.relative(e,o);if("."!==d.charAt(0))throw new ae.ErrnoError(28);if("."!==(d=q.relative(t,n)).charAt(0))throw new ae.ErrnoError(55);try{c=ae.lookupNode(i,a)}catch(p){}if(l!==c){var u=ae.isDir(l.mode),h=ae.mayDelete(r,s,u);if(h)throw new ae.ErrnoError(h);if(h=c?ae.mayDelete(i,a,u):ae.mayCreate(i,a))throw new ae.ErrnoError(h);if(!r.node_ops.rename)throw new ae.ErrnoError(63);if(ae.isMountpoint(l)||c&&ae.isMountpoint(c))throw new ae.ErrnoError(10);if(i!==r&&(h=ae.nodePermissions(r,"w")))throw new ae.ErrnoError(h);ae.hashRemoveNode(l);try{r.node_ops.rename(l,i,a)}catch(p){throw p}finally{ae.hashAddNode(l)}}},rmdir:e=>{var t=ae.lookupPath(e,{parent:!0}).node,r=$.basename(e),i=ae.lookupNode(t,r),n=ae.mayDelete(t,r,!0);if(n)throw new ae.ErrnoError(n);if(!t.node_ops.rmdir)throw new ae.ErrnoError(63);if(ae.isMountpoint(i))throw new ae.ErrnoError(10);t.node_ops.rmdir(t,r),ae.destroyNode(i)},readdir:e=>{var t=ae.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new ae.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=ae.lookupPath(e,{parent:!0}).node;if(!t)throw new ae.ErrnoError(44);var r=$.basename(e),i=ae.lookupNode(t,r),n=ae.mayDelete(t,r,!1);if(n)throw new ae.ErrnoError(n);if(!t.node_ops.unlink)throw new ae.ErrnoError(63);if(ae.isMountpoint(i))throw new ae.ErrnoError(10);t.node_ops.unlink(t,r),ae.destroyNode(i)},readlink:e=>{var t=ae.lookupPath(e).node;if(!t)throw new ae.ErrnoError(44);if(!t.node_ops.readlink)throw new ae.ErrnoError(28);return q.resolve(ae.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=ae.lookupPath(e,{follow:!t}).node;if(!r)throw new ae.ErrnoError(44);if(!r.node_ops.getattr)throw new ae.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>ae.stat(e,!0),chmod:(e,t,r)=>{var i;"string"==typeof e?i=ae.lookupPath(e,{follow:!r}).node:i=e;if(!i.node_ops.setattr)throw new ae.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{ae.chmod(e,t,!0)},fchmod:(e,t)=>{var r=ae.getStreamChecked(e);ae.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;"string"==typeof e?n=ae.lookupPath(e,{follow:!i}).node:n=e;if(!n.node_ops.setattr)throw new ae.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{ae.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=ae.getStreamChecked(e);ae.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new ae.ErrnoError(28);var r;"string"==typeof e?r=ae.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new ae.ErrnoError(63);if(ae.isDir(r.mode))throw new ae.ErrnoError(31);if(!ae.isFile(r.mode))throw new ae.ErrnoError(28);var i=ae.nodePermissions(r,"w");if(i)throw new ae.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=ae.getStreamChecked(e);if(!(2097155&r.flags))throw new ae.ErrnoError(28);ae.truncate(r.node,t)},utime:(e,t,r)=>{var i=ae.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(e,t,r)=>{if(""===e)throw new ae.ErrnoError(44);var i;if(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,r=void 0===r?438:r,r=64&t?4095&r|32768:0,"object"==typeof e)i=e;else{e=$.normalize(e);try{i=ae.lookupPath(e,{follow:!(131072&t)}).node}catch(c){}}var o=!1;if(64&t)if(i){if(128&t)throw new ae.ErrnoError(20)}else i=ae.mknod(e,r,0),o=!0;if(!i)throw new ae.ErrnoError(44);if(ae.isChrdev(i.mode)&&(t&=-513),65536&t&&!ae.isDir(i.mode))throw new ae.ErrnoError(54);if(!o){var s=ae.mayOpen(i,t);if(s)throw new ae.ErrnoError(s)}512&t&&!o&&ae.truncate(i,0),t&=-131713;var a=ae.createStream({node:i,path:ae.getPath(i),flags:t,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),n.logReadFiles&&!(1&t)&&(ae.readFiles||(ae.readFiles={}),e in ae.readFiles||(ae.readFiles[e]=1)),a},close:e=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{ae.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new ae.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new ae.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(i<0||n<0)throw new ae.ErrnoError(28);if(ae.isClosed(e))throw new ae.ErrnoError(8);if(1==(2097155&e.flags))throw new ae.ErrnoError(8);if(ae.isDir(e.node.mode))throw new ae.ErrnoError(31);if(!e.stream_ops.read)throw new ae.ErrnoError(28);var o=void 0!==n;if(o){if(!e.seekable)throw new ae.ErrnoError(70)}else n=e.position;var s=e.stream_ops.read(e,t,r,i,n);return o||(e.position+=s),s},write:(e,t,r,i,n,o)=>{if(i<0||n<0)throw new ae.ErrnoError(28);if(ae.isClosed(e))throw new ae.ErrnoError(8);if(!(2097155&e.flags))throw new ae.ErrnoError(8);if(ae.isDir(e.node.mode))throw new ae.ErrnoError(31);if(!e.stream_ops.write)throw new ae.ErrnoError(28);e.seekable&&1024&e.flags&&ae.llseek(e,0,2);var s=void 0!==n;if(s){if(!e.seekable)throw new ae.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,o);return s||(e.position+=a),a},allocate:(e,t,r)=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);if(t<0||r<=0)throw new ae.ErrnoError(28);if(!(2097155&e.flags))throw new ae.ErrnoError(8);if(!ae.isFile(e.node.mode)&&!ae.isDir(e.node.mode))throw new ae.ErrnoError(43);if(!e.stream_ops.allocate)throw new ae.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new ae.ErrnoError(2);if(1==(2097155&e.flags))throw new ae.ErrnoError(2);if(!e.stream_ops.mmap)throw new ae.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0,munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new ae.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'.concat(t.encoding,'"'));var r,i=ae.open(e,t.flags),n=ae.stat(e).size,o=new Uint8Array(n);return ae.read(i,o,0,n,0),"utf8"===t.encoding?r=Y(o,0):"binary"===t.encoding&&(r=o),ae.close(i),r},writeFile:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.flags=r.flags||577;var i=ae.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(Q(t)+1),o=Z(t,n,0,n.length);ae.write(i,n,0,o,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ae.write(i,t,0,t.byteLength,void 0,r.canOwn)}ae.close(i)},cwd:()=>ae.currentPath,chdir:e=>{var t=ae.lookupPath(e,{follow:!0});if(null===t.node)throw new ae.ErrnoError(44);if(!ae.isDir(t.node.mode))throw new ae.ErrnoError(54);var r=ae.nodePermissions(t.node,"x");if(r)throw new ae.ErrnoError(r);ae.currentPath=t.path},createDefaultDirectories:()=>{ae.mkdir("/tmp"),ae.mkdir("/home"),ae.mkdir("/home/web_user")},createDefaultDevices:()=>{ae.mkdir("/dev"),ae.registerDevice(ae.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),ae.mkdev("/dev/null",ae.makedev(1,3)),te.register(ae.makedev(5,0),te.default_tty_ops),te.register(ae.makedev(6,0),te.default_tty1_ops),ae.mkdev("/dev/tty",ae.makedev(5,0)),ae.mkdev("/dev/tty1",ae.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=J(e).byteLength),e[--t]);ae.createDevice("/dev","random",r),ae.createDevice("/dev","urandom",r),ae.mkdir("/dev/shm"),ae.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{ae.mkdir("/proc");var e=ae.mkdir("/proc/self");ae.mkdir("/proc/self/fd"),ae.mount({mount:()=>{var t=ae.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=ae.getStreamChecked(r),n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{n.stdin?ae.createDevice("/dev","stdin",n.stdin):ae.symlink("/dev/tty","/dev/stdin"),n.stdout?ae.createDevice("/dev","stdout",null,n.stdout):ae.symlink("/dev/tty","/dev/stdout"),n.stderr?ae.createDevice("/dev","stderr",null,n.stderr):ae.symlink("/dev/tty1","/dev/stderr"),ae.open("/dev/stdin",0),ae.open("/dev/stdout",1),ae.open("/dev/stderr",1)},ensureErrnoError:()=>{ae.ErrnoError||(ae.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ae.ErrnoError.prototype=new Error,ae.ErrnoError.prototype.constructor=ae.ErrnoError,[44].forEach((e=>{ae.genericErrors[e]=new ae.ErrnoError(e),ae.genericErrors[e].stack="<generic error, no stack>"})))},staticInit:()=>{ae.ensureErrnoError(),ae.nameTable=new Array(4096),ae.mount(ie,{},"/"),ae.createDefaultDirectories(),ae.createDefaultDevices(),ae.createSpecialDirectories(),ae.filesystems={MEMFS:ie}},init:(e,t,r)=>{ae.init.initialized=!0,ae.ensureErrnoError(),n.stdin=e||n.stdin,n.stdout=t||n.stdout,n.stderr=r||n.stderr,ae.createStandardStreams()},quit:()=>{ae.init.initialized=!1;for(var e=0;e<ae.streams.length;e++){var t=ae.streams[e];!t||ae.close(t)}},findObject:(e,t)=>{var r=ae.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=ae.lookupPath(e,{follow:!t})).path}catch(n){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=ae.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=$.basename(e),i=ae.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(n){r.error=n.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:ae.getPath(e);for(var n=t.split("/").reverse();n.length;){var o=n.pop();if(o){var s=$.join2(e,o);try{ae.mkdir(s)}catch(a){}e=s}}return s},createFile:(e,t,r,i,n)=>{var o=$.join2("string"==typeof e?e:ae.getPath(e),t),s=se(i,n);return ae.create(o,s)},createDataFile:(e,t,r,i,n,o)=>{var s=t;e&&(e="string"==typeof e?e:ae.getPath(e),s=t?$.join2(e,t):e);var a=se(i,n),c=ae.create(s,a);if(r){if("string"==typeof r){for(var l=new Array(r.length),d=0,u=r.length;d<u;++d)l[d]=r.charCodeAt(d);r=l}ae.chmod(c,146|a);var h=ae.open(c,577);ae.write(h,r,0,r.length,0,o),ae.close(h),ae.chmod(c,a)}return c},createDevice:(e,t,r,i)=>{var n=$.join2("string"==typeof e?e:ae.getPath(e),t),o=se(!!r,!!i);ae.createDevice.major||(ae.createDevice.major=64);var s=ae.makedev(ae.createDevice.major++,0);return ae.registerDevice(s,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,o)=>{for(var s=0,a=0;a<n;a++){var c;try{c=r()}catch(l){throw new ae.ErrnoError(29)}if(void 0===c&&0===s)throw new ae.ErrnoError(6);if(null==c)break;s++,t[i+a]=c}return s&&(e.node.timestamp=Date.now()),s},write:(e,t,r,n,o)=>{for(var s=0;s<n;s++)try{i(t[r+s])}catch(a){throw new ae.ErrnoError(29)}return n&&(e.node.timestamp=Date.now()),s}}),ae.mkdev(n,o,s)},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(!l)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=ee(l(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new ae.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function o(){this.lengthKnown=!1,this.chunks=[]}if(o.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},o.prototype.setDataGetter=function(e){this.getter=e},o.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,o=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;n||(s=i);var a=this;a.setDataGetter((e=>{var t=e*s,n=(e+1)*s-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==s&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):ee(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),(o||!i)&&(s=i=1,i=this.getter(0).length,s=i,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!c)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new o;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:s}}else a={isDevice:!1,url:r};var l=ae.createFile(e,t,a,i,n);a.contents?l.contents=a.contents:a.url&&(l.contents=null,l.url=a.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var d={};function u(e,t,r,i,n){var o=e.node.contents;if(n>=o.length)return 0;var s=Math.min(o.length-n,i);if(o.slice)for(var a=0;a<s;a++)t[r+a]=o[n+a];else for(a=0;a<s;a++)t[r+a]=o.get(n+a);return s}return Object.keys(l.stream_ops).forEach((e=>{var t=l.stream_ops[e];d[e]=function(){return ae.forceLoadFile(l),t.apply(null,arguments)}})),d.read=(e,t,r,i,n)=>(ae.forceLoadFile(l),u(e,t,r,i,n)),d.mmap=(e,t,r,i,n)=>{ae.forceLoadFile(l);var o=re();if(!o)throw new ae.ErrnoError(48);return u(e,v,o,t,r),{ptr:o,allocated:!0}},l.stream_ops=d,l}},ce=(e,t)=>e?Y(y,e,t):"",le={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if($.isAbs(t))return t;var i;-100===e?i=ae.cwd():i=le.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new ae.ErrnoError(44);return i}return $.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(a){if(a&&a.node&&$.normalize(t)!==$.normalize(ae.getPath(a.node)))return-54;throw a}S[r>>2]=i.dev,S[r+4>>2]=i.mode,I[r+8>>2]=i.nlink,S[r+12>>2]=i.uid,S[r+16>>2]=i.gid,S[r+20>>2]=i.rdev,W=[i.size>>>0,(H=i.size,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+24>>2]=W[0],S[r+28>>2]=W[1],S[r+32>>2]=4096,S[r+36>>2]=i.blocks;var n=i.atime.getTime(),o=i.mtime.getTime(),s=i.ctime.getTime();return W=[Math.floor(n/1e3)>>>0,(H=Math.floor(n/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+40>>2]=W[0],S[r+44>>2]=W[1],I[r+48>>2]=n%1e3*1e3,W=[Math.floor(o/1e3)>>>0,(H=Math.floor(o/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+56>>2]=W[0],S[r+60>>2]=W[1],I[r+64>>2]=o%1e3*1e3,W=[Math.floor(s/1e3)>>>0,(H=Math.floor(s/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+72>>2]=W[0],S[r+76>>2]=W[1],I[r+80>>2]=s%1e3*1e3,W=[i.ino>>>0,(H=i.ino,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+88>>2]=W[0],S[r+92>>2]=W[1],0},doMsync:function(e,t,r,i,n){if(!ae.isFile(t.node.mode))throw new ae.ErrnoError(43);if(2&i)return 0;var o=y.slice(e,e+r);ae.msync(t,o,n,r,i)},varargs:void 0,get:()=>(le.varargs+=4,S[le.varargs-4>>2]),getStr:e=>ce(e),getStreamFromFD:function(e){return ae.getStreamChecked(e)}};function de(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 ue=void 0;function he(e){for(var t="",r=e;y[r];)t+=ue[y[r++]];return t}var pe={},me={},fe={},_e=void 0;function ge(e){throw new _e(e)}var ve=void 0;function ye(e){throw new ve(e)}function Ee(e,t,r){function i(t){var i=r(t);i.length!==e.length&&ye("Mismatched type converter count");for(var n=0;n<e.length;++n)Te(e[n],i[n])}e.forEach((function(e){fe[e]=t}));var n=new Array(t.length),o=[],s=0;t.forEach(((e,t)=>{me.hasOwnProperty(e)?n[t]=me[e]:(o.push(e),pe.hasOwnProperty(e)||(pe[e]=[]),pe[e].push((()=>{n[t]=me[e],++s===o.length&&i(n)})))})),0===o.length&&i(n)}function Te(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i=t.name;if(e||ge('type "'.concat(i,'" must have a positive integer typeid pointer')),me.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;ge("Cannot register type '".concat(i,"' twice"))}if(me[e]=t,delete fe[e],pe.hasOwnProperty(e)){var n=pe[e];delete pe[e],n.forEach((e=>e()))}}(e,t,r)}function Se(e){if(!(this instanceof ze&&e instanceof ze))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n}function Ie(e){return{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}}function Ae(e){ge(e.$$.ptrType.registeredClass.name+" instance already deleted")}var Ce=!1;function be(e){}function Re(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function we(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=we(e,t,r.baseClass);return null===i?null:r.downcast(i)}var ke={};function De(){return Object.keys(xe).length}function Pe(){var e=[];for(var t in xe)xe.hasOwnProperty(t)&&e.push(xe[t]);return e}var Ne=[];function Oe(){for(;Ne.length;){var e=Ne.pop();e.$$.deleteScheduled=!1,e.delete()}}var Me=void 0;function Le(e){Me=e,Ne.length&&Me&&Me(Oe)}var xe={};function Ve(e,t){return t=function(e,t){for(void 0===t&&ge("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),xe[t]}function Ue(e,t){return(!t.ptrType||!t.ptr)&&ye("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!==!!t.smartPtr&&ye("Both smartPtrType and smartPtr must be specified"),t.count={value:1},Be(Object.create(e,{$$:{value:t}}))}function Fe(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=Ve(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?Ue(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):Ue(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var o,s=this.registeredClass.getActualType(t),a=ke[s];if(!a)return n.call(this);o=this.isConst?a.constPointerType:a.pointerType;var c=we(t,this.registeredClass,o.registeredClass);return null===c?n.call(this):this.isSmartPointer?Ue(o.registeredClass.instancePrototype,{ptrType:o,ptr:c,smartPtrType:this,smartPtr:e}):Ue(o.registeredClass.instancePrototype,{ptrType:o,ptr:c})}var Be=function(e){return"undefined"==typeof FinalizationRegistry?(Be=e=>e,e):(Ce=new FinalizationRegistry((e=>{Re(e.$$)})),be=e=>Ce.unregister(e),(Be=e=>{var t=e.$$;if(!!t.smartPtr){var r={$$:t};Ce.register(e,r,e)}return e})(e))};function je(){if(this.$$.ptr||Ae(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e=Be(Object.create(Object.getPrototypeOf(this),{$$:{value:Ie(this.$$)}}));return e.$$.count.value+=1,e.$$.deleteScheduled=!1,e}function He(){this.$$.ptr||Ae(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ge("Object already scheduled for deletion"),be(this),Re(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function We(){return!this.$$.ptr}function Ge(){return this.$$.ptr||Ae(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ge("Object already scheduled for deletion"),Ne.push(this),1===Ne.length&&Me&&Me(Oe),this.$$.deleteScheduled=!0,this}function ze(){}var $e=48,Je=57;function qe(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=$e&&t<=Je?"_".concat(e):e}function Ke(e,t){return e=qe(e),{[e]:function(){return t.apply(this,arguments)}}[e]}function Ye(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||ge("Function '".concat(r,"' called with an invalid number of arguments (").concat(arguments.length,") - expects one of (").concat(e[t].overloadTable,")!")),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function Xe(e,t,r,i,n,o,s,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=o,this.upcast=s,this.downcast=a,this.pureVirtualFunctions=[]}function Qe(e,t,r){for(;t!==r;)t.upcast||ge("Expected null or instance of ".concat(r.name,", got an instance of ").concat(t.name)),e=t.upcast(e),t=t.baseClass;return e}function Ze(e,t){if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name));var r=t.$$.ptrType.registeredClass;return Qe(t.$$.ptr,r,this.registeredClass)}function et(e,t){var r;if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name)),!this.isConst&&t.$$.ptrType.isConst&&ge("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));var i=t.$$.ptrType.registeredClass;if(r=Qe(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&ge("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:ge("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,It.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:ge("Unsupporting sharing policy")}return r}function tt(e,t){if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name)),t.$$.ptrType.isConst&&ge("Cannot convert argument of type ".concat(t.$$.ptrType.name," to parameter type ").concat(this.name));var r=t.$$.ptrType.registeredClass;return Qe(t.$$.ptr,r,this.registeredClass)}function rt(e){return this.fromWireType(S[e>>2])}function it(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e}function nt(e){this.rawDestructor&&this.rawDestructor(e)}function ot(e){null!==e&&e.delete()}function st(e,t,r,i,n,o,s,a,c,l,d){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=o,this.sharingPolicy=s,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=l,this.rawDestructor=d,n||void 0!==t.baseClass?this.toWireType=et:i?(this.toWireType=Ze,this.destructorFunction=null):(this.toWireType=tt,this.destructorFunction=null)}var at=[],ct=e=>{var t=at[e];return t||(e>=at.length&&(at.length=e+1),at[e]=t=R.get(e)),t},lt=(e,t,r)=>e.includes("j")?((e,t,r)=>{var i=n["dynCall_"+e];return r&&r.length?i.apply(null,[t].concat(r)):i.call(null,t)})(e,t,r):ct(t).apply(null,r),dt=(e,t)=>{var r=[];return function(){return r.length=0,Object.assign(r,arguments),lt(e,t,r)}};function ut(e,t){var r=(e=he(e)).includes("j")?dt(e,t):ct(t);return"function"!=typeof r&&ge("unknown function pointer with signature ".concat(e,": ").concat(t)),r}var ht=void 0;function pt(e){var t=Jt(e),r=he(t);return zt(t),r}function mt(e,t){var r=[],i={};throw t.forEach((function e(t){if(!i[t]&&!me[t]){if(fe[t])return void fe[t].forEach(e);r.push(t),i[t]=!0}})),new ht("".concat(e,": ")+r.map(pt).join([", "]))}function ft(e,t){for(var r=[],i=0;i<e;i++)r.push(I[t+4*i>>2]);return r}function _t(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function gt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type ".concat(typeof e," which is not a function"));var r=Ke(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function vt(e,t,r,i,n,o){var s=t.length;s<2&&ge("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var a=null!==t[1]&&null!==r,c=!1,l=1;l<t.length;++l)if(null!==t[l]&&void 0===t[l].destructorFunction){c=!0;break}var d="void"!==t[0].name,u="",h="";for(l=0;l<s-2;++l)u+=(0!==l?", ":"")+"arg"+l,h+=(0!==l?", ":"")+"arg"+l+"Wired";var p="\n return function ".concat(qe(e),"(").concat(u,") {\n if (arguments.length !== ").concat(s-2,") {\n throwBindingError('function ").concat(e," called with ").concat(arguments.length," arguments, expected ").concat(s-2," args!');\n }");c&&(p+="var destructors = [];\n");var m=c?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[ge,i,n,_t,t[0],t[1]];a&&(p+="var thisWired = classParam.toWireType("+m+", this);\n");for(l=0;l<s-2;++l)p+="var arg"+l+"Wired = argType"+l+".toWireType("+m+", arg"+l+"); // "+t[l+2].name+"\n",f.push("argType"+l),_.push(t[l+2]);if(a&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||o?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",c)p+="runDestructors(destructors);\n";else for(l=a?1:2;l<t.length;++l){var g=1===l?"thisWired":"arg"+(l-2)+"Wired";null!==t[l].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[l].name+"\n",f.push(g+"_dtor"),_.push(t[l].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),gt(Function,f).apply(null,_)}function yt(){this.allocated=[void 0],this.freelist=[]}var Et=new yt;function Tt(e){e>=Et.reserved&&0==--Et.get(e).refcount&&Et.free(e)}function St(){for(var e=0,t=Et.reserved;t<Et.allocated.length;++t)void 0!==Et.allocated[t]&&++e;return e}var It={toValue:e=>(e||ge("Cannot use deleted val. handle = "+e),Et.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 Et.allocate({refcount:1,value:e})}}};function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function Ct(e,t){switch(t){case 2:return function(e){return this.fromWireType(A[e>>2])};case 3:return function(e){return this.fromWireType(C[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function bt(e,t,r){switch(t){case 0:return r?function(e){return v[e]}:function(e){return y[e]};case 1:return r?function(e){return E[e>>1]}:function(e){return T[e>>1]};case 2:return r?function(e){return S[e>>2]}:function(e){return I[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Rt="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,wt=(e,t)=>{for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&T[i];)++i;if((r=i<<1)-e>32&&Rt)return Rt.decode(y.subarray(e,r));for(var o="",s=0;!(s>=t/2);++s){var a=E[e+2*s>>1];if(0==a)break;o+=String.fromCharCode(a)}return o},kt=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,o=0;o<n;++o){var s=e.charCodeAt(o);E[t>>1]=s,t+=2}return E[t>>1]=0,t-i},Dt=e=>2*e.length,Pt=(e,t)=>{for(var r=0,i="";!(r>=t/4);){var n=S[e+4*r>>2];if(0==n)break;if(++r,n>=65536){var o=n-65536;i+=String.fromCharCode(55296|o>>10,56320|1023&o)}else i+=String.fromCharCode(n)}return i},Nt=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t,n=i+r-4,o=0;o<e.length;++o){var s=e.charCodeAt(o);if(s>=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o);if(S[t>>2]=s,(t+=4)+4>n)break}return S[t>>2]=0,t-i},Ot=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i>=55296&&i<=57343&&++r,t+=4}return t};var Mt={};var Lt=[];function xt(e,t){var r=me[e];return void 0===r&&ge(t+" has unknown type "+pt(e)),r}var Vt=[];var Ut={},Ft=()=>{if(!Ft.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",_:s||"./this.program"};for(var t in Ut)void 0===Ut[t]?delete e[t]:e[t]=Ut[t];var r=[];for(var t in e)r.push("".concat(t,"=").concat(e[t]));Ft.strings=r}return Ft.strings};var Bt=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=ae.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i},jt=365,Ht=146;Object.defineProperties(Bt.prototype,{read:{get:function(){return(this.mode&jt)===jt},set:function(e){e?this.mode|=jt:this.mode&=~jt}},write:{get:function(){return(this.mode&Ht)===Ht},set:function(e){e?this.mode|=Ht:this.mode&=~Ht}},isFolder:{get:function(){return ae.isDir(this.mode)}},isDevice:{get:function(){return ae.isChrdev(this.mode)}}}),ae.FSNode=Bt,ae.createPreloadedFile=function(e,t,r,i,n,o,s,a,c,l){var d=t?q.resolve($.join2(e,t)):e;function u(r){function u(r){l&&l(),a||ae.createDataFile(e,t,r,i,n,c),o&&o(),M()}(function(e,t,r,i){"undefined"!=typeof Browser&&Browser.init();var n=!1;return oe.forEach((function(o){n||o.canHandle(t)&&(o.handle(e,t,r,i),n=!0)})),n})(r,d,u,(()=>{s&&s(),M()}))||u(r)}O(),"string"==typeof r?ne(r,(e=>u(e)),s):u(r)},ae.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);ue=e}(),_e=n.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},ve=n.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},ze.prototype.isAliasOf=Se,ze.prototype.clone=je,ze.prototype.delete=He,ze.prototype.isDeleted=We,ze.prototype.deleteLater=Ge,n.getInheritedInstanceCount=De,n.getLiveInheritedInstances=Pe,n.flushPendingDeletes=Oe,n.setDelayFunction=Le,st.prototype.getPointee=it,st.prototype.destructor=nt,st.prototype.argPackAdvance=8,st.prototype.readValueFromPointer=rt,st.prototype.deleteObject=ot,st.prototype.fromWireType=Fe,ht=n.UnboundTypeError=function(e,t){var r=Ke(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:"".concat(this.name,": ").concat(this.message)},r}(Error,"UnboundTypeError"),Object.assign(yt.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)}}),Et.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Et.reserved=Et.allocated.length,n.count_emval_handles=St;var Wt={p:function(e,t,r){throw new z(e).init(t,r),e},C:function(e,t,r){le.varargs=r;try{var i=le.getStreamFromFD(e);switch(t){case 0:return(n=le.get())<0?-28:ae.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=le.get();return i.flags|=n,0;case 5:n=le.get();return E[n+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return(e=>{S[$t()>>2]=e})(28),-1}}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return-o.errno}},w:function(e,t,r,i){le.varargs=i;try{t=le.getStr(t),t=le.calculateAt(e,t);var n=i?le.get():0;return ae.open(t,r,n).fd}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return-o.errno}},t:function(e,t,r,i,n){},n:function(e,t,r,i,n){var o=de(r);Te(e,{name:t=he(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=v;else if(2===r)i=E;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=S}return this.fromWireType(i[e>>o])},destructorFunction:null})},r:function(e,t,r,i,o,s,a,c,l,d,u,h,p){u=he(u),s=ut(o,s),c&&(c=ut(a,c)),d&&(d=ut(l,d)),p=ut(h,p);var m=qe(u);(function(e,t,r){n.hasOwnProperty(e)?((void 0===r||void 0!==n[e].overloadTable&&void 0!==n[e].overloadTable[r])&&ge("Cannot register public name '".concat(e,"' twice")),Ye(n,e,e),n.hasOwnProperty(r)&&ge("Cannot register multiple overloads of a function with the same number of arguments (".concat(r,")!")),n[e].overloadTable[r]=t):(n[e]=t,void 0!==r&&(n[e].numArguments=r))})(m,(function(){mt("Cannot construct ".concat(u," due to unbound types"),[i])})),Ee([e,t,r],i?[i]:[],(function(t){var r,o;t=t[0],i?o=(r=t.registeredClass).instancePrototype:o=ze.prototype;var a=Ke(m,(function(){if(Object.getPrototypeOf(this)!==l)throw new _e("Use 'new' to construct "+u);if(void 0===h.constructor_body)throw new _e(u+" has no accessible constructor");var e=h.constructor_body[arguments.length];if(void 0===e)throw new _e("Tried to invoke ctor of ".concat(u," with invalid number of parameters (").concat(arguments.length,") - expected (").concat(Object.keys(h.constructor_body).toString(),") parameters instead!"));return e.apply(this,arguments)})),l=Object.create(o,{constructor:{value:a}});a.prototype=l;var h=new Xe(u,a,l,p,r,s,c,d);h.baseClass&&(void 0===h.baseClass.__derivedClasses&&(h.baseClass.__derivedClasses=[]),h.baseClass.__derivedClasses.push(h));var f=new st(u,h,!0,!1,!1),_=new st(u+"*",h,!1,!1,!1),g=new st(u+" const*",h,!1,!0,!1);return ke[e]={pointerType:_,constPointerType:g},function(e,t,r){n.hasOwnProperty(e)||ye("Replacing nonexistant public symbol"),void 0!==n[e].overloadTable&&void 0!==r?n[e].overloadTable[r]=t:(n[e]=t,n[e].argCount=r)}(m,a),[f,_,g]}))},q:function(e,t,r,i,n,o){var s=ft(t,r);n=ut(i,n),Ee([],[e],(function(e){e=e[0];var r="constructor ".concat(e.name);if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new _e("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]=()=>{mt("Cannot construct ".concat(e.name," due to unbound types"),s)},Ee([],s,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=vt(r,i,null,n,o),[]})),[]}))},d:function(e,t,r,i,n,o,s,a,c){var l=ft(r,i);t=he(t),o=ut(n,o),Ee([],[e],(function(e){e=e[0];var i="".concat(e.name,".").concat(t);function n(){mt("Cannot call ".concat(i," due to unbound types"),l)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var d=e.registeredClass.instancePrototype,u=d[t];return void 0===u||void 0===u.overloadTable&&u.className!==e.name&&u.argCount===r-2?(n.argCount=r-2,n.className=e.name,d[t]=n):(Ye(d,t,i),d[t].overloadTable[r-2]=n),Ee([],l,(function(n){var a=vt(i,n,e,o,s,c);return void 0===d[t].overloadTable?(a.argCount=r-2,d[t]=a):d[t].overloadTable[r-2]=a,[]})),[]}))},D:function(e,t){Te(e,{name:t=he(t),fromWireType:function(e){var t=It.toValue(e);return Tt(e),t},toWireType:function(e,t){return It.toHandle(t)},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:null})},k:function(e,t,r){var i=de(r);Te(e,{name:t=he(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:Ct(t,i),destructorFunction:null})},c:function(e,t,r,i,n){t=he(t);var o=de(r),s=e=>e;if(0===i){var a=32-8*r;s=e=>e<<a>>>a}var c,l=t.includes("unsigned");c=l?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},Te(e,{name:t,fromWireType:s,toWireType:c,argPackAdvance:8,readValueFromPointer:bt(t,o,0!==i),destructorFunction:null})},b:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=I,r=t[e>>=2],n=t[e+1];return new i(t.buffer,n,r)}Te(e,{name:r=he(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var r="std::string"===(t=he(t));Te(e,{name:t,fromWireType:function(e){var t,i=I[e>>2],n=e+4;if(r)for(var o=n,s=0;s<=i;++s){var a=n+s;if(s==i||0==y[a]){var c=ce(o,a-o);void 0===t?t=c:(t+=String.fromCharCode(0),t+=c),o=a+1}}else{var l=new Array(i);for(s=0;s<i;++s)l[s]=String.fromCharCode(y[n+s]);t=l.join("")}return zt(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i,n="string"==typeof t;n||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||ge("Cannot pass non-string to std::string"),i=r&&n?Q(t):t.length;var o=Gt(4+i+1),s=o+4;if(I[o>>2]=i,r&&n)((e,t,r)=>{Z(e,y,t,r)})(t,s,i+1);else if(n)for(var a=0;a<i;++a){var c=t.charCodeAt(a);c>255&&(zt(s),ge("String has UTF-16 code units that do not fit in 8 bits")),y[s+a]=c}else for(a=0;a<i;++a)y[s+a]=t[a];return null!==e&&e.push(zt,o),o},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:function(e){zt(e)}})},f:function(e,t,r){var i,n,o,s,a;r=he(r),2===t?(i=wt,n=kt,s=Dt,o=()=>T,a=1):4===t&&(i=Pt,n=Nt,s=Ot,o=()=>I,a=2),Te(e,{name:r,fromWireType:function(e){for(var r,n=I[e>>2],s=o(),c=e+4,l=0;l<=n;++l){var d=e+4+l*t;if(l==n||0==s[d>>a]){var u=i(c,d-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=d+t}}return zt(e),r},toWireType:function(e,i){"string"!=typeof i&&ge("Cannot pass non-string to C++ string type ".concat(r));var o=s(i),c=Gt(4+o+t);return I[c>>2]=o>>a,n(i,c+4,o+t),null!==e&&e.push(zt,c),c},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:function(e){zt(e)}})},o:function(e,t){Te(e,{isVoid:!0,name:t=he(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,r,i){e=Lt[e],t=It.toValue(t),r=function(e){var t=Mt[e];return void 0===t?he(e):t}(r),e(t,r,null,i)},m:Tt,l:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i<e;++i)r[i]=xt(I[t+4*i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",o=Vt[n];if(void 0!==o)return o;for(var s=["retType"],a=[i],c="",l=0;l<e-1;++l)c+=(0!==l?", ":"")+"arg"+l,s.push("argType"+l),a.push(r[1+l]);var d="return function "+qe("methodCaller_"+n)+"(handle, name, destructors, args) {\n",u=0;for(l=0;l<e-1;++l)d+=" var arg"+l+" = argType"+l+".readValueFromPointer(args"+(u?"+"+u:"")+");\n",u+=r[l+1].argPackAdvance;for(d+=" var rv = handle[name]("+c+");\n",l=0;l<e-1;++l)r[l+1].deleteObject&&(d+=" argType"+l+".deleteObject(arg"+l+");\n");return i.isVoid||(d+=" return retType.toWireType(destructors, rv);\n"),d+="};\n",s.push(d),o=function(e){var t=Lt.length;return Lt.push(e),t}(gt(Function,s).apply(null,a)),Vt[n]=o,o},a:()=>{L("")},e:function(){return Date.now()},v:()=>y.length,A:(e,t,r)=>y.copyWithin(e,t,t+r),u:e=>{y.length,L("OOM")},y:(e,t)=>{var r=0;return Ft().forEach((function(i,n){var o=t+r;I[e+4*n>>2]=o,((e,t)=>{for(var r=0;r<e.length;++r)v[0|t++]=e.charCodeAt(r);v[0|t]=0})(i,o),r+=i.length+1})),0},z:(e,t)=>{var r=Ft();I[e>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),I[t>>2]=i,0},i:function(e){try{var t=le.getStreamFromFD(e);return ae.close(t),0}catch(r){if(void 0===ae||"ErrnoError"!==r.name)throw r;return r.errno}},x:function(e,t){try{var r=le.getStreamFromFD(e),i=r.tty?2:ae.isDir(r.mode)?3:ae.isLink(r.mode)?7:4;return v[t|0]=i,E[t+2>>1]=0,W=[0,(H=0,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[t+8>>2]=W[0],S[t+12>>2]=W[1],W=[0,(H=0,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[t+16>>2]=W[0],S[t+20>>2]=W[1],0}catch(n){if(void 0===ae||"ErrnoError"!==n.name)throw n;return n.errno}},B:function(e,t,r,i){try{var n=((e,t,r,i)=>{for(var n=0,o=0;o<r;o++){var s=I[t>>2],a=I[t+4>>2];t+=8;var c=ae.read(e,v,s,a,i);if(c<0)return-1;if(n+=c,c<a)break;void 0!==i&&(i+=c)}return n})(le.getStreamFromFD(e),t,r);return I[i>>2]=n,0}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return o.errno}},s:function(e,t,r,i,n){var o=function(e,t){return t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN}(t,r);try{if(isNaN(o))return 61;var s=le.getStreamFromFD(e);return ae.llseek(s,o,i),W=[s.position>>>0,(H=s.position,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[n>>2]=W[0],S[n+4>>2]=W[1],s.getdents&&0===o&&0===i&&(s.getdents=null),0}catch(a){if(void 0===ae||"ErrnoError"!==a.name)throw a;return a.errno}},h:function(e,t,r,i){try{var n=((e,t,r,i)=>{for(var n=0,o=0;o<r;o++){var s=I[t>>2],a=I[t+4>>2];t+=8;var c=ae.write(e,v,s,a,i);if(c<0)return-1;n+=c,void 0!==i&&(i+=c)}return n})(le.getStreamFromFD(e),t,r);return I[i>>2]=n,0}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return o.errno}}};!function(){var e={a:Wt};function t(e,t){var r=e.exports;return _=(g=r).E,function(){var e=_.buffer;n.HEAP8=v=new Int8Array(e),n.HEAP16=E=new Int16Array(e),n.HEAP32=S=new Int32Array(e),n.HEAPU8=y=new Uint8Array(e),n.HEAPU16=T=new Uint16Array(e),n.HEAPU32=I=new Uint32Array(e),n.HEAPF32=A=new Float32Array(e),n.HEAPF64=C=new Float64Array(e)}(),R=g.H,function(e){k.unshift(e)}(g.F),M(),r}if(O(),n.instantiateWasm)try{return n.instantiateWasm(e,t)}catch(r){f("Module.instantiateWasm callback failed with error: "+r),i(r)}(function(e,t,r,i){return e||"function"!=typeof WebAssembly.instantiateStreaming||F(t)||"function"!=typeof fetch?j(t,r,i):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,r).then(i,(function(e){return f("wasm streaming compile failed: "+e),f("falling back to ArrayBuffer instantiation"),j(t,r,i)}))))})(p,x,e,(function(e){t(e.instance)})).catch(i)}();var Gt=e=>(Gt=g.G)(e),zt=e=>(zt=g.I)(e),$t=()=>($t=g.J)(),Jt=e=>(Jt=g.K)(e);n.__embind_initialize_bindings=()=>(n.__embind_initialize_bindings=g.L)();var qt,Kt=e=>(Kt=g.M)(e);function Yt(){function e(){qt||(qt=!0,n.calledRun=!0,!b&&(!n.noFSInit&&!ae.init.initialized&&ae.init(),ae.ignorePermissions=!1,G(k),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),function(){if(n.postRun)for("function"==typeof n.postRun&&(n.postRun=[n.postRun]);n.postRun.length;)e=n.postRun.shift(),D.unshift(e);var e;G(D)}()))}P>0||(function(){if(n.preRun)for("function"==typeof n.preRun&&(n.preRun=[n.preRun]);n.preRun.length;)e=n.preRun.shift(),w.unshift(e);var e;G(w)}(),P>0)||(n.setStatus?(n.setStatus("Running..."),setTimeout((function(){setTimeout((function(){n.setStatus("")}),1),e()}),1)):e())}if(n.dynCall_jiji=(e,t,r,i,o)=>(n.dynCall_jiji=g.N)(e,t,r,i,o),n._ff_h264_cabac_tables=67061,N=function e(){qt||Yt(),qt||(N=e)},n.preInit)for("function"==typeof n.preInit&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return Yt(),t.ready}})(),uU=dU,hU=class extends lU{constructor(e){super(uU,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)}},pU=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var r,i,n=t;n.ready=new Promise(((e,t)=>{r=e,i=t}));var o=Object.assign({},n),s="object"==typeof window,a="function"==typeof importScripts;"object"==typeof process&&"object"==typeof process.versions&&process.versions.node;var c,l="";(s||a)&&(a?l=self.location.href:"undefined"!=typeof document&&document.currentScript&&(l=document.currentScript.src),e&&(l=e),l=0!==l.indexOf("blob:")?l.substr(0,l.replace(/[?#].*/,"").lastIndexOf("/")+1):"",a&&(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}));var d,u=n.print||console.log.bind(console),h=n.printErr||console.error.bind(console);Object.assign(n,o),o=null,n.arguments&&n.arguments,n.thisProgram&&n.thisProgram,n.quit&&n.quit,n.wasmBinary&&(d=n.wasmBinary),n.noExitRuntime,"object"!=typeof WebAssembly&&D("no native wasm support detected");var p,m,f,_,g,v,y,E,T,S,I=!1;var A,C=[],b=[],R=[];var w=0,k=null;function D(e){n.onAbort&&n.onAbort(e),h(e="Aborted("+e+")"),I=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}var P,N,O="data:application/octet-stream;base64,";function M(e){return e.startsWith(O)}function L(e){if(e==P&&d)return new Uint8Array(d);if(c)return c(e);throw"both async and sync fetching of the wasm failed"}function x(e,t,r){return function(e){return d||!s&&!a||"function"!=typeof fetch?Promise.resolve().then((()=>L(e))):fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>L(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(r,(e=>{h("failed to asynchronously prepare wasm: "+e),D(e)}))}M(P="videodec_simd.wasm")||(N=P,P=n.locateFile?n.locateFile(N,l):l+N);var V=e=>{for(;e.length>0;)e.shift()(n)};function U(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){E[this.ptr+4>>2]=e},this.get_type=function(){return E[this.ptr+4>>2]},this.set_destructor=function(e){E[this.ptr+8>>2]=e},this.get_destructor=function(){return E[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,f[this.ptr+12|0]=e},this.get_caught=function(){return 0!=f[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,f[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=f[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){E[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return E[this.ptr+16>>2]},this.get_exception_ptr=function(){if(At(this.get_type()))return E[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}function F(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 B=void 0;function j(e){for(var t="",r=e;_[r];)t+=B[_[r++]];return t}var H={},W={},G={},z=void 0;function $(e){throw new z(e)}var J=void 0;function q(e){throw new J(e)}function K(e,t,r){function i(t){var i=r(t);i.length!==e.length&&q("Mismatched type converter count");for(var n=0;n<e.length;++n)Y(e[n],i[n])}e.forEach((function(e){G[e]=t}));var n=new Array(t.length),o=[],s=0;t.forEach(((e,t)=>{W.hasOwnProperty(e)?n[t]=W[e]:(o.push(e),H.hasOwnProperty(e)||(H[e]=[]),H[e].push((()=>{n[t]=W[e],++s===o.length&&i(n)})))})),0===o.length&&i(n)}function Y(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i=t.name;if(e||$('type "'.concat(i,'" must have a positive integer typeid pointer')),W.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;$("Cannot register type '".concat(i,"' twice"))}if(W[e]=t,delete G[e],H.hasOwnProperty(e)){var n=H[e];delete H[e],n.forEach((e=>e()))}}(e,t,r)}function X(e){if(!(this instanceof Ee&&e instanceof Ee))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n}function Q(e){return{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}}function Z(e){$(e.$$.ptrType.registeredClass.name+" instance already deleted")}var ee=!1;function te(e){}function re(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function ie(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=ie(e,t,r.baseClass);return null===i?null:r.downcast(i)}var ne={};function oe(){return Object.keys(ue).length}function se(){var e=[];for(var t in ue)ue.hasOwnProperty(t)&&e.push(ue[t]);return e}var ae=[];function ce(){for(;ae.length;){var e=ae.pop();e.$$.deleteScheduled=!1,e.delete()}}var le=void 0;function de(e){le=e,ae.length&&le&&le(ce)}var ue={};function he(e,t){return t=function(e,t){for(void 0===t&&$("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),ue[t]}function pe(e,t){return(!t.ptrType||!t.ptr)&&q("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!==!!t.smartPtr&&q("Both smartPtrType and smartPtr must be specified"),t.count={value:1},fe(Object.create(e,{$$:{value:t}}))}function me(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=he(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?pe(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):pe(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var o,s=this.registeredClass.getActualType(t),a=ne[s];if(!a)return n.call(this);o=this.isConst?a.constPointerType:a.pointerType;var c=ie(t,this.registeredClass,o.registeredClass);return null===c?n.call(this):this.isSmartPointer?pe(o.registeredClass.instancePrototype,{ptrType:o,ptr:c,smartPtrType:this,smartPtr:e}):pe(o.registeredClass.instancePrototype,{ptrType:o,ptr:c})}var fe=function(e){return"undefined"==typeof FinalizationRegistry?(fe=e=>e,e):(ee=new FinalizationRegistry((e=>{re(e.$$)})),te=e=>ee.unregister(e),(fe=e=>{var t=e.$$;if(!!t.smartPtr){var r={$$:t};ee.register(e,r,e)}return e})(e))};function _e(){if(this.$$.ptr||Z(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e=fe(Object.create(Object.getPrototypeOf(this),{$$:{value:Q(this.$$)}}));return e.$$.count.value+=1,e.$$.deleteScheduled=!1,e}function ge(){this.$$.ptr||Z(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&$("Object already scheduled for deletion"),te(this),re(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function ve(){return!this.$$.ptr}function ye(){return this.$$.ptr||Z(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&$("Object already scheduled for deletion"),ae.push(this),1===ae.length&&le&&le(ce),this.$$.deleteScheduled=!0,this}function Ee(){}var Te=48,Se=57;function Ie(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=Te&&t<=Se?"_".concat(e):e}function Ae(e,t){return e=Ie(e),{[e]:function(){return t.apply(this,arguments)}}[e]}function Ce(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||$("Function '".concat(r,"' called with an invalid number of arguments (").concat(arguments.length,") - expects one of (").concat(e[t].overloadTable,")!")),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function be(e,t,r,i,n,o,s,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=o,this.upcast=s,this.downcast=a,this.pureVirtualFunctions=[]}function Re(e,t,r){for(;t!==r;)t.upcast||$("Expected null or instance of ".concat(r.name,", got an instance of ").concat(t.name)),e=t.upcast(e),t=t.baseClass;return e}function we(e,t){if(null===t)return this.isReference&&$("null is not a valid ".concat(this.name)),0;t.$$||$('Cannot pass "'.concat(Ze(t),'" as a ').concat(this.name)),t.$$.ptr||$("Cannot pass deleted object as a pointer of type ".concat(this.name));var r=t.$$.ptrType.registeredClass;return Re(t.$$.ptr,r,this.registeredClass)}function ke(e,t){var r;if(null===t)return this.isReference&&$("null is not a valid ".concat(this.name)),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||$('Cannot pass "'.concat(Ze(t),'" as a ').concat(this.name)),t.$$.ptr||$("Cannot pass deleted object as a pointer of type ".concat(this.name)),!this.isConst&&t.$$.ptrType.isConst&&$("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));var i=t.$$.ptrType.registeredClass;if(r=Re(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&$("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:$("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,Qe.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:$("Unsupporting sharing policy")}return r}function De(e,t){if(null===t)return this.isReference&&$("null is not a valid ".concat(this.name)),0;t.$$||$('Cannot pass "'.concat(Ze(t),'" as a ').concat(this.name)),t.$$.ptr||$("Cannot pass deleted object as a pointer of type ".concat(this.name)),t.$$.ptrType.isConst&&$("Cannot convert argument of type ".concat(t.$$.ptrType.name," to parameter type ").concat(this.name));var r=t.$$.ptrType.registeredClass;return Re(t.$$.ptr,r,this.registeredClass)}function Pe(e){return this.fromWireType(y[e>>2])}function Ne(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e}function Oe(e){this.rawDestructor&&this.rawDestructor(e)}function Me(e){null!==e&&e.delete()}function Le(e,t,r,i,n,o,s,a,c,l,d){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=o,this.sharingPolicy=s,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=l,this.rawDestructor=d,n||void 0!==t.baseClass?this.toWireType=ke:i?(this.toWireType=we,this.destructorFunction=null):(this.toWireType=De,this.destructorFunction=null)}var xe=[],Ve=e=>{var t=xe[e];return t||(e>=xe.length&&(xe.length=e+1),xe[e]=t=A.get(e)),t},Ue=(e,t,r)=>e.includes("j")?((e,t,r)=>{var i=n["dynCall_"+e];return r&&r.length?i.apply(null,[t].concat(r)):i.call(null,t)})(e,t,r):Ve(t).apply(null,r),Fe=(e,t)=>{var r=[];return function(){return r.length=0,Object.assign(r,arguments),Ue(e,t,r)}};function Be(e,t){var r=(e=j(e)).includes("j")?Fe(e,t):Ve(t);return"function"!=typeof r&&$("unknown function pointer with signature ".concat(e,": ").concat(t)),r}var je=void 0;function He(e){var t=St(e),r=j(t);return Et(t),r}function We(e,t){var r=[],i={};throw t.forEach((function e(t){if(!i[t]&&!W[t]){if(G[t])return void G[t].forEach(e);r.push(t),i[t]=!0}})),new je("".concat(e,": ")+r.map(He).join([", "]))}function Ge(e,t){for(var r=[],i=0;i<e;i++)r.push(E[t+4*i>>2]);return r}function ze(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function $e(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type ".concat(typeof e," which is not a function"));var r=Ae(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function Je(e,t,r,i,n,o){var s=t.length;s<2&&$("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var a=null!==t[1]&&null!==r,c=!1,l=1;l<t.length;++l)if(null!==t[l]&&void 0===t[l].destructorFunction){c=!0;break}var d="void"!==t[0].name,u="",h="";for(l=0;l<s-2;++l)u+=(0!==l?", ":"")+"arg"+l,h+=(0!==l?", ":"")+"arg"+l+"Wired";var p="\n return function ".concat(Ie(e),"(").concat(u,") {\n if (arguments.length !== ").concat(s-2,") {\n throwBindingError('function ").concat(e," called with ").concat(arguments.length," arguments, expected ").concat(s-2," args!');\n }");c&&(p+="var destructors = [];\n");var m=c?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[$,i,n,ze,t[0],t[1]];a&&(p+="var thisWired = classParam.toWireType("+m+", this);\n");for(l=0;l<s-2;++l)p+="var arg"+l+"Wired = argType"+l+".toWireType("+m+", arg"+l+"); // "+t[l+2].name+"\n",f.push("argType"+l),_.push(t[l+2]);if(a&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||o?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",c)p+="runDestructors(destructors);\n";else for(l=a?1:2;l<t.length;++l){var g=1===l?"thisWired":"arg"+(l-2)+"Wired";null!==t[l].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[l].name+"\n",f.push(g+"_dtor"),_.push(t[l].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),$e(Function,f).apply(null,_)}function qe(){this.allocated=[void 0],this.freelist=[]}var Ke=new qe;function Ye(e){e>=Ke.reserved&&0==--Ke.get(e).refcount&&Ke.free(e)}function Xe(){for(var e=0,t=Ke.reserved;t<Ke.allocated.length;++t)void 0!==Ke.allocated[t]&&++e;return e}var Qe={toValue:e=>(e||$("Cannot use deleted val. handle = "+e),Ke.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 Ke.allocate({refcount:1,value:e})}}};function Ze(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function et(e,t){switch(t){case 2:return function(e){return this.fromWireType(T[e>>2])};case 3:return function(e){return this.fromWireType(S[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function tt(e,t,r){switch(t){case 0:return r?function(e){return f[e]}:function(e){return _[e]};case 1:return r?function(e){return g[e>>1]}:function(e){return v[e>>1]};case 2:return r?function(e){return y[e>>2]}:function(e){return E[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var rt="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,it=(e,t,r)=>{for(var i=t+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&rt)return rt.decode(e.subarray(t,n));for(var o="";t<n;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var c=63&e[t++];if((s=224==(240&s)?(15&s)<<12|a<<6|c:(7&s)<<18|a<<12|c<<6|63&e[t++])<65536)o+=String.fromCharCode(s);else{var l=s-65536;o+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else o+=String.fromCharCode((31&s)<<6|a)}else o+=String.fromCharCode(s)}return o},nt=(e,t)=>e?it(_,e,t):"";var ot="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,st=(e,t)=>{for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&v[i];)++i;if((r=i<<1)-e>32&&ot)return ot.decode(_.subarray(e,r));for(var o="",s=0;!(s>=t/2);++s){var a=g[e+2*s>>1];if(0==a)break;o+=String.fromCharCode(a)}return o},at=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,o=0;o<n;++o){var s=e.charCodeAt(o);g[t>>1]=s,t+=2}return g[t>>1]=0,t-i},ct=e=>2*e.length,lt=(e,t)=>{for(var r=0,i="";!(r>=t/4);){var n=y[e+4*r>>2];if(0==n)break;if(++r,n>=65536){var o=n-65536;i+=String.fromCharCode(55296|o>>10,56320|1023&o)}else i+=String.fromCharCode(n)}return i},dt=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t,n=i+r-4,o=0;o<e.length;++o){var s=e.charCodeAt(o);if(s>=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o);if(y[t>>2]=s,(t+=4)+4>n)break}return y[t>>2]=0,t-i},ut=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i>=55296&&i<=57343&&++r,t+=4}return t};var ht={};var pt=[];function mt(e,t){var r=W[e];return void 0===r&&$(t+" has unknown type "+He(e)),r}var ft=[];var _t;_t=()=>performance.now();var gt=[null,[],[]],vt=(e,t)=>{var r=gt[e];0===t||10===t?((1===e?u:h)(it(r,0)),r.length=0):r.push(t)};(function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);B=e})(),z=n.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},J=n.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},Ee.prototype.isAliasOf=X,Ee.prototype.clone=_e,Ee.prototype.delete=ge,Ee.prototype.isDeleted=ve,Ee.prototype.deleteLater=ye,n.getInheritedInstanceCount=oe,n.getLiveInheritedInstances=se,n.flushPendingDeletes=ce,n.setDelayFunction=de,Le.prototype.getPointee=Ne,Le.prototype.destructor=Oe,Le.prototype.argPackAdvance=8,Le.prototype.readValueFromPointer=Pe,Le.prototype.deleteObject=Me,Le.prototype.fromWireType=me,je=n.UnboundTypeError=function(e,t){var r=Ae(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:"".concat(this.name,": ").concat(this.message)},r}(Error,"UnboundTypeError"),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)}}),Ke.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Ke.reserved=Ke.allocated.length,n.count_emval_handles=Xe;var yt={o:function(e,t,r){throw new U(e).init(t,r),e},r:function(e,t,r,i,n){},m:function(e,t,r,i,n){var o=F(r);Y(e,{name:t=j(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=f;else if(2===r)i=g;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=y}return this.fromWireType(i[e>>o])},destructorFunction:null})},q:function(e,t,r,i,o,s,a,c,l,d,u,h,p){u=j(u),s=Be(o,s),c&&(c=Be(a,c)),d&&(d=Be(l,d)),p=Be(h,p);var m=Ie(u);(function(e,t,r){n.hasOwnProperty(e)?((void 0===r||void 0!==n[e].overloadTable&&void 0!==n[e].overloadTable[r])&&$("Cannot register public name '".concat(e,"' twice")),Ce(n,e,e),n.hasOwnProperty(r)&&$("Cannot register multiple overloads of a function with the same number of arguments (".concat(r,")!")),n[e].overloadTable[r]=t):(n[e]=t,void 0!==r&&(n[e].numArguments=r))})(m,(function(){We("Cannot construct ".concat(u," due to unbound types"),[i])})),K([e,t,r],i?[i]:[],(function(t){var r,o;t=t[0],i?o=(r=t.registeredClass).instancePrototype:o=Ee.prototype;var a=Ae(m,(function(){if(Object.getPrototypeOf(this)!==l)throw new z("Use 'new' to construct "+u);if(void 0===h.constructor_body)throw new z(u+" has no accessible constructor");var e=h.constructor_body[arguments.length];if(void 0===e)throw new z("Tried to invoke ctor of ".concat(u," with invalid number of parameters (").concat(arguments.length,") - expected (").concat(Object.keys(h.constructor_body).toString(),") parameters instead!"));return e.apply(this,arguments)})),l=Object.create(o,{constructor:{value:a}});a.prototype=l;var h=new be(u,a,l,p,r,s,c,d);h.baseClass&&(void 0===h.baseClass.__derivedClasses&&(h.baseClass.__derivedClasses=[]),h.baseClass.__derivedClasses.push(h));var f=new Le(u,h,!0,!1,!1),_=new Le(u+"*",h,!1,!1,!1),g=new Le(u+" const*",h,!1,!0,!1);return ne[e]={pointerType:_,constPointerType:g},function(e,t,r){n.hasOwnProperty(e)||q("Replacing nonexistant public symbol"),void 0!==n[e].overloadTable&&void 0!==r?n[e].overloadTable[r]=t:(n[e]=t,n[e].argCount=r)}(m,a),[f,_,g]}))},p:function(e,t,r,i,n,o){var s=Ge(t,r);n=Be(i,n),K([],[e],(function(e){e=e[0];var r="constructor ".concat(e.name);if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new z("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]=()=>{We("Cannot construct ".concat(e.name," due to unbound types"),s)},K([],s,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=Je(r,i,null,n,o),[]})),[]}))},d:function(e,t,r,i,n,o,s,a,c){var l=Ge(r,i);t=j(t),o=Be(n,o),K([],[e],(function(e){e=e[0];var i="".concat(e.name,".").concat(t);function n(){We("Cannot call ".concat(i," due to unbound types"),l)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var d=e.registeredClass.instancePrototype,u=d[t];return void 0===u||void 0===u.overloadTable&&u.className!==e.name&&u.argCount===r-2?(n.argCount=r-2,n.className=e.name,d[t]=n):(Ce(d,t,i),d[t].overloadTable[r-2]=n),K([],l,(function(n){var a=Je(i,n,e,o,s,c);return void 0===d[t].overloadTable?(a.argCount=r-2,d[t]=a):d[t].overloadTable[r-2]=a,[]})),[]}))},u:function(e,t){Y(e,{name:t=j(t),fromWireType:function(e){var t=Qe.toValue(e);return Ye(e),t},toWireType:function(e,t){return Qe.toHandle(t)},argPackAdvance:8,readValueFromPointer:Pe,destructorFunction:null})},k:function(e,t,r){var i=F(r);Y(e,{name:t=j(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:et(t,i),destructorFunction:null})},b:function(e,t,r,i,n){t=j(t);var o=F(r),s=e=>e;if(0===i){var a=32-8*r;s=e=>e<<a>>>a}var c=t.includes("unsigned");Y(e,{name:t,fromWireType:s,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:tt(t,o,0!==i),destructorFunction:null})},a:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=E,r=t[e>>=2],n=t[e+1];return new i(t.buffer,n,r)}Y(e,{name:r=j(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var r="std::string"===(t=j(t));Y(e,{name:t,fromWireType:function(e){var t,i=E[e>>2],n=e+4;if(r)for(var o=n,s=0;s<=i;++s){var a=n+s;if(s==i||0==_[a]){var c=nt(o,a-o);void 0===t?t=c:(t+=String.fromCharCode(0),t+=c),o=a+1}}else{var l=new Array(i);for(s=0;s<i;++s)l[s]=String.fromCharCode(_[n+s]);t=l.join("")}return Et(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i,n="string"==typeof t;n||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||$("Cannot pass non-string to std::string"),i=r&&n?(e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i<=127?t++:i<=2047?t+=2:i>=55296&&i<=57343?(t+=4,++r):t+=3}return t})(t):t.length;var o=Tt(4+i+1),s=o+4;if(E[o>>2]=i,r&&n)((e,t,r)=>{((e,t,r,i)=>{if(!(i>0))return 0;for(var n=r,o=r+i-1,s=0;s<e.length;++s){var a=e.charCodeAt(s);if(a>=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++s)),a<=127){if(r>=o)break;t[r++]=a}else if(a<=2047){if(r+1>=o)break;t[r++]=192|a>>6,t[r++]=128|63&a}else if(a<=65535){if(r+2>=o)break;t[r++]=224|a>>12,t[r++]=128|a>>6&63,t[r++]=128|63&a}else{if(r+3>=o)break;t[r++]=240|a>>18,t[r++]=128|a>>12&63,t[r++]=128|a>>6&63,t[r++]=128|63&a}}t[r]=0})(e,_,t,r)})(t,s,i+1);else if(n)for(var a=0;a<i;++a){var c=t.charCodeAt(a);c>255&&(Et(s),$("String has UTF-16 code units that do not fit in 8 bits")),_[s+a]=c}else for(a=0;a<i;++a)_[s+a]=t[a];return null!==e&&e.push(Et,o),o},argPackAdvance:8,readValueFromPointer:Pe,destructorFunction:function(e){Et(e)}})},g:function(e,t,r){var i,n,o,s,a;r=j(r),2===t?(i=st,n=at,s=ct,o=()=>v,a=1):4===t&&(i=lt,n=dt,s=ut,o=()=>E,a=2),Y(e,{name:r,fromWireType:function(e){for(var r,n=E[e>>2],s=o(),c=e+4,l=0;l<=n;++l){var d=e+4+l*t;if(l==n||0==s[d>>a]){var u=i(c,d-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=d+t}}return Et(e),r},toWireType:function(e,i){"string"!=typeof i&&$("Cannot pass non-string to C++ string type ".concat(r));var o=s(i),c=Tt(4+o+t);return E[c>>2]=o>>a,n(i,c+4,o+t),null!==e&&e.push(Et,c),c},argPackAdvance:8,readValueFromPointer:Pe,destructorFunction:function(e){Et(e)}})},n:function(e,t){Y(e,{isVoid:!0,name:t=j(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},e:function(e,t,r,i){e=pt[e],t=Qe.toValue(t),r=function(e){var t=ht[e];return void 0===t?j(e):t}(r),e(t,r,null,i)},l:Ye,h:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i<e;++i)r[i]=mt(E[t+4*i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",o=ft[n];if(void 0!==o)return o;for(var s=["retType"],a=[i],c="",l=0;l<e-1;++l)c+=(0!==l?", ":"")+"arg"+l,s.push("argType"+l),a.push(r[1+l]);var d="return function "+Ie("methodCaller_"+n)+"(handle, name, destructors, args) {\n",u=0;for(l=0;l<e-1;++l)d+=" var arg"+l+" = argType"+l+".readValueFromPointer(args"+(u?"+"+u:"")+");\n",u+=r[l+1].argPackAdvance;for(d+=" var rv = handle[name]("+c+");\n",l=0;l<e-1;++l)r[l+1].deleteObject&&(d+=" argType"+l+".deleteObject(arg"+l+");\n");return i.isVoid||(d+=" return retType.toWireType(destructors, rv);\n"),d+="};\n",s.push(d),o=function(e){var t=pt.length;return pt.push(e),t}($e(Function,s).apply(null,a)),ft[n]=o,o},f:()=>{D("")},c:_t,t:(e,t,r)=>_.copyWithin(e,t,t+r),s:e=>{_.length,D("OOM")},i:(e,t,r,i)=>{for(var n=0,o=0;o<r;o++){var s=E[t>>2],a=E[t+4>>2];t+=8;for(var c=0;c<a;c++)vt(e,_[s+c]);n+=a}return E[i>>2]=n,0}};!function(){var e={a:yt};function t(e,t){var r=e.exports;return p=(m=r).v,function(){var e=p.buffer;n.HEAP8=f=new Int8Array(e),n.HEAP16=g=new Int16Array(e),n.HEAP32=y=new Int32Array(e),n.HEAPU8=_=new Uint8Array(e),n.HEAPU16=v=new Uint16Array(e),n.HEAPU32=E=new Uint32Array(e),n.HEAPF32=T=new Float32Array(e),n.HEAPF64=S=new Float64Array(e)}(),A=m.z,function(e){b.unshift(e)}(m.w),function(){if(w--,n.monitorRunDependencies&&n.monitorRunDependencies(w),0==w&&k){var e=k;k=null,e()}}(),r}if(w++,n.monitorRunDependencies&&n.monitorRunDependencies(w),n.instantiateWasm)try{return n.instantiateWasm(e,t)}catch(r){h("Module.instantiateWasm callback failed with error: "+r),i(r)}(function(e,t,r,i){return e||"function"!=typeof WebAssembly.instantiateStreaming||M(t)||"function"!=typeof fetch?x(t,r,i):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,r).then(i,(function(e){return h("wasm streaming compile failed: "+e),h("falling back to ArrayBuffer instantiation"),x(t,r,i)}))))})(d,P,e,(function(e){t(e.instance)})).catch(i)}();var Et=e=>(Et=m.x)(e),Tt=e=>(Tt=m.y)(e),St=e=>(St=m.A)(e);n.__embind_initialize_bindings=()=>(n.__embind_initialize_bindings=m.B)();var It,At=e=>(At=m.C)(e);function Ct(){function e(){It||(It=!0,n.calledRun=!0,!I&&(V(b),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),function(){if(n.postRun)for("function"==typeof n.postRun&&(n.postRun=[n.postRun]);n.postRun.length;)e=n.postRun.shift(),R.unshift(e);var e;V(R)}()))}w>0||(function(){if(n.preRun)for("function"==typeof n.preRun&&(n.preRun=[n.preRun]);n.preRun.length;)e=n.preRun.shift(),C.unshift(e);var e;V(C)}(),w>0)||(n.setStatus?(n.setStatus("Running..."),setTimeout((function(){setTimeout((function(){n.setStatus("")}),1),e()}),1)):e())}if(n.dynCall_jiji=(e,t,r,i,o)=>(n.dynCall_jiji=m.D)(e,t,r,i,o),k=function e(){It||Ct(),It||(k=e)},n.preInit)for("function"==typeof n.preInit&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return Ct(),t.ready}})(),mU=pU,fU=class extends lU{constructor(e){super(mU,null!=e&&e.wasmPath?fetch(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)}},_U=class extends aU{initialize(){return $b(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(Fb(Ub({},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()}};Wb([iU([aU.INIT,"closed"],"initialized")],_U.prototype,"initialize",1),Wb([iU("initialized","configured",{sync:!0})],_U.prototype,"configure",1),Wb([nU("configured")],_U.prototype,"decode",1),Wb([iU([],aU.INIT)],_U.prototype,"reset",1),Wb([iU([],"closed",{ignoreError:!0,sync:!0})],_U.prototype,"close",1);var gU=class{static box(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];let n=8,o=r.length;for(let c=0;c<o;c++)n+=r[c].byteLength;let s=new Uint8Array(n);s[0]=n>>>24&255,s[1]=n>>>16&255,s[2]=n>>>8&255,s[3]=255&n,s.set(e,4);let a=8;for(let c=0;c<o;c++)s.set(r[c],a),a+=r[c].byteLength;return s}static generateInitSegment(e){let t=gU.box(gU.types.ftyp,gU.constants.FTYP),r=gU.moov(e),i=new Uint8Array(t.byteLength+r.byteLength);return i.set(t,0),i.set(r,t.byteLength),i}static moov(e){let t=gU.mvhd(e.timescale,e.duration),r=gU.trak(e),i=gU.mvex(e);return gU.box(gU.types.moov,t,r,i)}static mvhd(e,t){return gU.box(gU.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]))}static trak(e){return gU.box(gU.types.trak,gU.tkhd(e),gU.mdia(e))}static tkhd(e){let t=e.id,r=e.duration,i=e.presentWidth,n=e.presentHeight;return gU.box(gU.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>>8&255,255&i,0,0,n>>>8&255,255&n,0,0]))}static mdia(e){return gU.box(gU.types.mdia,gU.mdhd(e),gU.hdlr(e),gU.minf(e))}static mdhd(e){let t=e.timescale,r=e.duration;return gU.box(gU.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,r>>>24&255,r>>>16&255,r>>>8&255,255&r,85,196,0,0]))}static hdlr(e){let t=null;return t="audio"===e.type?gU.constants.HDLR_AUDIO:gU.constants.HDLR_VIDEO,gU.box(gU.types.hdlr,t)}static minf(e){let t=null;return t="audio"===e.type?gU.box(gU.types.smhd,gU.constants.SMHD):gU.box(gU.types.vmhd,gU.constants.VMHD),gU.box(gU.types.minf,t,gU.dinf(),gU.stbl(e))}static dinf(){return gU.box(gU.types.dinf,gU.box(gU.types.dref,gU.constants.DREF))}static stbl(e){return gU.box(gU.types.stbl,gU.stsd(e),gU.box(gU.types.stts,gU.constants.STTS),gU.box(gU.types.stsc,gU.constants.STSC),gU.box(gU.types.stsz,gU.constants.STSZ),gU.box(gU.types.stco,gU.constants.STCO))}static stsd(e){return"audio"===e.type?gU.box(gU.types.stsd,gU.constants.STSD_PREFIX,gU.mp4a(e)):"avc"===e.videoType?gU.box(gU.types.stsd,gU.constants.STSD_PREFIX,gU.avc1(e)):gU.box(gU.types.stsd,gU.constants.STSD_PREFIX,gU.hvc1(e))}static mp4a(e){let t=e.channelCount,r=e.audioSampleRate,i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t,0,16,0,0,0,0,r>>>8&255,255&r,0,0]);return gU.box(gU.types.mp4a,i,gU.esds(e))}static esds(e){let t=e.config||[],r=t.length,i=new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([r]).concat(t).concat([6,1,2]));return gU.box(gU.types.esds,i)}static avc1(e){let t=e.avcc,r=e.codecWidth,i=e.codecHeight,n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,r>>>8&255,255&r,i>>>8&255,255&i,0,72,0,0,0,72,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return gU.box(gU.types.avc1,n,gU.box(gU.types.avcC,t))}static hvc1(e){let t=e.avcc,r=e.codecWidth,i=e.codecHeight,n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,r>>>8&255,255&r,i>>>8&255,255&i,0,72,0,0,0,72,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return gU.box(gU.types.hvc1,n,gU.box(gU.types.hvcC,t))}static mvex(e){return gU.box(gU.types.mvex,gU.trex(e))}static trex(e){let t=e.id,r=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return gU.box(gU.types.trex,r)}static moof(e,t){return gU.box(gU.types.moof,gU.mfhd(e.sequenceNumber),gU.traf(e,t))}static mfhd(e){let t=new Uint8Array([0,0,0,0,e>>>24&255,e>>>16&255,e>>>8&255,255&e]);return gU.box(gU.types.mfhd,t)}static traf(e,t){let r=e.id,i=gU.box(gU.types.tfhd,new Uint8Array([0,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r])),n=gU.box(gU.types.tfdt,new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t])),o=gU.sdtp(e),s=gU.trun(e,o.byteLength+16+16+8+16+8+8);return gU.box(gU.types.traf,i,n,s,o)}static sdtp(e){let t=new Uint8Array(5),r=e.flags;return t[4]=r.isLeading<<6|r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy,gU.box(gU.types.sdtp,t)}static trun(e,t){let r=new Uint8Array(28);t+=36,r.set([0,0,15,1,0,0,0,1,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0);let i=e.duration,n=e.size,o=e.flags,s=e.cts;return r.set([i>>>24&255,i>>>16&255,i>>>8&255,255&i,n>>>24&255,n>>>16&255,n>>>8&255,255&n,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.isNonSync,0,0,s>>>24&255,s>>>16&255,s>>>8&255,255&s],12),gU.box(gU.types.trun,r)}static mdat(e){return gU.box(gU.types.mdat,e)}},vU=gU;vU.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},vU.constants={FTYP:new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),STSD_PREFIX:new Uint8Array([0,0,0,0,0,0,0,1]),STTS:new Uint8Array([0,0,0,0,0,0,0,0]),STSC:new Uint8Array([0,0,0,0,0,0,0,0]),STCO:new Uint8Array([0,0,0,0,0,0,0,0]),STSZ:new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),HDLR_VIDEO:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),HDLR_AUDIO:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),DREF:new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),SMHD:new Uint8Array([0,0,0,0,0,0,0,0]),VMHD:new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])};for(let Ij in vU.types)vU.types.hasOwnProperty(Ij)&&(vU.types[Ij]=[Ij.charCodeAt(0),Ij.charCodeAt(1),Ij.charCodeAt(2),Ij.charCodeAt(3)]);vU.constants.STSC=vU.constants.STTS,vU.constants.STCO=vU.constants.STTS;var yU=vU,EU=class{constructor(e){this.TAG="ExpGolomb",this._buffer=e,this._buffer_index=0,this._total_bytes=e.byteLength,this._total_bits=8*e.byteLength,this._current_word=0,this._current_word_bits_left=0}destroy(){this._buffer=new Uint8Array(0)}_fillCurrentWord(){let e=this._total_bytes-this._buffer_index;if(e<=0)throw new Error("ExpGolomb: _fillCurrentWord() but no bytes available");let t=Math.min(4,e),r=new Uint8Array(4);r.set(this._buffer.subarray(this._buffer_index,this._buffer_index+t)),this._current_word=new DataView(r.buffer).getUint32(0,!1),this._buffer_index+=t,this._current_word_bits_left=8*t}readBits(e){if(e>32)throw new Error("ExpGolomb: readBits() bits exceeded max 32bits!");if(e<=this._current_word_bits_left){let t=this._current_word>>>32-e;return this._current_word<<=e,this._current_word_bits_left-=e,t}let t=this._current_word_bits_left?this._current_word:0;t>>>=32-this._current_word_bits_left;let r=e-this._current_word_bits_left;this._fillCurrentWord();let i=Math.min(r,this._current_word_bits_left),n=this._current_word>>>32-i;return this._current_word<<=i,this._current_word_bits_left-=i,t=t<<i|n,t}readBool(){return 1===this.readBits(1)}readByte(){return this.readBits(8)}_skipLeadingZero(){let e;for(e=0;e<this._current_word_bits_left;e++)if(this._current_word&2147483648>>>e)return this._current_word<<=e,this._current_word_bits_left-=e,e;return this._fillCurrentWord(),e+this._skipLeadingZero()}readUEG(){let e=this._skipLeadingZero();return this.readBits(e+1)-1}readSEG(){let e=this.readUEG();return 1&e?e+1>>>1:-1*(e>>>1)}},TU=class{static _ebsp2rbsp(e){let t=e,r=t.byteLength,i=new Uint8Array(r),n=0;for(let o=0;o<r;o++)o>=2&&3===t[o]&&0===t[o-1]&&0===t[o-2]||(i[n]=t[o],n++);return new Uint8Array(i.buffer,0,n)}static parseSPS(e){let t=e.subarray(1,4),r="avc1.";for(let M=0;M<3;M++){let e=t[M].toString(16);e.length<2&&(e="0"+e),r+=e}let i=TU._ebsp2rbsp(e),n=new EU(i);n.readByte();let o=n.readByte();n.readByte();let s=n.readByte();n.readUEG();let a=TU.getProfileString(o),c=TU.getLevelString(s),l=1,d=420,u=8,h=8;if((100===o||110===o||122===o||244===o||44===o||83===o||86===o||118===o||128===o||138===o||144===o)&&(l=n.readUEG(),3===l&&n.readBits(1),l<=3&&(d=[0,420,422,444][l]),u=n.readUEG()+8,h=n.readUEG()+8,n.readBits(1),n.readBool())){let e=3!==l?8:12;for(let t=0;t<e;t++)n.readBool()&&(t<6?TU._skipScalingList(n,16):TU._skipScalingList(n,64))}n.readUEG();let p=n.readUEG();if(0===p)n.readUEG();else if(1===p){n.readBits(1),n.readSEG(),n.readSEG();let e=n.readUEG();for(let t=0;t<e;t++)n.readSEG()}let m=n.readUEG();n.readBits(1);let f=n.readUEG(),_=n.readUEG(),g=n.readBits(1);0===g&&n.readBits(1),n.readBits(1);let v=0,y=0,E=0,T=0;n.readBool()&&(v=n.readUEG(),y=n.readUEG(),E=n.readUEG(),T=n.readUEG());let S=1,I=1,A=0,C=!0,b=0,R=0;if(n.readBool()){if(n.readBool()){let e=n.readByte();e>0&&e<16?(S=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],I=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(S=n.readByte()<<8|n.readByte(),I=n.readByte()<<8|n.readByte())}if(n.readBool()&&n.readBool(),n.readBool()&&(n.readBits(4),n.readBool()&&n.readBits(24)),n.readBool()&&(n.readUEG(),n.readUEG()),n.readBool()){let e=n.readBits(32),t=n.readBits(32);C=n.readBool(),b=t,R=2*e,A=b/R}}let w=1;(1!==S||1!==I)&&(w=S/I);let k=0,D=0;if(0===l)k=1,D=2-g;else{k=3===l?1:2,D=(1===l?2:1)*(2-g)}let P=16*(f+1),N=16*(_+1)*(2-g);P-=(v+y)*k,N-=(E+T)*D;let O=Math.ceil(P*w);return n.destroy(),n=null,{codec_mimetype:r,profile_idc:o,level_idc:s,profile_string:a,level_string:c,chroma_format_idc:l,bit_depth:u,bit_depth_luma:u,bit_depth_chroma:h,ref_frames:m,chroma_format:d,chroma_format_string:TU.getChromaFormatString(d),frame_rate:{fixed:C,fps:A,fps_den:R,fps_num:b},sar_ratio:{width:S,height:I},codec_size:{width:P,height:N},present_size:{width:O,height:N}}}static _skipScalingList(e,t){let r=8,i=8,n=0;for(let o=0;o<t;o++)0!==i&&(n=e.readSEG(),i=(r+n+256)%256),r=0===i?r:i}static getProfileString(e){switch(e){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}}static getLevelString(e){return(e/10).toFixed(1)}static getChromaFormatString(e){switch(e){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}}},SU=TU;function IU(e){let{sps:t,pps:r}=e,i=8+t.byteLength+1+2+r.byteLength,n=!1,o=SU.parseSPS(t);66!==t[3]&&77!==t[3]&&88!==t[3]&&(n=!0,i+=4);let s=new Uint8Array(i);s[0]=1,s[1]=t[1],s[2]=t[2],s[3]=t[3],s[4]=255,s[5]=225;let a=t.byteLength;s[6]=a>>>8,s[7]=255&a;let c=8;s.set(t,8),c+=a,s[c]=1;let l=r.byteLength;s[c+1]=l>>>8,s[c+2]=255&l,s.set(r,c+3),c+=3+l,n&&(s[c]=252|o.chroma_format_idc,s[c+1]=248|o.bit_depth_luma-8,s[c+2]=248|o.bit_depth_chroma-8,s[c+3]=0,c+=4);let d=[23,0,0,0,0],u=new Uint8Array(d.length+s.byteLength);return u.set(d,0),u.set(s,d.length),u}var AU=class extends aU{constructor(){super(...arguments),this.sourceBufferCache=[]}decode(e){var t,r,i,n,o,s;if(null!=(t=this.config)&&t.description)try{let t=e.data.byteLength,r=8+t,i=new Uint8Array(r);new DataView(i.buffer,0).setUint32(0,r,!1),i.set(yU.types.mdat,4);let s={id:1,sequenceNumber:++this.sequenceNumber,size:t,dts:e.timestamp,cts:e.timestamp,isKeyframe:"key"===e.type,data:e.data,flags:{isLeading:0,dependsOn:2,isDependedOn:1,hasRedundancy:0,isNonSync:0},duration:40},a=yU.moof(s,e.timestamp),c=new Uint8Array(a.byteLength+i.byteLength);c.set(a,0),c.set(i,a.byteLength),null!=(n=this.sourceBuffer)&&n.updating?this.sourceBufferCache.push(c):null==(o=this.sourceBuffer)||o.appendBuffer(c)}catch(a){console.log(null==(s=this.element)?void 0:s.error),console.error(a)}else{let t,n,o=e.data instanceof ArrayBuffer?new Uint8Array(e.data):e.data,s=!1,a=(e=>{let t=[];for(let r=0;r<e.length-3;r++)0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]?t.push(r+4):0===e[r]&&0===e[r+1]&&1===e[r+2]&&t.push(r+3);return t})(o),c=[];for(let e=0;e<a.length;e++){let t=a[e],r=e<a.length-1?a[e+1]:o.length;c.push(o.subarray(t,r))}if(c.forEach(((e,r)=>{let i=31&e[0];7===i?t=e:8===i?n=e:5===i&&(s=!0)})),t&&n&&!this.sourceBuffer){let e=SU.parseSPS(t),r={id:1,type:"video",timescale:1e3,duration:0,avcc:IU({sps:t,pps:n}),codecWidth:e.codec_size.width,codecHeight:e.codec_size.height,presentWidth:e.present_size.width,presentHeight:e.present_size.height,videoType:"avc"};this.sourceBuffer=this.mse.addSourceBuffer('video/mp4; codecs="'.concat(e.codec_mimetype,'"')),this.sourceBuffer.appendBuffer(yU.generateInitSegment(r)),this.sourceBuffer.addEventListener("updateend",(()=>{this.sourceBufferCache.length&&this.sourceBuffer.appendBuffer(this.sourceBufferCache.shift())}))}else{let t=c.reduce(((e,t)=>e+t.length+4),0),n=8+t,a=new Uint8Array(n),l=new DataView(a.buffer,0);l.setUint32(0,n,!1),a.set(yU.types.mdat,4);let d=8;c.forEach((e=>{l.setUint32(d,e.length,!1),a.set(e,d+4),d+=e.length+4}));let u={id:1,sequenceNumber:++this.sequenceNumber,size:t,dts:e.timestamp,cts:e.timestamp,isKeyframe:s,data:o,flags:{isLeading:0,dependsOn:2,isDependedOn:1,hasRedundancy:0,isNonSync:0},duration:40},h=yU.moof(u,e.timestamp),p=new Uint8Array(h.byteLength+a.byteLength);p.set(h,0),p.set(a,h.byteLength),null!=(r=this.sourceBuffer)&&r.updating?this.sourceBufferCache.push(p):null==(i=this.sourceBuffer)||i.appendBuffer(p)}}}flush(){throw new Error("Method not implemented.")}reset(){throw new Error("Method not implemented.")}close(){this.src&&URL.revokeObjectURL(this.src)}initialize(e){return this.mse=new MediaSource,this.src=URL.createObjectURL(this.mse),this.element=e,e.src=this.src,new Promise((e=>{this.mse.addEventListener("sourceopen",e)}))}configure(e){if(this.config=e,e.description){let t=e.description,r=6,i=t[r]<<8|t[r+1],n=t.subarray(r+2,r+2+i),o=SU.parseSPS(n),s={id:1,type:"video",timescale:1e3,duration:0,avcc:t,codecWidth:o.codec_size.width,codecHeight:o.codec_size.height,presentWidth:o.present_size.width,presentHeight:o.present_size.height,videoType:"avc"};console.log(s),this.sourceBuffer=this.mse.addSourceBuffer('video/mp4; codecs="'.concat(o.codec_mimetype,'"')),this.sourceBuffer.appendBuffer(yU.generateInitSegment(s)),this.sourceBuffer.addEventListener("updateend",(()=>{this.sourceBufferCache.length&&this.sourceBuffer.appendBuffer(this.sourceBufferCache.shift())}))}}};Wb([iU([],aU.INIT,{sync:!0})],AU.prototype,"reset",1),Wb([iU([],"closed",{ignoreError:!0,sync:!0})],AU.prototype,"close",1),Wb([iU([aU.INIT,"closed"],"initialized")],AU.prototype,"initialize",1),Wb([iU("initialized","configured",{sync:!0})],AU.prototype,"configure",1);var CU=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var r,i,n=t;n.ready=new Promise(((e,t)=>{r=e,i=t}));var o=Object.assign({},n),s="./this.program",a="object"==typeof window,c="function"==typeof importScripts;"object"==typeof process&&"object"==typeof process.versions&&process.versions.node;var l,d,u,h="";(a||c)&&(c?h=self.location.href:"undefined"!=typeof document&&document.currentScript&&(h=document.currentScript.src),e&&(h=e),h=0!==h.indexOf("blob:")?h.substr(0,h.replace(/[?#].*/,"").lastIndexOf("/")+1):"",l=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},c&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),d=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var p,m=n.print||console.log.bind(console),f=n.printErr||console.error.bind(console);Object.assign(n,o),o=null,n.arguments&&n.arguments,n.thisProgram&&(s=n.thisProgram),n.quit&&n.quit,n.wasmBinary&&(p=n.wasmBinary),n.noExitRuntime,"object"!=typeof WebAssembly&&L("no native wasm support detected");var _,g,v,y,E,T,S,I,A,C,b=!1;var R,w=[],k=[],D=[];var P=0,N=null;function O(e){P++,n.monitorRunDependencies&&n.monitorRunDependencies(P)}function M(e){if(P--,n.monitorRunDependencies&&n.monitorRunDependencies(P),0==P&&N){var t=N;N=null,t()}}function L(e){n.onAbort&&n.onAbort(e),f(e="Aborted("+e+")"),b=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}var x,V,U="data:application/octet-stream;base64,";function F(e){return e.startsWith(U)}function B(e){if(e==x&&p)return new Uint8Array(p);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}function j(e,t,r){return function(e){return p||!a&&!c||"function"!=typeof fetch?Promise.resolve().then((()=>B(e))):fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()})).catch((()=>B(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then((e=>e)).then(r,(e=>{f("failed to asynchronously prepare wasm: "+e),L(e)}))}F(x="audiodec.wasm")||(V=x,x=n.locateFile?n.locateFile(V,h):h+V);var H,W,G=e=>{for(;e.length>0;)e.shift()(n)};function z(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){I[this.ptr+4>>2]=e},this.get_type=function(){return I[this.ptr+4>>2]},this.set_destructor=function(e){I[this.ptr+8>>2]=e},this.get_destructor=function(){return I[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,v[this.ptr+12|0]=e},this.get_caught=function(){return 0!=v[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,v[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=v[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){I[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return I[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Kt(this.get_type()))return I[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var $={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=$.isAbs(e),r="/"===e.substr(-1);return!(e=$.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))&&!t&&(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=$.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=$.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return $.normalize(e.join("/"))},join2:(e,t)=>$.normalize(e+"/"+t)},J=e=>(J=(()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);L("initRandomDevice")})())(e),q={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:ae.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=$.isAbs(i)}return(t?"/":"")+(e=$.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=q.resolve(e).substr(1),t=q.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),o=Math.min(i.length,n.length),s=o,a=0;a<o;a++)if(i[a]!==n[a]){s=a;break}var c=[];for(a=s;a<i.length;a++)c.push("..");return(c=c.concat(n.slice(s))).join("/")}},K="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,Y=(e,t,r)=>{for(var i=t+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&K)return K.decode(e.subarray(t,n));for(var o="";t<n;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var c=63&e[t++];if((s=224==(240&s)?(15&s)<<12|a<<6|c:(7&s)<<18|a<<12|c<<6|63&e[t++])<65536)o+=String.fromCharCode(s);else{var l=s-65536;o+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else o+=String.fromCharCode((31&s)<<6|a)}else o+=String.fromCharCode(s)}return o},X=[],Q=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i<=127?t++:i<=2047?t+=2:i>=55296&&i<=57343?(t+=4,++r):t+=3}return t},Z=(e,t,r,i)=>{if(!(i>0))return 0;for(var n=r,o=r+i-1,s=0;s<e.length;++s){var a=e.charCodeAt(s);if(a>=55296&&a<=57343)a=65536+((1023&a)<<10)|1023&e.charCodeAt(++s);if(a<=127){if(r>=o)break;t[r++]=a}else if(a<=2047){if(r+1>=o)break;t[r++]=192|a>>6,t[r++]=128|63&a}else if(a<=65535){if(r+2>=o)break;t[r++]=224|a>>12,t[r++]=128|a>>6&63,t[r++]=128|63&a}else{if(r+3>=o)break;t[r++]=240|a>>18,t[r++]=128|a>>12&63,t[r++]=128|a>>6&63,t[r++]=128|63&a}}return t[r]=0,r-n};function ee(e,t,r){var i=r>0?r:Q(e)+1,n=new Array(i),o=Z(e,n,0,n.length);return t&&(n.length=o),n}var te={ttys:[],init:function(){},shutdown:function(){},register:function(e,t){te.ttys[e]={input:[],output:[],ops:t},ae.registerDevice(e,te.stream_ops)},stream_ops:{open:function(e){var t=te.ttys[e.node.rdev];if(!t)throw new ae.ErrnoError(43);e.tty=t,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,t,r,i,n){if(!e.tty||!e.tty.ops.get_char)throw new ae.ErrnoError(60);for(var o=0,s=0;s<i;s++){var a;try{a=e.tty.ops.get_char(e.tty)}catch(c){throw new ae.ErrnoError(29)}if(void 0===a&&0===o)throw new ae.ErrnoError(6);if(null==a)break;o++,t[r+s]=a}return o&&(e.node.timestamp=Date.now()),o},write:function(e,t,r,i,n){if(!e.tty||!e.tty.ops.put_char)throw new ae.ErrnoError(60);try{for(var o=0;o<i;o++)e.tty.ops.put_char(e.tty,t[r+o])}catch(s){throw new ae.ErrnoError(29)}return i&&(e.node.timestamp=Date.now()),o}},default_tty_ops:{get_char:function(e){return(()=>{if(!X.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;X=ee(e,!0)}return X.shift()})()},put_char:function(e,t){null===t||10===t?(m(Y(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(m(Y(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,t,r){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(f(Y(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync:function(e){e.output&&e.output.length>0&&(f(Y(e.output,0)),e.output=[])}}},re=e=>{L()},ie={ops_table:null,mount:e=>ie.createNode(null,"/",16895,0),createNode(e,t,r,i){if(ae.isBlkdev(r)||ae.isFIFO(r))throw new ae.ErrnoError(63);ie.ops_table||(ie.ops_table={dir:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,lookup:ie.node_ops.lookup,mknod:ie.node_ops.mknod,rename:ie.node_ops.rename,unlink:ie.node_ops.unlink,rmdir:ie.node_ops.rmdir,readdir:ie.node_ops.readdir,symlink:ie.node_ops.symlink},stream:{llseek:ie.stream_ops.llseek}},file:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:{llseek:ie.stream_ops.llseek,read:ie.stream_ops.read,write:ie.stream_ops.write,allocate:ie.stream_ops.allocate,mmap:ie.stream_ops.mmap,msync:ie.stream_ops.msync}},link:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr,readlink:ie.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ie.node_ops.getattr,setattr:ie.node_ops.setattr},stream:ae.chrdev_stream_ops}});var n=ae.createNode(e,t,r,i);return ae.isDir(n.mode)?(n.node_ops=ie.ops_table.dir.node,n.stream_ops=ie.ops_table.dir.stream,n.contents={}):ae.isFile(n.mode)?(n.node_ops=ie.ops_table.file.node,n.stream_ops=ie.ops_table.file.stream,n.usedBytes=0,n.contents=null):ae.isLink(n.mode)?(n.node_ops=ie.ops_table.link.node,n.stream_ops=ie.ops_table.link.stream):ae.isChrdev(n.mode)&&(n.node_ops=ie.ops_table.chrdev.node,n.stream_ops=ie.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=ae.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,ae.isDir(e.mode)?t.size=4096:ae.isFile(e.mode)?t.size=e.usedBytes:ae.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&&ie.resizeFileStorage(e,t.size)},lookup(e,t){throw ae.genericErrors[44]},mknod:(e,t,r,i)=>ie.createNode(e,t,r,i),rename(e,t,r){if(ae.isDir(e.mode)){var i;try{i=ae.lookupNode(t,r)}catch(o){}if(i)for(var n in i.contents)throw new ae.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=ae.lookupNode(e,t);for(var i in r.contents)throw new ae.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)!e.contents.hasOwnProperty(r)||t.push(r);return t},symlink(e,t,r){var i=ie.createNode(e,t,41471,0);return i.link=r,i},readlink(e){if(!ae.isLink(e.mode))throw new ae.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,i,n){var o=e.node.contents;if(n>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-n,i);if(s>8&&o.subarray)t.set(o.subarray(n,n+s),r);else for(var a=0;a<s;a++)t[r+a]=o[n+a];return s},write(e,t,r,i,n,o){if(!i)return 0;var s=e.node;if(s.timestamp=Date.now(),t.subarray&&(!s.contents||s.contents.subarray)){if(o)return s.contents=t.subarray(r,r+i),s.usedBytes=i,i;if(0===s.usedBytes&&0===n)return s.contents=t.slice(r,r+i),s.usedBytes=i,i;if(n+i<=s.usedBytes)return s.contents.set(t.subarray(r,r+i),n),i}if(ie.expandFileStorage(s,n+i),s.contents.subarray&&t.subarray)s.contents.set(t.subarray(r,r+i),n);else for(var a=0;a<i;a++)s.contents[n+a]=t[r+a];return s.usedBytes=Math.max(s.usedBytes,n+i),i},llseek(e,t,r){var i=t;if(1===r?i+=e.position:2===r&&ae.isFile(e.node.mode)&&(i+=e.node.usedBytes),i<0)throw new ae.ErrnoError(28);return i},allocate(e,t,r){ie.expandFileStorage(e.node,t+r),e.node.usedBytes=Math.max(e.node.usedBytes,t+r)},mmap(e,t,r,i,n){if(!ae.isFile(e.node.mode))throw new ae.ErrnoError(43);var o,s,a=e.node.contents;if(2&n||a.buffer!==v.buffer){if((r>0||r+t<a.length)&&(a=a.subarray?a.subarray(r,r+t):Array.prototype.slice.call(a,r,r+t)),s=!0,!(o=re()))throw new ae.ErrnoError(48);v.set(a,o)}else s=!1,o=a.byteOffset;return{ptr:o,allocated:s}},msync:(e,t,r,i,n)=>(ie.stream_ops.write(e,t,0,i,r,!1),0)}},ne=(e,t,r,i)=>{var n=i?"":"al ".concat(e);d(e,(r=>{(function(e,t){e||L(t)})(r,'Loading data file "'.concat(e,'" failed (no arrayBuffer).')),t(new Uint8Array(r)),n&&M()}),(t=>{if(!r)throw'Loading data file "'.concat(e,'" failed.');r()})),n&&O()},oe=n.preloadPlugins||[];function se(e,t){var r=0;return e&&(r|=365),t&&(r|=146),r}var ae={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=q.resolve(e)))return{path:"",node:null};if(t=Object.assign({follow_mount:!0,recurse_count:0},t),t.recurse_count>8)throw new ae.ErrnoError(32);for(var r=e.split("/").filter((e=>!!e)),i=ae.root,n="/",o=0;o<r.length;o++){var s=o===r.length-1;if(s&&t.parent)break;if(i=ae.lookupNode(i,r[o]),n=$.join2(n,r[o]),ae.isMountpoint(i)&&(!s||s&&t.follow_mount)&&(i=i.mounted.root),!s||t.follow)for(var a=0;ae.isLink(i.mode);){var c=ae.readlink(n);if(n=q.resolve($.dirname(n),c),i=ae.lookupPath(n,{recurse_count:t.recurse_count+1}).node,a++>40)throw new ae.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(ae.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?"".concat(r,"/").concat(t):r+t:r}t=t?"".concat(e.name,"/").concat(t):e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i<t.length;i++)r=(r<<5)-r+t.charCodeAt(i)|0;return(e+r>>>0)%ae.nameTable.length},hashAddNode:e=>{var t=ae.hashName(e.parent.id,e.name);e.name_next=ae.nameTable[t],ae.nameTable[t]=e},hashRemoveNode:e=>{var t=ae.hashName(e.parent.id,e.name);if(ae.nameTable[t]===e)ae.nameTable[t]=e.name_next;else for(var r=ae.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=ae.mayLookup(e);if(r)throw new ae.ErrnoError(r,e);for(var i=ae.hashName(e.id,t),n=ae.nameTable[i];n;n=n.name_next){var o=n.name;if(n.parent.id===e.id&&o===t)return n}return ae.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new ae.FSNode(e,t,r,i);return ae.hashAddNode(n),n},destroyNode:e=>{ae.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)=>ae.ignorePermissions?0:t.includes("r")&&!(292&e.mode)||t.includes("w")&&!(146&e.mode)||t.includes("x")&&!(73&e.mode)?2:0,mayLookup:e=>ae.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{ae.lookupNode(e,t);return 20}catch(r){}return ae.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=ae.lookupNode(e,t)}catch(o){return o.errno}var n=ae.nodePermissions(e,"wx");if(n)return n;if(r){if(!ae.isDir(i.mode))return 54;if(ae.isRoot(i)||ae.getPath(i)===ae.cwd())return 10}else if(ae.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?ae.isLink(e.mode)?32:ae.isDir(e.mode)&&("r"!==ae.flagsToPermissionString(t)||512&t)?31:ae.nodePermissions(e,ae.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var e=0;e<=ae.MAX_OPEN_FDS;e++)if(!ae.streams[e])return e;throw new ae.ErrnoError(33)},getStreamChecked:e=>{var t=ae.getStream(e);if(!t)throw new ae.ErrnoError(8);return t},getStream:e=>ae.streams[e],createStream:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return ae.FSStream||(ae.FSStream=function(){this.shared={}},ae.FSStream.prototype={},Object.defineProperties(ae.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 ae.FSStream,e),-1==t&&(t=ae.nextfd()),e.fd=t,ae.streams[t]=e,e},closeStream:e=>{ae.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=ae.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new ae.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{ae.devices[e]={stream_ops:t}},getDevice:e=>ae.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),ae.syncFSRequests++,ae.syncFSRequests>1&&f("warning: ".concat(ae.syncFSRequests," FS.syncfs operations in flight at once, probably just doing extra work"));var r=ae.getMounts(ae.root.mount),i=0;function n(e){return ae.syncFSRequests--,t(e)}function o(e){if(e)return o.errored?void 0:(o.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return o(null);t.type.syncfs(t,e,o)}))},mount:(e,t,r)=>{var i,n="/"===r,o=!r;if(n&&ae.root)throw new ae.ErrnoError(10);if(!n&&!o){var s=ae.lookupPath(r,{follow_mount:!1});if(r=s.path,i=s.node,ae.isMountpoint(i))throw new ae.ErrnoError(10);if(!ae.isDir(i.mode))throw new ae.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?ae.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=ae.lookupPath(e,{follow_mount:!1});if(!ae.isMountpoint(t.node))throw new ae.ErrnoError(28);var r=t.node,i=r.mounted,n=ae.getMounts(i);Object.keys(ae.nameTable).forEach((e=>{for(var t=ae.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&ae.destroyNode(t),t=r}})),r.mounted=null;var o=r.mount.mounts.indexOf(i);r.mount.mounts.splice(o,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=ae.lookupPath(e,{parent:!0}).node,n=$.basename(e);if(!n||"."===n||".."===n)throw new ae.ErrnoError(28);var o=ae.mayCreate(i,n);if(o)throw new ae.ErrnoError(o);if(!i.node_ops.mknod)throw new ae.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,ae.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,ae.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n<r.length;++n)if(r[n]){i+="/"+r[n];try{ae.mkdir(i,t)}catch(o){if(20!=o.errno)throw o}}},mkdev:(e,t,r)=>(void 0===r&&(r=t,t=438),t|=8192,ae.mknod(e,t,r)),symlink:(e,t)=>{if(!q.resolve(e))throw new ae.ErrnoError(44);var r=ae.lookupPath(t,{parent:!0}).node;if(!r)throw new ae.ErrnoError(44);var i=$.basename(t),n=ae.mayCreate(r,i);if(n)throw new ae.ErrnoError(n);if(!r.node_ops.symlink)throw new ae.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=$.dirname(e),o=$.dirname(t),s=$.basename(e),a=$.basename(t);if(r=ae.lookupPath(e,{parent:!0}).node,i=ae.lookupPath(t,{parent:!0}).node,!r||!i)throw new ae.ErrnoError(44);if(r.mount!==i.mount)throw new ae.ErrnoError(75);var c,l=ae.lookupNode(r,s),d=q.relative(e,o);if("."!==d.charAt(0))throw new ae.ErrnoError(28);if("."!==(d=q.relative(t,n)).charAt(0))throw new ae.ErrnoError(55);try{c=ae.lookupNode(i,a)}catch(p){}if(l!==c){var u=ae.isDir(l.mode),h=ae.mayDelete(r,s,u);if(h)throw new ae.ErrnoError(h);if(h=c?ae.mayDelete(i,a,u):ae.mayCreate(i,a))throw new ae.ErrnoError(h);if(!r.node_ops.rename)throw new ae.ErrnoError(63);if(ae.isMountpoint(l)||c&&ae.isMountpoint(c))throw new ae.ErrnoError(10);if(i!==r&&(h=ae.nodePermissions(r,"w")))throw new ae.ErrnoError(h);ae.hashRemoveNode(l);try{r.node_ops.rename(l,i,a)}catch(p){throw p}finally{ae.hashAddNode(l)}}},rmdir:e=>{var t=ae.lookupPath(e,{parent:!0}).node,r=$.basename(e),i=ae.lookupNode(t,r),n=ae.mayDelete(t,r,!0);if(n)throw new ae.ErrnoError(n);if(!t.node_ops.rmdir)throw new ae.ErrnoError(63);if(ae.isMountpoint(i))throw new ae.ErrnoError(10);t.node_ops.rmdir(t,r),ae.destroyNode(i)},readdir:e=>{var t=ae.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new ae.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=ae.lookupPath(e,{parent:!0}).node;if(!t)throw new ae.ErrnoError(44);var r=$.basename(e),i=ae.lookupNode(t,r),n=ae.mayDelete(t,r,!1);if(n)throw new ae.ErrnoError(n);if(!t.node_ops.unlink)throw new ae.ErrnoError(63);if(ae.isMountpoint(i))throw new ae.ErrnoError(10);t.node_ops.unlink(t,r),ae.destroyNode(i)},readlink:e=>{var t=ae.lookupPath(e).node;if(!t)throw new ae.ErrnoError(44);if(!t.node_ops.readlink)throw new ae.ErrnoError(28);return q.resolve(ae.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=ae.lookupPath(e,{follow:!t}).node;if(!r)throw new ae.ErrnoError(44);if(!r.node_ops.getattr)throw new ae.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>ae.stat(e,!0),chmod:(e,t,r)=>{var i;"string"==typeof e?i=ae.lookupPath(e,{follow:!r}).node:i=e;if(!i.node_ops.setattr)throw new ae.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{ae.chmod(e,t,!0)},fchmod:(e,t)=>{var r=ae.getStreamChecked(e);ae.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;"string"==typeof e?n=ae.lookupPath(e,{follow:!i}).node:n=e;if(!n.node_ops.setattr)throw new ae.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{ae.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=ae.getStreamChecked(e);ae.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new ae.ErrnoError(28);var r;"string"==typeof e?r=ae.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new ae.ErrnoError(63);if(ae.isDir(r.mode))throw new ae.ErrnoError(31);if(!ae.isFile(r.mode))throw new ae.ErrnoError(28);var i=ae.nodePermissions(r,"w");if(i)throw new ae.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=ae.getStreamChecked(e);if(!(2097155&r.flags))throw new ae.ErrnoError(28);ae.truncate(r.node,t)},utime:(e,t,r)=>{var i=ae.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(e,t,r)=>{if(""===e)throw new ae.ErrnoError(44);var i;if(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,r=void 0===r?438:r,r=64&t?4095&r|32768:0,"object"==typeof e)i=e;else{e=$.normalize(e);try{i=ae.lookupPath(e,{follow:!(131072&t)}).node}catch(c){}}var o=!1;if(64&t)if(i){if(128&t)throw new ae.ErrnoError(20)}else i=ae.mknod(e,r,0),o=!0;if(!i)throw new ae.ErrnoError(44);if(ae.isChrdev(i.mode)&&(t&=-513),65536&t&&!ae.isDir(i.mode))throw new ae.ErrnoError(54);if(!o){var s=ae.mayOpen(i,t);if(s)throw new ae.ErrnoError(s)}512&t&&!o&&ae.truncate(i,0),t&=-131713;var a=ae.createStream({node:i,path:ae.getPath(i),flags:t,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),n.logReadFiles&&!(1&t)&&(ae.readFiles||(ae.readFiles={}),e in ae.readFiles||(ae.readFiles[e]=1)),a},close:e=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(t){throw t}finally{ae.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new ae.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new ae.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(i<0||n<0)throw new ae.ErrnoError(28);if(ae.isClosed(e))throw new ae.ErrnoError(8);if(1==(2097155&e.flags))throw new ae.ErrnoError(8);if(ae.isDir(e.node.mode))throw new ae.ErrnoError(31);if(!e.stream_ops.read)throw new ae.ErrnoError(28);var o=void 0!==n;if(o){if(!e.seekable)throw new ae.ErrnoError(70)}else n=e.position;var s=e.stream_ops.read(e,t,r,i,n);return o||(e.position+=s),s},write:(e,t,r,i,n,o)=>{if(i<0||n<0)throw new ae.ErrnoError(28);if(ae.isClosed(e))throw new ae.ErrnoError(8);if(!(2097155&e.flags))throw new ae.ErrnoError(8);if(ae.isDir(e.node.mode))throw new ae.ErrnoError(31);if(!e.stream_ops.write)throw new ae.ErrnoError(28);e.seekable&&1024&e.flags&&ae.llseek(e,0,2);var s=void 0!==n;if(s){if(!e.seekable)throw new ae.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,o);return s||(e.position+=a),a},allocate:(e,t,r)=>{if(ae.isClosed(e))throw new ae.ErrnoError(8);if(t<0||r<=0)throw new ae.ErrnoError(28);if(!(2097155&e.flags))throw new ae.ErrnoError(8);if(!ae.isFile(e.node.mode)&&!ae.isDir(e.node.mode))throw new ae.ErrnoError(43);if(!e.stream_ops.allocate)throw new ae.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new ae.ErrnoError(2);if(1==(2097155&e.flags))throw new ae.ErrnoError(2);if(!e.stream_ops.mmap)throw new ae.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0,munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new ae.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'.concat(t.encoding,'"'));var r,i=ae.open(e,t.flags),n=ae.stat(e).size,o=new Uint8Array(n);return ae.read(i,o,0,n,0),"utf8"===t.encoding?r=Y(o,0):"binary"===t.encoding&&(r=o),ae.close(i),r},writeFile:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};r.flags=r.flags||577;var i=ae.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(Q(t)+1),o=Z(t,n,0,n.length);ae.write(i,n,0,o,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");ae.write(i,t,0,t.byteLength,void 0,r.canOwn)}ae.close(i)},cwd:()=>ae.currentPath,chdir:e=>{var t=ae.lookupPath(e,{follow:!0});if(null===t.node)throw new ae.ErrnoError(44);if(!ae.isDir(t.node.mode))throw new ae.ErrnoError(54);var r=ae.nodePermissions(t.node,"x");if(r)throw new ae.ErrnoError(r);ae.currentPath=t.path},createDefaultDirectories:()=>{ae.mkdir("/tmp"),ae.mkdir("/home"),ae.mkdir("/home/web_user")},createDefaultDevices:()=>{ae.mkdir("/dev"),ae.registerDevice(ae.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),ae.mkdev("/dev/null",ae.makedev(1,3)),te.register(ae.makedev(5,0),te.default_tty_ops),te.register(ae.makedev(6,0),te.default_tty1_ops),ae.mkdev("/dev/tty",ae.makedev(5,0)),ae.mkdev("/dev/tty1",ae.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=J(e).byteLength),e[--t]);ae.createDevice("/dev","random",r),ae.createDevice("/dev","urandom",r),ae.mkdir("/dev/shm"),ae.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{ae.mkdir("/proc");var e=ae.mkdir("/proc/self");ae.mkdir("/proc/self/fd"),ae.mount({mount:()=>{var t=ae.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=ae.getStreamChecked(r),n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{n.stdin?ae.createDevice("/dev","stdin",n.stdin):ae.symlink("/dev/tty","/dev/stdin"),n.stdout?ae.createDevice("/dev","stdout",null,n.stdout):ae.symlink("/dev/tty","/dev/stdout"),n.stderr?ae.createDevice("/dev","stderr",null,n.stderr):ae.symlink("/dev/tty1","/dev/stderr"),ae.open("/dev/stdin",0),ae.open("/dev/stdout",1),ae.open("/dev/stderr",1)},ensureErrnoError:()=>{ae.ErrnoError||(ae.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},ae.ErrnoError.prototype=new Error,ae.ErrnoError.prototype.constructor=ae.ErrnoError,[44].forEach((e=>{ae.genericErrors[e]=new ae.ErrnoError(e),ae.genericErrors[e].stack="<generic error, no stack>"})))},staticInit:()=>{ae.ensureErrnoError(),ae.nameTable=new Array(4096),ae.mount(ie,{},"/"),ae.createDefaultDirectories(),ae.createDefaultDevices(),ae.createSpecialDirectories(),ae.filesystems={MEMFS:ie}},init:(e,t,r)=>{ae.init.initialized=!0,ae.ensureErrnoError(),n.stdin=e||n.stdin,n.stdout=t||n.stdout,n.stderr=r||n.stderr,ae.createStandardStreams()},quit:()=>{ae.init.initialized=!1;for(var e=0;e<ae.streams.length;e++){var t=ae.streams[e];!t||ae.close(t)}},findObject:(e,t)=>{var r=ae.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=ae.lookupPath(e,{follow:!t})).path}catch(n){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=ae.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=$.basename(e),i=ae.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(n){r.error=n.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:ae.getPath(e);for(var n=t.split("/").reverse();n.length;){var o=n.pop();if(o){var s=$.join2(e,o);try{ae.mkdir(s)}catch(a){}e=s}}return s},createFile:(e,t,r,i,n)=>{var o=$.join2("string"==typeof e?e:ae.getPath(e),t),s=se(i,n);return ae.create(o,s)},createDataFile:(e,t,r,i,n,o)=>{var s=t;e&&(e="string"==typeof e?e:ae.getPath(e),s=t?$.join2(e,t):e);var a=se(i,n),c=ae.create(s,a);if(r){if("string"==typeof r){for(var l=new Array(r.length),d=0,u=r.length;d<u;++d)l[d]=r.charCodeAt(d);r=l}ae.chmod(c,146|a);var h=ae.open(c,577);ae.write(h,r,0,r.length,0,o),ae.close(h),ae.chmod(c,a)}return c},createDevice:(e,t,r,i)=>{var n=$.join2("string"==typeof e?e:ae.getPath(e),t),o=se(!!r,!!i);ae.createDevice.major||(ae.createDevice.major=64);var s=ae.makedev(ae.createDevice.major++,0);return ae.registerDevice(s,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,o)=>{for(var s=0,a=0;a<n;a++){var c;try{c=r()}catch(l){throw new ae.ErrnoError(29)}if(void 0===c&&0===s)throw new ae.ErrnoError(6);if(null==c)break;s++,t[i+a]=c}return s&&(e.node.timestamp=Date.now()),s},write:(e,t,r,n,o)=>{for(var s=0;s<n;s++)try{i(t[r+s])}catch(a){throw new ae.ErrnoError(29)}return n&&(e.node.timestamp=Date.now()),s}}),ae.mkdev(n,o,s)},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(!l)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=ee(l(e.url),!0),e.usedBytes=e.contents.length}catch(t){throw new ae.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function o(){this.lengthKnown=!1,this.chunks=[]}if(o.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},o.prototype.setDataGetter=function(e){this.getter=e},o.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,o=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;n||(s=i);var a=this;a.setDataGetter((e=>{var t=e*s,n=(e+1)*s-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==s&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):ee(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),(o||!i)&&(s=i=1,i=this.getter(0).length,s=i,m("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!c)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new o;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:s}}else a={isDevice:!1,url:r};var l=ae.createFile(e,t,a,i,n);a.contents?l.contents=a.contents:a.url&&(l.contents=null,l.url=a.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var d={};function u(e,t,r,i,n){var o=e.node.contents;if(n>=o.length)return 0;var s=Math.min(o.length-n,i);if(o.slice)for(var a=0;a<s;a++)t[r+a]=o[n+a];else for(a=0;a<s;a++)t[r+a]=o.get(n+a);return s}return Object.keys(l.stream_ops).forEach((e=>{var t=l.stream_ops[e];d[e]=function(){return ae.forceLoadFile(l),t.apply(null,arguments)}})),d.read=(e,t,r,i,n)=>(ae.forceLoadFile(l),u(e,t,r,i,n)),d.mmap=(e,t,r,i,n)=>{ae.forceLoadFile(l);var o=re();if(!o)throw new ae.ErrnoError(48);return u(e,v,o,t,r),{ptr:o,allocated:!0}},l.stream_ops=d,l}},ce=(e,t)=>e?Y(y,e,t):"",le={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if($.isAbs(t))return t;var i;-100===e?i=ae.cwd():i=le.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new ae.ErrnoError(44);return i}return $.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(a){if(a&&a.node&&$.normalize(t)!==$.normalize(ae.getPath(a.node)))return-54;throw a}S[r>>2]=i.dev,S[r+4>>2]=i.mode,I[r+8>>2]=i.nlink,S[r+12>>2]=i.uid,S[r+16>>2]=i.gid,S[r+20>>2]=i.rdev,W=[i.size>>>0,(H=i.size,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+24>>2]=W[0],S[r+28>>2]=W[1],S[r+32>>2]=4096,S[r+36>>2]=i.blocks;var n=i.atime.getTime(),o=i.mtime.getTime(),s=i.ctime.getTime();return W=[Math.floor(n/1e3)>>>0,(H=Math.floor(n/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+40>>2]=W[0],S[r+44>>2]=W[1],I[r+48>>2]=n%1e3*1e3,W=[Math.floor(o/1e3)>>>0,(H=Math.floor(o/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+56>>2]=W[0],S[r+60>>2]=W[1],I[r+64>>2]=o%1e3*1e3,W=[Math.floor(s/1e3)>>>0,(H=Math.floor(s/1e3),+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+72>>2]=W[0],S[r+76>>2]=W[1],I[r+80>>2]=s%1e3*1e3,W=[i.ino>>>0,(H=i.ino,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[r+88>>2]=W[0],S[r+92>>2]=W[1],0},doMsync:function(e,t,r,i,n){if(!ae.isFile(t.node.mode))throw new ae.ErrnoError(43);if(2&i)return 0;var o=y.slice(e,e+r);ae.msync(t,o,n,r,i)},varargs:void 0,get:()=>(le.varargs+=4,S[le.varargs-4>>2]),getStr:e=>ce(e),getStreamFromFD:function(e){return ae.getStreamChecked(e)}};function de(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 ue=void 0;function he(e){for(var t="",r=e;y[r];)t+=ue[y[r++]];return t}var pe={},me={},fe={},_e=void 0;function ge(e){throw new _e(e)}var ve=void 0;function ye(e){throw new ve(e)}function Ee(e,t,r){function i(t){var i=r(t);i.length!==e.length&&ye("Mismatched type converter count");for(var n=0;n<e.length;++n)Te(e[n],i[n])}e.forEach((function(e){fe[e]=t}));var n=new Array(t.length),o=[],s=0;t.forEach(((e,t)=>{me.hasOwnProperty(e)?n[t]=me[e]:(o.push(e),pe.hasOwnProperty(e)||(pe[e]=[]),pe[e].push((()=>{n[t]=me[e],++s===o.length&&i(n)})))})),0===o.length&&i(n)}function Te(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var i=t.name;if(e||ge('type "'.concat(i,'" must have a positive integer typeid pointer')),me.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;ge("Cannot register type '".concat(i,"' twice"))}if(me[e]=t,delete fe[e],pe.hasOwnProperty(e)){var n=pe[e];delete pe[e],n.forEach((e=>e()))}}(e,t,r)}function Se(e){if(!(this instanceof ze&&e instanceof ze))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n}function Ie(e){return{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}}function Ae(e){ge(e.$$.ptrType.registeredClass.name+" instance already deleted")}var Ce=!1;function be(e){}function Re(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function we(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=we(e,t,r.baseClass);return null===i?null:r.downcast(i)}var ke={};function De(){return Object.keys(xe).length}function Pe(){var e=[];for(var t in xe)xe.hasOwnProperty(t)&&e.push(xe[t]);return e}var Ne=[];function Oe(){for(;Ne.length;){var e=Ne.pop();e.$$.deleteScheduled=!1,e.delete()}}var Me=void 0;function Le(e){Me=e,Ne.length&&Me&&Me(Oe)}var xe={};function Ve(e,t){return t=function(e,t){for(void 0===t&&ge("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),xe[t]}function Ue(e,t){return(!t.ptrType||!t.ptr)&&ye("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!==!!t.smartPtr&&ye("Both smartPtrType and smartPtr must be specified"),t.count={value:1},Be(Object.create(e,{$$:{value:t}}))}function Fe(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=Ve(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?Ue(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):Ue(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var o,s=this.registeredClass.getActualType(t),a=ke[s];if(!a)return n.call(this);o=this.isConst?a.constPointerType:a.pointerType;var c=we(t,this.registeredClass,o.registeredClass);return null===c?n.call(this):this.isSmartPointer?Ue(o.registeredClass.instancePrototype,{ptrType:o,ptr:c,smartPtrType:this,smartPtr:e}):Ue(o.registeredClass.instancePrototype,{ptrType:o,ptr:c})}var Be=function(e){return"undefined"==typeof FinalizationRegistry?(Be=e=>e,e):(Ce=new FinalizationRegistry((e=>{Re(e.$$)})),be=e=>Ce.unregister(e),(Be=e=>{var t=e.$$;if(!!t.smartPtr){var r={$$:t};Ce.register(e,r,e)}return e})(e))};function je(){if(this.$$.ptr||Ae(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e=Be(Object.create(Object.getPrototypeOf(this),{$$:{value:Ie(this.$$)}}));return e.$$.count.value+=1,e.$$.deleteScheduled=!1,e}function He(){this.$$.ptr||Ae(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ge("Object already scheduled for deletion"),be(this),Re(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function We(){return!this.$$.ptr}function Ge(){return this.$$.ptr||Ae(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ge("Object already scheduled for deletion"),Ne.push(this),1===Ne.length&&Me&&Me(Oe),this.$$.deleteScheduled=!0,this}function ze(){}var $e=48,Je=57;function qe(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=$e&&t<=Je?"_".concat(e):e}function Ke(e,t){return e=qe(e),{[e]:function(){return t.apply(this,arguments)}}[e]}function Ye(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||ge("Function '".concat(r,"' called with an invalid number of arguments (").concat(arguments.length,") - expects one of (").concat(e[t].overloadTable,")!")),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function Xe(e,t,r,i,n,o,s,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=o,this.upcast=s,this.downcast=a,this.pureVirtualFunctions=[]}function Qe(e,t,r){for(;t!==r;)t.upcast||ge("Expected null or instance of ".concat(r.name,", got an instance of ").concat(t.name)),e=t.upcast(e),t=t.baseClass;return e}function Ze(e,t){if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name));var r=t.$$.ptrType.registeredClass;return Qe(t.$$.ptr,r,this.registeredClass)}function et(e,t){var r;if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name)),!this.isConst&&t.$$.ptrType.isConst&&ge("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));var i=t.$$.ptrType.registeredClass;if(r=Qe(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&ge("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:ge("Cannot convert argument of type ".concat(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name," to parameter type ").concat(this.name));break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,It.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:ge("Unsupporting sharing policy")}return r}function tt(e,t){if(null===t)return this.isReference&&ge("null is not a valid ".concat(this.name)),0;t.$$||ge('Cannot pass "'.concat(At(t),'" as a ').concat(this.name)),t.$$.ptr||ge("Cannot pass deleted object as a pointer of type ".concat(this.name)),t.$$.ptrType.isConst&&ge("Cannot convert argument of type ".concat(t.$$.ptrType.name," to parameter type ").concat(this.name));var r=t.$$.ptrType.registeredClass;return Qe(t.$$.ptr,r,this.registeredClass)}function rt(e){return this.fromWireType(S[e>>2])}function it(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e}function nt(e){this.rawDestructor&&this.rawDestructor(e)}function ot(e){null!==e&&e.delete()}function st(e,t,r,i,n,o,s,a,c,l,d){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=o,this.sharingPolicy=s,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=l,this.rawDestructor=d,n||void 0!==t.baseClass?this.toWireType=et:i?(this.toWireType=Ze,this.destructorFunction=null):(this.toWireType=tt,this.destructorFunction=null)}var at=[],ct=e=>{var t=at[e];return t||(e>=at.length&&(at.length=e+1),at[e]=t=R.get(e)),t},lt=(e,t,r)=>e.includes("j")?((e,t,r)=>{var i=n["dynCall_"+e];return r&&r.length?i.apply(null,[t].concat(r)):i.call(null,t)})(e,t,r):ct(t).apply(null,r),dt=(e,t)=>{var r=[];return function(){return r.length=0,Object.assign(r,arguments),lt(e,t,r)}};function ut(e,t){var r=(e=he(e)).includes("j")?dt(e,t):ct(t);return"function"!=typeof r&&ge("unknown function pointer with signature ".concat(e,": ").concat(t)),r}var ht=void 0;function pt(e){var t=Jt(e),r=he(t);return zt(t),r}function mt(e,t){var r=[],i={};throw t.forEach((function e(t){if(!i[t]&&!me[t]){if(fe[t])return void fe[t].forEach(e);r.push(t),i[t]=!0}})),new ht("".concat(e,": ")+r.map(pt).join([", "]))}function ft(e,t){for(var r=[],i=0;i<e;i++)r.push(I[t+4*i>>2]);return r}function _t(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function gt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type ".concat(typeof e," which is not a function"));var r=Ke(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function vt(e,t,r,i,n,o){var s=t.length;s<2&&ge("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var a=null!==t[1]&&null!==r,c=!1,l=1;l<t.length;++l)if(null!==t[l]&&void 0===t[l].destructorFunction){c=!0;break}var d="void"!==t[0].name,u="",h="";for(l=0;l<s-2;++l)u+=(0!==l?", ":"")+"arg"+l,h+=(0!==l?", ":"")+"arg"+l+"Wired";var p="\n return function ".concat(qe(e),"(").concat(u,") {\n if (arguments.length !== ").concat(s-2,") {\n throwBindingError('function ").concat(e," called with ").concat(arguments.length," arguments, expected ").concat(s-2," args!');\n }");c&&(p+="var destructors = [];\n");var m=c?"destructors":"null",f=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],_=[ge,i,n,_t,t[0],t[1]];a&&(p+="var thisWired = classParam.toWireType("+m+", this);\n");for(l=0;l<s-2;++l)p+="var arg"+l+"Wired = argType"+l+".toWireType("+m+", arg"+l+"); // "+t[l+2].name+"\n",f.push("argType"+l),_.push(t[l+2]);if(a&&(h="thisWired"+(h.length>0?", ":"")+h),p+=(d||o?"var rv = ":"")+"invoker(fn"+(h.length>0?", ":"")+h+");\n",c)p+="runDestructors(destructors);\n";else for(l=a?1:2;l<t.length;++l){var g=1===l?"thisWired":"arg"+(l-2)+"Wired";null!==t[l].destructorFunction&&(p+=g+"_dtor("+g+"); // "+t[l].name+"\n",f.push(g+"_dtor"),_.push(t[l].destructorFunction))}return d&&(p+="var ret = retType.fromWireType(rv);\nreturn ret;\n"),p+="}\n",f.push(p),gt(Function,f).apply(null,_)}function yt(){this.allocated=[void 0],this.freelist=[]}var Et=new yt;function Tt(e){e>=Et.reserved&&0==--Et.get(e).refcount&&Et.free(e)}function St(){for(var e=0,t=Et.reserved;t<Et.allocated.length;++t)void 0!==Et.allocated[t]&&++e;return e}var It={toValue:e=>(e||ge("Cannot use deleted val. handle = "+e),Et.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 Et.allocate({refcount:1,value:e})}}};function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function Ct(e,t){switch(t){case 2:return function(e){return this.fromWireType(A[e>>2])};case 3:return function(e){return this.fromWireType(C[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}function bt(e,t,r){switch(t){case 0:return r?function(e){return v[e]}:function(e){return y[e]};case 1:return r?function(e){return E[e>>1]}:function(e){return T[e>>1]};case 2:return r?function(e){return S[e>>2]}:function(e){return I[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Rt="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,wt=(e,t)=>{for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&T[i];)++i;if((r=i<<1)-e>32&&Rt)return Rt.decode(y.subarray(e,r));for(var o="",s=0;!(s>=t/2);++s){var a=E[e+2*s>>1];if(0==a)break;o+=String.fromCharCode(a)}return o},kt=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,o=0;o<n;++o){var s=e.charCodeAt(o);E[t>>1]=s,t+=2}return E[t>>1]=0,t-i},Dt=e=>2*e.length,Pt=(e,t)=>{for(var r=0,i="";!(r>=t/4);){var n=S[e+4*r>>2];if(0==n)break;if(++r,n>=65536){var o=n-65536;i+=String.fromCharCode(55296|o>>10,56320|1023&o)}else i+=String.fromCharCode(n)}return i},Nt=(e,t,r)=>{if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t,n=i+r-4,o=0;o<e.length;++o){var s=e.charCodeAt(o);if(s>=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++o);if(S[t>>2]=s,(t+=4)+4>n)break}return S[t>>2]=0,t-i},Ot=e=>{for(var t=0,r=0;r<e.length;++r){var i=e.charCodeAt(r);i>=55296&&i<=57343&&++r,t+=4}return t};var Mt={};var Lt=[];function xt(e,t){var r=me[e];return void 0===r&&ge(t+" has unknown type "+pt(e)),r}var Vt=[];var Ut={},Ft=()=>{if(!Ft.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",_:s||"./this.program"};for(var t in Ut)void 0===Ut[t]?delete e[t]:e[t]=Ut[t];var r=[];for(var t in e)r.push("".concat(t,"=").concat(e[t]));Ft.strings=r}return Ft.strings};var Bt=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=ae.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i},jt=365,Ht=146;Object.defineProperties(Bt.prototype,{read:{get:function(){return(this.mode&jt)===jt},set:function(e){e?this.mode|=jt:this.mode&=~jt}},write:{get:function(){return(this.mode&Ht)===Ht},set:function(e){e?this.mode|=Ht:this.mode&=~Ht}},isFolder:{get:function(){return ae.isDir(this.mode)}},isDevice:{get:function(){return ae.isChrdev(this.mode)}}}),ae.FSNode=Bt,ae.createPreloadedFile=function(e,t,r,i,n,o,s,a,c,l){var d=t?q.resolve($.join2(e,t)):e;function u(r){function u(r){l&&l(),a||ae.createDataFile(e,t,r,i,n,c),o&&o(),M()}(function(e,t,r,i){"undefined"!=typeof Browser&&Browser.init();var n=!1;return oe.forEach((function(o){n||o.canHandle(t)&&(o.handle(e,t,r,i),n=!0)})),n})(r,d,u,(()=>{s&&s(),M()}))||u(r)}O(),"string"==typeof r?ne(r,(e=>u(e)),s):u(r)},ae.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);ue=e}(),_e=n.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},ve=n.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},ze.prototype.isAliasOf=Se,ze.prototype.clone=je,ze.prototype.delete=He,ze.prototype.isDeleted=We,ze.prototype.deleteLater=Ge,n.getInheritedInstanceCount=De,n.getLiveInheritedInstances=Pe,n.flushPendingDeletes=Oe,n.setDelayFunction=Le,st.prototype.getPointee=it,st.prototype.destructor=nt,st.prototype.argPackAdvance=8,st.prototype.readValueFromPointer=rt,st.prototype.deleteObject=ot,st.prototype.fromWireType=Fe,ht=n.UnboundTypeError=function(e,t){var r=Ke(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:"".concat(this.name,": ").concat(this.message)},r}(Error,"UnboundTypeError"),Object.assign(yt.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)}}),Et.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Et.reserved=Et.allocated.length,n.count_emval_handles=St;var Wt={p:function(e,t,r){throw new z(e).init(t,r),e},C:function(e,t,r){le.varargs=r;try{var i=le.getStreamFromFD(e);switch(t){case 0:return(n=le.get())<0?-28:ae.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=le.get();return i.flags|=n,0;case 5:n=le.get();return E[n+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return(e=>{S[$t()>>2]=e})(28),-1}}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return-o.errno}},w:function(e,t,r,i){le.varargs=i;try{t=le.getStr(t),t=le.calculateAt(e,t);var n=i?le.get():0;return ae.open(t,r,n).fd}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return-o.errno}},t:function(e,t,r,i,n){},n:function(e,t,r,i,n){var o=de(r);Te(e,{name:t=he(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=v;else if(2===r)i=E;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=S}return this.fromWireType(i[e>>o])},destructorFunction:null})},r:function(e,t,r,i,o,s,a,c,l,d,u,h,p){u=he(u),s=ut(o,s),c&&(c=ut(a,c)),d&&(d=ut(l,d)),p=ut(h,p);var m=qe(u);(function(e,t,r){n.hasOwnProperty(e)?((void 0===r||void 0!==n[e].overloadTable&&void 0!==n[e].overloadTable[r])&&ge("Cannot register public name '".concat(e,"' twice")),Ye(n,e,e),n.hasOwnProperty(r)&&ge("Cannot register multiple overloads of a function with the same number of arguments (".concat(r,")!")),n[e].overloadTable[r]=t):(n[e]=t,void 0!==r&&(n[e].numArguments=r))})(m,(function(){mt("Cannot construct ".concat(u," due to unbound types"),[i])})),Ee([e,t,r],i?[i]:[],(function(t){var r,o;t=t[0],i?o=(r=t.registeredClass).instancePrototype:o=ze.prototype;var a=Ke(m,(function(){if(Object.getPrototypeOf(this)!==l)throw new _e("Use 'new' to construct "+u);if(void 0===h.constructor_body)throw new _e(u+" has no accessible constructor");var e=h.constructor_body[arguments.length];if(void 0===e)throw new _e("Tried to invoke ctor of ".concat(u," with invalid number of parameters (").concat(arguments.length,") - expected (").concat(Object.keys(h.constructor_body).toString(),") parameters instead!"));return e.apply(this,arguments)})),l=Object.create(o,{constructor:{value:a}});a.prototype=l;var h=new Xe(u,a,l,p,r,s,c,d);h.baseClass&&(void 0===h.baseClass.__derivedClasses&&(h.baseClass.__derivedClasses=[]),h.baseClass.__derivedClasses.push(h));var f=new st(u,h,!0,!1,!1),_=new st(u+"*",h,!1,!1,!1),g=new st(u+" const*",h,!1,!0,!1);return ke[e]={pointerType:_,constPointerType:g},function(e,t,r){n.hasOwnProperty(e)||ye("Replacing nonexistant public symbol"),void 0!==n[e].overloadTable&&void 0!==r?n[e].overloadTable[r]=t:(n[e]=t,n[e].argCount=r)}(m,a),[f,_,g]}))},q:function(e,t,r,i,n,o){var s=ft(t,r);n=ut(i,n),Ee([],[e],(function(e){e=e[0];var r="constructor ".concat(e.name);if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new _e("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]=()=>{mt("Cannot construct ".concat(e.name," due to unbound types"),s)},Ee([],s,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=vt(r,i,null,n,o),[]})),[]}))},d:function(e,t,r,i,n,o,s,a,c){var l=ft(r,i);t=he(t),o=ut(n,o),Ee([],[e],(function(e){e=e[0];var i="".concat(e.name,".").concat(t);function n(){mt("Cannot call ".concat(i," due to unbound types"),l)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var d=e.registeredClass.instancePrototype,u=d[t];return void 0===u||void 0===u.overloadTable&&u.className!==e.name&&u.argCount===r-2?(n.argCount=r-2,n.className=e.name,d[t]=n):(Ye(d,t,i),d[t].overloadTable[r-2]=n),Ee([],l,(function(n){var a=vt(i,n,e,o,s,c);return void 0===d[t].overloadTable?(a.argCount=r-2,d[t]=a):d[t].overloadTable[r-2]=a,[]})),[]}))},D:function(e,t){Te(e,{name:t=he(t),fromWireType:function(e){var t=It.toValue(e);return Tt(e),t},toWireType:function(e,t){return It.toHandle(t)},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:null})},k:function(e,t,r){var i=de(r);Te(e,{name:t=he(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:Ct(t,i),destructorFunction:null})},c:function(e,t,r,i,n){t=he(t);var o=de(r),s=e=>e;if(0===i){var a=32-8*r;s=e=>e<<a>>>a}var c=t.includes("unsigned");Te(e,{name:t,fromWireType:s,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:bt(t,o,0!==i),destructorFunction:null})},b:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=I,r=t[e>>=2],n=t[e+1];return new i(t.buffer,n,r)}Te(e,{name:r=he(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},j:function(e,t){var r="std::string"===(t=he(t));Te(e,{name:t,fromWireType:function(e){var t,i=I[e>>2],n=e+4;if(r)for(var o=n,s=0;s<=i;++s){var a=n+s;if(s==i||0==y[a]){var c=ce(o,a-o);void 0===t?t=c:(t+=String.fromCharCode(0),t+=c),o=a+1}}else{var l=new Array(i);for(s=0;s<i;++s)l[s]=String.fromCharCode(y[n+s]);t=l.join("")}return zt(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i,n="string"==typeof t;n||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||ge("Cannot pass non-string to std::string"),i=r&&n?Q(t):t.length;var o=Gt(4+i+1),s=o+4;if(I[o>>2]=i,r&&n)((e,t,r)=>{Z(e,y,t,r)})(t,s,i+1);else if(n)for(var a=0;a<i;++a){var c=t.charCodeAt(a);c>255&&(zt(s),ge("String has UTF-16 code units that do not fit in 8 bits")),y[s+a]=c}else for(a=0;a<i;++a)y[s+a]=t[a];return null!==e&&e.push(zt,o),o},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:function(e){zt(e)}})},f:function(e,t,r){var i,n,o,s,a;r=he(r),2===t?(i=wt,n=kt,s=Dt,o=()=>T,a=1):4===t&&(i=Pt,n=Nt,s=Ot,o=()=>I,a=2),Te(e,{name:r,fromWireType:function(e){for(var r,n=I[e>>2],s=o(),c=e+4,l=0;l<=n;++l){var d=e+4+l*t;if(l==n||0==s[d>>a]){var u=i(c,d-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=d+t}}return zt(e),r},toWireType:function(e,i){"string"!=typeof i&&ge("Cannot pass non-string to C++ string type ".concat(r));var o=s(i),c=Gt(4+o+t);return I[c>>2]=o>>a,n(i,c+4,o+t),null!==e&&e.push(zt,c),c},argPackAdvance:8,readValueFromPointer:rt,destructorFunction:function(e){zt(e)}})},o:function(e,t){Te(e,{isVoid:!0,name:t=he(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},g:function(e,t,r,i){e=Lt[e],t=It.toValue(t),r=function(e){var t=Mt[e];return void 0===t?he(e):t}(r),e(t,r,null,i)},m:Tt,l:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i<e;++i)r[i]=xt(I[t+4*i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",o=Vt[n];if(void 0!==o)return o;for(var s=["retType"],a=[i],c="",l=0;l<e-1;++l)c+=(0!==l?", ":"")+"arg"+l,s.push("argType"+l),a.push(r[1+l]);var d="return function "+qe("methodCaller_"+n)+"(handle, name, destructors, args) {\n",u=0;for(l=0;l<e-1;++l)d+=" var arg"+l+" = argType"+l+".readValueFromPointer(args"+(u?"+"+u:"")+");\n",u+=r[l+1].argPackAdvance;for(d+=" var rv = handle[name]("+c+");\n",l=0;l<e-1;++l)r[l+1].deleteObject&&(d+=" argType"+l+".deleteObject(arg"+l+");\n");return i.isVoid||(d+=" return retType.toWireType(destructors, rv);\n"),d+="};\n",s.push(d),o=function(e){var t=Lt.length;return Lt.push(e),t}(gt(Function,s).apply(null,a)),Vt[n]=o,o},a:()=>{L("")},e:function(){return Date.now()},v:()=>y.length,A:(e,t,r)=>y.copyWithin(e,t,t+r),u:e=>{y.length,L("OOM")},y:(e,t)=>{var r=0;return Ft().forEach((function(i,n){var o=t+r;I[e+4*n>>2]=o,((e,t)=>{for(var r=0;r<e.length;++r)v[0|t++]=e.charCodeAt(r);v[0|t]=0})(i,o),r+=i.length+1})),0},z:(e,t)=>{var r=Ft();I[e>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),I[t>>2]=i,0},i:function(e){try{var t=le.getStreamFromFD(e);return ae.close(t),0}catch(r){if(void 0===ae||"ErrnoError"!==r.name)throw r;return r.errno}},x:function(e,t){try{var r=le.getStreamFromFD(e),i=r.tty?2:ae.isDir(r.mode)?3:ae.isLink(r.mode)?7:4;return v[t|0]=i,E[t+2>>1]=0,W=[0,(H=0,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[t+8>>2]=W[0],S[t+12>>2]=W[1],W=[0,(H=0,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[t+16>>2]=W[0],S[t+20>>2]=W[1],0}catch(n){if(void 0===ae||"ErrnoError"!==n.name)throw n;return n.errno}},B:function(e,t,r,i){try{var n=((e,t,r,i)=>{for(var n=0,o=0;o<r;o++){var s=I[t>>2],a=I[t+4>>2];t+=8;var c=ae.read(e,v,s,a,i);if(c<0)return-1;if(n+=c,c<a)break;void 0!==i&&(i+=c)}return n})(le.getStreamFromFD(e),t,r);return I[i>>2]=n,0}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return o.errno}},s:function(e,t,r,i,n){var o=function(e,t){return t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN}(t,r);try{if(isNaN(o))return 61;var s=le.getStreamFromFD(e);return ae.llseek(s,o,i),W=[s.position>>>0,(H=s.position,+Math.abs(H)>=1?H>0?+Math.floor(H/4294967296)>>>0:~~+Math.ceil((H-+(~~H>>>0))/4294967296)>>>0:0)],S[n>>2]=W[0],S[n+4>>2]=W[1],s.getdents&&0===o&&0===i&&(s.getdents=null),0}catch(a){if(void 0===ae||"ErrnoError"!==a.name)throw a;return a.errno}},h:function(e,t,r,i){try{var n=((e,t,r,i)=>{for(var n=0,o=0;o<r;o++){var s=I[t>>2],a=I[t+4>>2];t+=8;var c=ae.write(e,v,s,a,i);if(c<0)return-1;n+=c,void 0!==i&&(i+=c)}return n})(le.getStreamFromFD(e),t,r);return I[i>>2]=n,0}catch(o){if(void 0===ae||"ErrnoError"!==o.name)throw o;return o.errno}}};!function(){var e={a:Wt};function t(e,t){var r=e.exports;return _=(g=r).E,function(){var e=_.buffer;n.HEAP8=v=new Int8Array(e),n.HEAP16=E=new Int16Array(e),n.HEAP32=S=new Int32Array(e),n.HEAPU8=y=new Uint8Array(e),n.HEAPU16=T=new Uint16Array(e),n.HEAPU32=I=new Uint32Array(e),n.HEAPF32=A=new Float32Array(e),n.HEAPF64=C=new Float64Array(e)}(),R=g.H,function(e){k.unshift(e)}(g.F),M(),r}if(O(),n.instantiateWasm)try{return n.instantiateWasm(e,t)}catch(r){f("Module.instantiateWasm callback failed with error: "+r),i(r)}(function(e,t,r,i){return e||"function"!=typeof WebAssembly.instantiateStreaming||F(t)||"function"!=typeof fetch?j(t,r,i):fetch(t,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,r).then(i,(function(e){return f("wasm streaming compile failed: "+e),f("falling back to ArrayBuffer instantiation"),j(t,r,i)}))))})(p,x,e,(function(e){t(e.instance)})).catch(i)}();var Gt=e=>(Gt=g.G)(e),zt=e=>(zt=g.I)(e),$t=()=>($t=g.J)(),Jt=e=>(Jt=g.K)(e);n.__embind_initialize_bindings=()=>(n.__embind_initialize_bindings=g.L)();var qt,Kt=e=>(Kt=g.M)(e);function Yt(){function e(){qt||(qt=!0,n.calledRun=!0,!b&&(!n.noFSInit&&!ae.init.initialized&&ae.init(),ae.ignorePermissions=!1,G(k),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),function(){if(n.postRun)for("function"==typeof n.postRun&&(n.postRun=[n.postRun]);n.postRun.length;)e=n.postRun.shift(),D.unshift(e);var e;G(D)}()))}P>0||(function(){if(n.preRun)for("function"==typeof n.preRun&&(n.preRun=[n.preRun]);n.preRun.length;)e=n.preRun.shift(),w.unshift(e);var e;G(w)}(),P>0)||(n.setStatus?(n.setStatus("Running..."),setTimeout((function(){setTimeout((function(){n.setStatus("")}),1),e()}),1)):e())}if(n.dynCall_viiijj=(e,t,r,i,o,s,a,c)=>(n.dynCall_viiijj=g.N)(e,t,r,i,o,s,a,c),n.dynCall_jij=(e,t,r,i)=>(n.dynCall_jij=g.O)(e,t,r,i),n.dynCall_jii=(e,t,r)=>(n.dynCall_jii=g.P)(e,t,r),n.dynCall_jiji=(e,t,r,i,o)=>(n.dynCall_jiji=g.Q)(e,t,r,i,o),N=function e(){qt||Yt(),qt||(N=e)},n.preInit)for("function"==typeof n.preInit&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return Yt(),t.ready}})(),bU=CU,RU=class extends aU{constructor(){super(...arguments),this.sampleRate=0,this.channels=0}initialize(){return new Promise((e=>{let t={print:e=>console.log(e),printErr:e=>console.log("[JS] ERROR: ".concat(e)),onAbort:()=>console.log("[JS] FATAL: WASM ABORTED")};t.postRun=t=>{this.module=t,this.decoder=new this.module.AudioDecoder(this),e()},console.log("audio soft decoder initialize call"),bU(t)}))}configure(e){var t;this.config=e,this.decoder.setCodec(this.config.codec,null!=(t=this.config.description)?t:"")}decode(e){this.decoder.decode(e.data,e.timestamp)}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}audioInfo(e,t){this.sampleRate=e,this.channels=t;let r={sampleRate:e,channels:t,depth:16};this.emit("audioCodecInfo",r)}pcmData(e,t,r){if(!this.module)return;let i=[],n=0,o=0;for(let a=0;a<this.channels;a++){let r=this.module.HEAPU32[(e>>2)+a]>>2,o=this.module.HEAPF32.subarray(r,r+t);i.push(o),n+=o.length}let s=new Float32Array(n);this.emit("audioFrame",new AudioData({format:"f32-planar",sampleRate:this.sampleRate,numberOfChannels:this.channels,timestamp:r,numberOfFrames:t,data:i.reduce(((e,t)=>(e.subarray(o).set(t),o+=t.length,e)),s)}))}errorInfo(e){let t={errMsg:e};this.emit("error",t)}};Wb([iU(aU.INIT,"initialized")],RU.prototype,"initialize",1),Wb([iU("initialized","configured",{sync:!0})],RU.prototype,"configure",1),Wb([nU("configured")],RU.prototype,"decode",1),Wb([iU("configured","initialized",{sync:!0})],RU.prototype,"reset",1),Wb([iU([],"closed",{sync:!0})],RU.prototype,"close",1);var wU=class extends aU{initialize(){return $b(this,null,(function*(){this.decoder=new AudioDecoder({output:e=>{this.emit("audioFrame",e)},error:e=>{this.emit("error",e),this.close()}})}))}configure(e){this.config=e,this.decoder.configure(e)}decode(e){"configured"===this.decoder.state&&this.decoder.decode(new EncodedAudioChunk(e))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){this.decoder.close()}};Wb([iU([aU.INIT,"closed"],"initialized")],wU.prototype,"initialize",1),Wb([iU("initialized","configured",{sync:!0})],wU.prototype,"configure",1),Wb([nU("configured")],wU.prototype,"decode",1),Wb([iU([],aU.INIT,{sync:!0})],wU.prototype,"reset",1),Wb([iU([],"closed",{ignoreError:!0,sync:!0})],wU.prototype,"close",1);var kU=class extends VL{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 }"}),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,i=r.createTexture();return r.bindTexture(r.TEXTURE_2D,i),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),i}render(e){let t=this.context.ctx,r=this.width,i=this.height;return this.useProgram(),t.viewport(0,0,r,i),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,i,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,i/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,i/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}},DU=[e=>{e.codec="avc1.420028"},e=>{delete e.hardwareAcceleration}],PU=(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")},NU=class{constructor(e,t,r){Gb(this,"trackDoneOB"),Gb(this,"startOB"),Gb(this,"stopOB"),Gb(this,"decoder"),Gb(this,"videoContext"),Gb(this,"gop",0),Gb(this,"gop_helper",0),Gb(this,"waitFirstKeyFrame",!0),Gb(this,"startTimestamp",0),Gb(this,"startTime",0),Gb(this,"inputFrameCount",0),Gb(this,"decodedFrameCount",0),Gb(this,"downgradeLevel",0),Gb(this,"config"),Gb(this,"videoElement"),Gb(this,"type","wasm"),Gb(this,"renderer","2d"),Gb(this,"wasmOption",{yuvMode:!0}),Gb(this,"_decodeSink");let{kvStatManager:i,trtc:n}=e;if(this.wasmOption={yuvMode:"webgl"===r.renderer,wasmPath:r.wasmPath,workerMode:r.workerMode,canvas:r.canvas},this.config=r.config,this.videoElement=r.videoElement,this.type=r.type,this.renderer=r.renderer,this.trackDoneOB=nx(t,aU.INIT),this.stopOB=rx(this.trackDoneOB),"auto"===r.type){switch(r.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}this.startOB=rx();let o,s=rx();JL(s,dx(((e,r)=>(e!==r&&n.emit(_V.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,{userId:t.userId,streamType:"main"===t.streamType?"main":"sub",type:this.type,renderer:this.renderer,reason:o,prevState:e,state:r}),r)),"INITIALIZED"),cx(this.stopOB),Ex());JL(this.startOB,tx(0),_x((e=>{let r=this.pipe(t);return s.next("STARTING"),t.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer)),JL(r,cx(this.stopOB),Ex((()=>{t.stat.framesDecoded++}),(r=>{if(t.log.error(r),i.addFailedEvent({key:PU(this.type,this.renderer),error:r}),e>4)this.startOB.error(r);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":if("webgl"===this.renderer)this.changeRenderer("videoFrame")}this.startOB.next(e+1)}}))),JL(r,ax(1),yx(ox))})),cx(this.stopOB),Ex((()=>{t.player.handlePlaying("canvas"),s.next("STARTED")}),(e=>{o=e,s.next("FAILED"),n.emit(_V.ERROR,new Kx({code:Gx.OPERATION_FAILED,extraCode:5505}))}),(()=>{i.addSuccessEvent({key:PU(this.type,this.renderer)}),i.addSuccessEvent({key:514704})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,"videoFrame"===this.renderer&&!FN()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}decode(e){var t;if(this.inputFrameCount++,"configured"!==(null==(t=this.decoder)?void 0:t.state))return e;let r="key"===e.type,{timestamp:i}=e;if(r?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,!this.decoder||"configured"!==this.decoder.state)return e;{if(this.waitFirstKeyFrame){if(!r)return;this.waitFirstKeyFrame=!1,this.startTimestamp=i,this.startTime=Date.now()}let t=(i-this.startTimestamp)/90,n=Date.now()-this.startTime-t;switch(r&&((n<500?0:n/1e3|0)>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),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}this.decoder.decode(e)}}pipe(e){return ex()((t=>$b(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e,t;null==(e=this.decoder)||e.close(),null==(t=this.videoContext)||t.destroy()}));let{renderer:r,type:i}=this;try{switch(i){case"wasm":this.decoder=yO()?new fU(this.wasmOption):new hU(this.wasmOption);break;case"webCodecs":for(let e=0;e<=DU.length;e++){let{supported:r}=yield VideoDecoder.isConfigSupported(this.config);if(r)break;if(e===DU.length)return void t.error(3);DU[e](this.config)}this.decoder=new _U;break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",(e=>{this.decodedFrameCount++,t.next(e)})),this.decoder.on("error",(r=>{e.log.error(r),t.error("webCodecs"===i?4:8)})),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),"wasm"===i&&"webgl"===r){this.videoContext=new Nx({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(Nx.UNAVAILABLE,(r=>{e.log.error(r),t.error(7)}));let r=new kU(this.videoContext);this.decoder.on("videoCodecInfo",(e=>r.resize(e.width,e.height))),this.decoder.on("videoFrame",(e=>{[r.Y,r.U,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)}else if("videoFrame"===r){e.player.setCanvas();let r=new MediaStreamTrackGenerator({kind:"video"}),n=r.writable.getWriter();e.setInputMediaStreamTrack(r),this.decoder.on("videoFrame",(e=>{n.write(e)})),r.onmute=()=>{t.error("webCodecs"===i?5:9)}}else{this.videoContext=new Ox({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let t=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",(e=>{t.image=e,t.update()}));let r=new Ix(this.videoContext,{name:"remotePlayer",logger:e.log});t.connect(r),e.source=t,e.player.setCanvas(this.videoContext._canvas)}}catch(n){e.log.error(n),t.error("webCodecs"===i?2:6)}}))))}},OU={type:"object"},MU=class{constructor(e){this.core=e,Gb(this,"log"),Gb(this,"contextMap",new Map),Gb(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return"videoDecoder"}getGroup(e){return"".concat(e.track.userId).concat(e.track.streamType)}getName(){return MU.Name}getValidateRule(e){return OU}start(e){this.decodeProcessorMap.set(e.track,this.decode(e)),this.core.room.videoManager.addDecodeProcessor({processor:e=>{let{frame:t,track:r}=e;var i;return(null==(i=this.decodeProcessorMap.get(r))?void 0:i({frame:t,track:r}))||t},type:3})}decode(e){return t=>{let{frame:r,track:i}=t;if(i!==e.track)return r;if(this.contextMap.has(i))return this.contextMap.get(i).decode(r);let n=new NU(this.core,i,e);return JL(n.trackDoneOB,ax(1),Ex((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:i})}))),this.contextMap.set(i,n),n.decode(r)}}stop(e){let t=this.contextMap.get(e.track);t&&(t.close("stop"),this.contextMap.delete(e.track)),0===this.contextMap.size&&this.core.room.videoManager.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 NU(this.core,e.track,e))}}},LU=MU;Gb(LU,"Name","VideoDecoder");var xU,VU=0,UU=class{constructor(e){this.core=e,Gb(this,"_core"),Gb(this,"log"),Gb(this,"dumpLocalVideoMap",{}),Gb(this,"dumpRemoteVideoMap",{}),Gb(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++VU)}),this.log.info("created")}getName(){return UU.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 $b(this,null,(function*(){!new URLSearchParams(location.search).has("trtcDebug")||(yield this.openDebugDiaLog(),this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED&&this.addVideoProcessor())}))}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return $b(this,null,(function*(){try{if(xU)yield xU;else{let e=Date.now();xU=this.loadScript("https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@".concat(pR,".js")),yield xU,this.log.info("download debug dialog script cost: ".concat(Date.now()-e,"ms"))}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(yN){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(yN))}}))}closeDebugDiaLog(){var e;null==(e=this.dialog)||e.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):this.encodeVideoDump,type:2}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):this.decodeVideoDump,type:2})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:2}),this._core.room.videoManager.removeDecodeProcessor({type:2})}encodeVideo(e){let{frame:t,mediaType:r}=e;return this.encodeVideoDump({frame:t,onDump:()=>{if(!r)return;let e=2===r?"sub":"main",i=this.dumpLocalVideoMap[e];i&&(i.data.push(t.data),i.duration>0&&Date.now()-i.startTimestamp>1e3*i.duration&&i.onDumpEnd())}})}decodeVideo(e){let{frame:t,track:r}=e;return this.decodeVideoDump({frame:t,onDump:()=>{if(!r)return;let e=this.dumpRemoteVideoMap["".concat(r.userId,"-").concat(r.streamType)];e&&(e.data.push(t.data),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}})}encodeVideoDump(e){let{frame:t,onDump:r}=e;return null==r||r(),t}decodeVideoDump(e){let{frame:t,onDump:r}=e;return null==r||r(),t}loadScript(e){return new Promise(((t,r)=>{this.log.info("loading debug dialog from ".concat(e));let i=document.createElement("script");i.type="text/javascript",i.onload=t,i.onerror=r,i.crossOrigin="anonymous",i.src=e,document.head.append?document.head.append(i):document.getElementsByTagName("head")[0].appendChild(i)}))}},FU=UU;Gb(FU,"Name","Debug"),Gb(FU,"autoStart",!0),Wb([GO({settings:{timeout:3e3,retries:3},onError(e,t,r){var i;null!=(i=null==e?void 0:e.message)&&i.includes("timeout")?t():r(e)}})],FU.prototype,"loadScript",1);var BU=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},jU=class{constructor(e,t,r){Gb(this,"trackDoneOB"),Gb(this,"startOB"),Gb(this,"stopOB"),Gb(this,"inputFrameCount",0),Gb(this,"decodedFrameCount",0),Gb(this,"type","auto"),Gb(this,"config"),Gb(this,"decoder"),Gb(this,"_decodeSink");let{kvStatManager:i,trtc:n}=e;this.config=r.config,this.trackDoneOB=nx(t,aU.INIT),this.stopOB=rx(this.trackDoneOB),this.startOB=rx(),"auto"===r.type?this.type="webCodecs":this.type=r.type;let o=rx();JL(this.startOB,tx(0),_x((e=>{let r=this.pipe(t);return o.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),JL(r,cx(this.stopOB),Ex((()=>{}),(r=>{t.log.error(r),i.addFailedEvent({key:BU(this.type),error:r}),e>4?this.startOB.error(r):this.startOB.next(e+1)}))),JL(r,ax(1),yx(ox))})),cx(this.stopOB),Ex((()=>{t.player.setOutput(),o.next("STARTED")}),(e=>{o.next("FAILED")}),(()=>{i.addSuccessEvent({key:BU(this.type)}),i.addSuccessEvent({key:504702})})))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return ex()((t=>$b(this,null,(function*(){this._decodeSink=t,t.defer((()=>{var e;null==(e=this.decoder)||e.close()}));let{type:r}=this;try{if("webCodecs"===r)this.decoder=new AudioDecoder({error:r=>{e.log.error(r),t.error(4)},output:r=>{this.decodedFrameCount++,t.next(r),e.player.write(r)}});this.decoder.configure(this.config)}catch(_R){e.log.error(_R),t.error("webCodecs"===r?2:6)}}))))}decodeFrame(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},HU={type:"object"},WU=class{constructor(e){this.core=e,Gb(this,"log"),Gb(this,"contextMap",new Map),Gb(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return WU.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return WU.Name}getValidateRule(e){return HU}start(e){let{track:t}=e;this.decodeProcessorMap.set(t,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:e=>{let{frame:t,track:r}=e;return this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t},type:3})}decode(e){return t=>{let{frame:r,track:i}=t;if(i!==e.track)return r;if(this.contextMap.has(i))return this.contextMap.get(i).decodeFrame(r);let n=new jU(this.core,i,e);return JL(n.trackDoneOB,ax(1),Ex((()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:i})}))),this.contextMap.set(i,n),n.decodeFrame(r)}}stop(e){let{track:t}=e,r=this.contextMap.get(t);!r||(r.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new jU(this.core,e.track,e))}}},GU=WU;Gb(GU,"Name","AudioDecoder");var zU=0,$U=new Set,JU=null;mR("5.8.7-beta.9");var qU={RtcError:Kx,ErrorCode:Gx,ErrorCodeDictionary:zx},KU=class extends rR.EventEmitter{constructor(e,t){super(),Gb(this,"_room"),Gb(this,"_eventListened",new Set),Gb(this,"_localVideoTrack",null),Gb(this,"_localAudioTrack",null),Gb(this,"_localScreenTrack",null),Gb(this,"_localScreenAudioTrack",null),Gb(this,"_localVideoConfig",null),Gb(this,"_localScreenConfig",null),Gb(this,"_localAudioConfig",null),Gb(this,"_remoteVideoConfigMap",new Map),Gb(this,"_remoteAudioConfigMap",new Map),Gb(this,"_remoteAudioVolumeMap",new Map),Gb(this,"_remoteAudioMuteMap",new Map),Gb(this,"_mediaTrackMap",new WeakMap),Gb(this,"_log",pN.createLogger({id:"t".concat(++zU)})),Gb(this,"_plugins",new Map),Gb(this,"_networkQuality",null),Gb(this,"_speakerId"),Gb(this,"_getPCMAbortCtrl"),this._room=new e(Ub({logger:this._log,frameWorkType:KU.frameWorkType},t)),this._log.debug("TRTC.create() ".concat(JSON.stringify(t,((e,t)=>"plugins"===e?t.map((e=>e.Name)):t)))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}}),t.plugins&&t.plugins.forEach((e=>{this._use(e,t.assetsPath)})),this._use(MV,t.assetsPath),this._use(UV,t.assetsPath),this._use(GU,t.assetsPath),this._use(LU,t.assetsPath),this._use(FU),t.enableSEI&&mO&&this._use(YV),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(_V.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{this._log.error(new Kx({code:Gx.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:r}=e;e.emit=function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];try{return r.apply(e,n)}catch(_R){let r=HD({key:Qw.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return pN.warn("".concat(r,"\n\n").concat(_R.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;Hx&&(Hx=!1,5!==pN.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(RR,"/en/index.html")),console.info("* Changelog: ".concat(RR,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),pN.info("TRTC Web SDK Version:",pR),pN.info("UA:",navigator.userAgent),pN.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),ND().then((e=>{e&&pN.info(PD)})))}();let r=new KU(e,t||{});return $U.add(r),r}get room(){return this._room}_listenEvents(){jO(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(_V.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(_V.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(_V.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(_V.ERROR,Kx.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(_V.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e;let t=Fb(Ub({},e),{uplinkRTT:Math.min(e.uplinkRTT,qw),downlinkRTT:Math.min(e.downlinkRTT,qw)});this.emit(_V.NETWORK_QUALITY,t)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{jO(t,t).add("player-state-changed",(r=>{let i=Fb(Ub({},r),{userId:e.userId});t.kind===WR.VIDEO&&(i.streamType=vV(t.streamType)),this.emit(t.kind===WR.AUDIO?_V.AUDIO_PLAY_STATE_CHANGED:_V.VIDEO_PLAY_STATE_CHANGED,i)})).add("error",(e=>{e.getCode()===nR.PLAY_NOT_ALLOWED&&this.emit(_V.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{HO(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:r}=e,{userId:i}=r,n=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=r;s||this._remoteAudioConfigMap.delete(i),a||this._remoteVideoConfigMap.delete("".concat(i,"_","main")),r.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(i,"_","sub")),n!==s&&(this.emit(s?_V.REMOTE_AUDIO_AVAILABLE:_V.REMOTE_AUDIO_UNAVAILABLE,{userId:i}),s?this._onAudioAvailable({userId:i}):this._onAudioUnavailable({userId:i,muteState:r})),o!==a&&(this.emit(a?_V.REMOTE_VIDEO_AVAILABLE:_V.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"main"}),a?this._onVideoAvailable({userId:i,streamType:"main"}):this._onVideoUnavailable({userId:i,streamType:"main"})),t.hasAuxiliary!==r.hasAuxiliary&&(this.emit(r.hasAuxiliary?_V.REMOTE_VIDEO_AVAILABLE:_V.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"sub"}),r.hasAuxiliary?this._onVideoAvailable({userId:i,streamType:"sub"}):this._onVideoUnavailable({userId:i,streamType:"sub"}))})).add("sei-message",(e=>{this.emit(_V.SEI_MESSAGE,Fb(Ub({},e),{streamType:vV(e.streamType)}))})).add("firewall-restriction",(()=>{this.emit(_V.ERROR,new Kx({code:Gx.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(e=>{var t,r,i,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(r=this._networkQuality)?void 0:r.uplinkRTT)||(null==(i=this._networkQuality)?void 0:i.downlinkRTT)||0,qw),upLoss:(null==(n=this._networkQuality)?void 0:n.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/Xw},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/Xw},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(_V.STATISTICS,l)})).add("custom-message",(e=>{this.emit(_V.CUSTOM_MESSAGE,e)})),jO(this,xM).add("audioInputAdded",(e=>{this.emit(_V.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(_V.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(_V.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(_V.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>$b(this,null,(function*(){if(this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),JU&&JU.deviceId===Vw){let e=(yield HM()).find((e=>e.deviceId===Vw));e&&JU.groupId!==e.groupId&&(JU=e,this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>$b(this,null,(function*(){this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield HM())[0];if(!t||!JU||JU.groupId===t.groupId)return;let r=JU.deviceId===e.deviceId,i=JU.deviceId===Vw&&JU.deviceId===t.deviceId;(r||i)&&(JU=t,this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name))return void this._log.warn("duplicate install plugin",e.Name);let r=new e(SV.call(this,{TRTC:KU,room:this._room,errorModule:qU,assetsPath:t}));this._plugins.set(e.Name,r),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return $b(this,null,(function*(){var t,r;let{scene:i="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!DP(e.proxy)&&e.proxy.turnServer&&(null==(r=(t=this._room).setTurnServer)||r.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,NP(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,i,KU.frameWorkType),this._checkTrackToPublish(),jV.start()}))}exitRoom(){return $b(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return $b(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(){HO(this),this.removeAllListeners(),this._room.destroy(),$U.delete(this),0===$U.size&&jV.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((e=>{var t;return null==(t=e.destroy)?void 0:t.call(e)}))}startLocalAudio(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:r=!0,mute:i,option:n}=t,o=new yL(e._room.audioManager),s={},a={muted:!0};n&&(kP(n.microphoneId)?kP(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&PP(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),kP(n.profile)||(DP(n.profile)?BR[n.profile]&&o.setProfile(BR[n.profile]):o.setProfile(n.profile)),PP(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),kP(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),kP(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),kP(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(_V.ERROR,new Kx({code:Gx.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(_V.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let r;t.error&&(r=Kx.convertFrom(t.error)),e.emit(_V.PUBLISH_STATE_CHANGED,Fb(Ub({},t),{error:r}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),kP(i)||o.setMute(i),jO(o,o).add("player-state-changed",(t=>{e.emit(_V.AUDIO_PLAY_STATE_CHANGED,Fb(Ub({},t),{userId:""}))})),e.listeners(_V.AUDIO_FRAME).length>0&&(e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(KU.EVENT.AUDIO_FRAME,{data:t})}))),e._getPCMAbortCtrl&&o.on("input-media-track-changed",(()=>{e._getPCMAbortCtrl&&(e._getPCMAbortCtrl.abort("inputMediaTrackChanged"),e._getPCMAbortCtrl=e._room.audioManager.getPCM((t=>{e.emit(KU.EVENT.AUDIO_FRAME,{data:t})})))})),r&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=Fb(Ub({},t),{publish:r}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return $b(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:i}=e,n={};i&&(i.microphoneId?yield this._localAudioTrack.switchDevice(i.microphoneId):kP(i.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(i.audioTrack)),kP(i.captureVolume)||this._localAudioTrack.setCaptureVolume(i.captureVolume),kP(i.earMonitorVolume)||(n.muted=!(i.earMonitorVolume>0),n.volume=i.earMonitorVolume),yield this._localAudioTrack.update3A(i)),this._room.isJoined&&!kP(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),kP(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),YP(this._localAudioConfig,e)}))}stopLocalAudio(){return $b(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),HO(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))}))}startLocalVideo(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:r,publish:i=!0,mute:n,option:o}=t,s=new SL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:kP(o.useFrontCamera)?kP(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?WR.FACING_MODE_USER:WR.FACING_MODE_ENVIRONMENT,kP(o.profile)||(DP(o.profile)?jR[o.profile]&&s.setProfile(jR[o.profile]):s.setProfile(o.profile)),kP(o.fillMode)||(c.objectFit=o.fillMode),kP(o.mirror)||(c.mirror=o.mirror),kP(o.small)||(QN()?DP(o.small)?s.small=jR[o.small]:!0===o.small?s.small=jR["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(_V.ERROR,new Kx({code:Gx.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(_V.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let r;t.error&&(r=Kx.convertFrom(t.error)),e.emit(_V.PUBLISH_STATE_CHANGED,Fb(Ub({},t),{error:r}))})),e._listenOutputTrackChanged(s),yield s.capture(a),kP(n)||(yield s.setMute(n)),s.mediaTrack){if(null!=o&&o.qosPreference){let e=yV(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=yV(Wx.QOS_PREFERENCE_SMOOTH));s.outMediaTrack&&(s.outMediaTrack.contentHint=s.mediaTrack.contentHint)}jO(s,s).add("player-state-changed",(t=>{e.emit(_V.VIDEO_PLAY_STATE_CHANGED,Fb(Ub({},t),{userId:"",streamType:"main"}))})),i&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=Fb(Ub({},t),{view:r,publish:i}),yield e._updateVideoPlayOption({view:r,playOption:c,track:s})}()}))}updateLocalVideo(e){return $b(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:i,option:n}=e,o={};if(n){if(kP(n.profile)||(DP(n.profile)?jR[n.profile]&&this._localVideoTrack.setProfile(jR[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&kP(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):kP(n.useFrontCamera)?kP(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?WR.FACING_MODE_USER:WR.FACING_MODE_ENVIRONMENT),kP(n.fillMode)||(o.objectFit=n.fillMode),kP(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=yV(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=e)}if(n.small){let e=!this._localVideoTrack.small;QN()?(!0===n.small?this._localVideoTrack.small=jR["120p"]:DP(n.small)?this._localVideoTrack.small=jR[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===n.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!kP(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),kP(i)||(yield this._localVideoTrack.setMute(i)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),YP(this._localVideoConfig,e)}))}stopLocalVideo(){return $b(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),HO(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:r=null,publish:i=!0,option:n}=t,o=new bL(e._room.videoManager);o.on("4",(t=>{let r;t.error&&(r=Kx.convertFrom(t.error)),e.emit(_V.PUBLISH_STATE_CHANGED,Fb(Ub({},t),{error:r}))})),e._listenOutputTrackChanged(o),"main"===t.streamType&&(o.mediaType=4);let s=null,a={},c={};n&&(kP(n.profile)||(DP(n.profile)?HR[n.profile]&&o.setProfile(HR[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),kP(n.fillMode)||(c.objectFit=n.fillMode),n.videoTrack&&(a.videoTrack=n.videoTrack),n.audioTrack&&(a.audioTrack=n.audioTrack),n.captureElement&&(a.captureElement=n.captureElement),n.preferDisplaySurface&&(a.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(a);if(null!=n&&n.qosPreference){let e=yV(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=yV(Wx.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(WR.ENDED,(()=>{e._stopScreenShare(),e.emit(_V.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new RL(e._room.audioManager),yield s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),jO(o,o).add("player-state-changed",(t=>{e.emit(_V.VIDEO_PLAY_STATE_CHANGED,Fb(Ub({},t),{userId:"",streamType:"sub"}))})),i&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=Fb(Ub({},t),{view:r,publish:i}),yield e._updateVideoPlayOption({view:r,playOption:c,track:o})}()}))}updateScreenShare(e){return $b(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:i}=e,n={};if(i&&(kP(i.fillMode)||(n.objectFit=i.fillMode),i.qosPreference)){let e=yV(i.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!kP(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((()=>{}))),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch((()=>{})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((()=>{})))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),YP(this._localScreenConfig,e)}))}stopScreenShare(){return $b(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return $b(this,null,(function*(){let{view:t,userId:r,streamType:i,option:n}=e,o="".concat(r,"_").concat(i);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(r,", streamType:").concat(i));let s=this._room.remotePublishedUserMap.get(r);if(!s)return;let a={},c="main"===i?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),n&&(kP(n.fillMode)||(a.objectFit=n.fillMode),kP(n.mirror)||(a.mirror=n.mirror),a.canvasRender=n.canvasRender,"main"===i&&!kP(n.small)&&(s.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,c.user)));this._log.info("remote video will fall back when decode failed"),JL(nx(c,"decode-failed"),cx(nx(c,aU.INIT)),Ex((()=>{this.startPlugin(LU.Name,{type:"auto",renderer:"videoFrame",track:c,config:{codec:"avc1.420028"},fallback:"wasm"})}),(e=>{this._log.error("fallback",e)}),(()=>this._log.info("fallback complete")))),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(o,{config:e}),n&&!kP(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return $b(this,null,(function*(){var t,r;let{view:i,userId:n,streamType:o,option:s}=e,a="".concat(n,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(n))return;let l={};s&&(kP(s.fillMode)||(l.objectFit=s.fillMode),kP(s.mirror)||(l.mirror=s.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);if("main"===o&&(null==u?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),"sub"===o&&(null==u?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack),!d)return;let{config:h}=c;"main"===o&&s&&!kP(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:i,playOption:l,track:d,prevConfig:h}),YP(h,e);let p=kP(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=kP(i)?h.view:i,f=kP(null==s?void 0:s.viewRoot)?null==(r=h.option)?void 0:r.viewRoot:s.viewRoot;this._observeView({remoteTrack:d,view:m,receiveWhenViewVisible:p,viewRoot:f})}))}stopRemoteVideo(e){return $b(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return $b(this,null,(function*(){let r=[],i=this._room.remotePublishedUserMap.get(e.userId);if(i){let{muteState:t,remoteVideoTrack:n,remoteAuxiliaryTrack:o}=i;"main"===e.streamType&&(n.stop(),t.hasVideo&&r.push(n)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&r.push(o))}for(let e of r)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));let n=this._remoteVideoConfigMap.get("".concat(e.userId,"_").concat(e.streamType));n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return $b(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&!this._remoteAudioConfigMap.has(t.userId)&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let r of e)this._remoteAudioVolumeMap.set(r.userId,t),r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return $b(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return $b(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return $b(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)||(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===KU.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(KU.EVENT.AUDIO_FRAME,{data:e})})),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",(()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM((e=>{this.emit(KU.EVENT.AUDIO_FRAME,{data:e})})))})))),this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];try{gV.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(r)))}catch(_R){}return super.emit(e,...r)}off(e,t,r){var i,n;return this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners(),null==(i=this._getPCMAbortCtrl)||i.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===KU.EVENT.AUDIO_FRAME&&(null==(n=this._getPCMAbortCtrl)||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},r=null,i="main",n=!1;if(DP(t)?e=t:(e=t.userId,n=!0===t.processed,t.streamType&&(i=t.streamType)),e){let t=this._room.remotePublishedUserMap.get(e);t&&(r=t.remoteAudioTrack)}else r="sub"===i?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:r="main",processed:i=!1}=e,n=null;if(""===t)"main"===r&&this._localVideoTrack&&(n=this._localVideoTrack),"sub"===r&&this._localScreenTrack&&(n=this._localScreenTrack);else{let e=this._room.remotePublishedUserMap.get(t);e&&(n="main"===r?e.remoteVideoTrack:e.remoteAuxiliaryTrack)}return n?i&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{userId:t,streamType:r="main"}=e;if(t){let e=this._room.remotePublishedUserMap.get(t);if("main"===r&&(null==e?void 0:e.muteState.hasVideo))return e.remoteVideoTrack.getVideoFrame();if("sub"===r&&(null==e?void 0:e.muteState.hasAuxiliary))return e.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===r&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===r&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(r=this._localScreenAudioTrack)||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}setCurrentSpeaker(e){return $b(this,null,(function*(){(yield HM()).forEach((t=>{t.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),JU=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')}))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return $b(this,null,(function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let i={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let r=this._remoteAudioVolumeMap.get(t),o=PP(r)?r:100;i.volume=o,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),JL(nx(n,"decode-failed"),cx(nx(n,aU.INIT)),Ex((()=>{this.startPlugin(GU.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),yield this._updateAudioPlayOption({playOption:i,track:n})}catch(o){throw this._remoteAudioConfigMap.delete(t),o}this._emitTrackEvent(n)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return $b(this,null,(function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.get(r.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return $b(this,arguments,(function(e){let{view:t,playOption:r,track:i,prevConfig:n}=e;return function*(){if(i.setMirror(r.mirror),kP(t)&&n&&n.view&&!$P(r)){let e=QP(n.view);e.length>0&&(yield i.play(e,r))}if(!kP(t)){let e=QP(t);e.length>0?yield i.play(e,r):i.stop()}}()}))}_updateAudioPlayOption(e){return $b(this,arguments,(function(e){let{playOption:t={},track:r,prevConfig:i}=e;return function*(){if(!r.isPlayCalled)try{yield r.play(null,t)}catch(gR){}kP(t.muted)||r.setPlayerMute(t.muted),kP(t.volume)||r.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e,!1)))}_emitTrackEvent(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(_V.TRACK,{userId:r,streamType:vV(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,r;let i=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&i.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&i.push(this._localVideoTrack),null!=(r=this._localScreenConfig)&&r.publish&&(this._localScreenTrack&&i.push(this._localScreenTrack),this._localScreenAudioTrack&&i.push(this._localScreenAudioTrack)),0!==i.length)return this._room.publish(...i).catch((()=>{}))}_observeView(e){let{remoteTrack:t,view:r,receiveWhenViewVisible:i=!1,viewRoot:n}=e;if(kP(r))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(vV(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===r||MP(r)&&0===r.length||!i)return null==s||s.disconnect(),void(t.isSubscribed||this._room.subscribe(t).catch((()=>{})));let a=o.visibleViewMap||new Map,c=-1;(!s||s.root!==n)&&(null==s||s.disconnect(),a.clear(),s=new IntersectionObserver((e=>{e.forEach((e=>{a.set(e.target,e.isIntersecting)})),clearTimeout(c),c=window.setTimeout((()=>{[...a.values()].find((e=>e))?t.isSubscribed||this._room.subscribe(t).catch((()=>{})):t.isSubscribed&&this._room.unsubscribe(t).catch((()=>{}))}),200)}),{root:n}));let l=new Set(QP(r));a.forEach(((e,t)=>{l.has(t)||(s.unobserve(t),a.delete(t))})),l.forEach((e=>{a.set(e,!0),s.observe(e)})),s.takeRecords().forEach((e=>{a.set(e.target,e.isIntersecting)})),o.visibleViewMap=a,o.observer=s}_exitRoom(){return $b(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",r=e.split("_".concat(t))[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){let t=IV.get(e);t&&(t.forEach((e=>clearTimeout(e))),IV.delete(e))}(this),this._room.remotePublishedUserMap.forEach((e=>{HO(e.remoteAudioTrack),HO(e.remoteVideoTrack),HO(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return $b(this,null,(function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield null==(e=this._room)?void 0:e.unpublish(...t).catch((()=>{}))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),HO(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return $b(this,null,(function*(){if(JU&&!VM(JU))this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:JU});else{let e=yield HM();if(e[0]&&!VM(e[0]))JU=e[0],this.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!JU||VM(JU))&&(this._initActiveSpeaker(),KD.off("102",this._initActiveSpeaker))};KD.on("102",e)}}}))}_onAudioAvailable(e){let{userId:t}=e,r=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===r||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:t}).catch((()=>{}))}_onVideoAvailable(e){let{userId:t,streamType:r}=e;if(!this._room.autoReceiveVideo)return;let i=this._room.remotePublishedUserMap.get(t);if(i){let e="main"===r?i.remoteVideoTrack:i.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}_onAudioUnavailable(e){let{userId:t,muteState:r}=e;r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((()=>{}))}_onVideoUnavailable(e){let{userId:t,streamType:r}=e;this._stopRemoteVideo({userId:t,streamType:r},!1).catch((()=>{}))}sendSEIMessage(e,t){var r;let i=this._plugins.get("SEI");i&&(i.update({buffer:e,options:Fb(Ub({seiPayloadType:243},t),{small:!(null==(r=this._localVideoTrack)||!r.small)})}),DN.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;null==(r=(t=this._room).sendCustomMessage)||r.call(t,e),DN.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){pN.setLogLevel(e),kP(t)||(t?pN.enableUploadLog():pN.disableUploadLog())}static isSupported(){return HN()}static getCameraList(){return BM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return FM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return HM(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return $b(this,null,(function*(){(yield HM()).forEach((t=>{t.deviceId===e&&($U.forEach((r=>{r._setCurrentSpeaker(e),r.emit(_V.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),JU=t)}))}))}static _addKVStat(e){let{type:t,key:r,value:i,base:n,useUV:o,version:s}=e;switch(s&&(kN.version=s),t){case"count":kN.addCount({key:r,useUV:o});break;case"enum":kN.addEnum({key:r,value:i,useUV:o});break;case"number":kN.addNumber({key:r,value:i,split:n})}}},YU=KU;Gb(YU,"_loggerManager",pN),Gb(YU,"EVENT",_V),Gb(YU,"ERROR_CODE",Gx),Gb(YU,"TYPE",Wx),Gb(YU,"frameWorkType",30),Wb([wV({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"}})})],YU.prototype,"use",1),Wb([AV(nV.TRTC.enterRoom),pV("room",((e,t)=>{let[r]=e,[i]=t;return(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId})),sL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),wV()],YU.prototype,"enterRoom",1),Wb([wV()],YU.prototype,"exitRoom",1),Wb([AV(nV.TRTC.switchRole),mV("room",{merge:(e,t)=>t}),wV()],YU.prototype,"switchRole",1),Wb([wV()],YU.prototype,"destroy",1),Wb([AV(nV.TRTC.startLocalAudio),pV("audio",((e,t)=>{let[r]=e,[i]=t;var n,o;return(null==(n=null==r?void 0:r.option)?void 0:n.microphoneId)===(null==(o=null==i?void 0:i.option)?void 0:o.microphoneId)})),wV()],YU.prototype,"startLocalAudio",1),Wb([AV(nV.TRTC.updateLocalAudio),mV("audio",{debounce:{delay:200,getKey:()=>"".concat(zU,"-localAudio"),isNeedToDebounce:e=>{var t;return!kP(null==(t=e.option)?void 0:t.captureVolume)}}}),wV()],YU.prototype,"updateLocalAudio",1),Wb([fV("audio"),wV()],YU.prototype,"stopLocalAudio",1),Wb([AV(nV.TRTC.startLocalVideo),pV("video",((e,t)=>{let[r]=e,[i]=t;var n,o;return(null==(n=null==r?void 0:r.option)?void 0:n.cameraId)===(null==(o=null==i?void 0:i.option)?void 0:o.cameraId)})),wV()],YU.prototype,"startLocalVideo",1),Wb([AV(nV.TRTC.updateLocalVideo),mV("video"),wV()],YU.prototype,"updateLocalVideo",1),Wb([fV("video"),wV()],YU.prototype,"stopLocalVideo",1),Wb([AV(nV.TRTC.startScreenShare),pV("screen",(()=>!0)),wV()],YU.prototype,"startScreenShare",1),Wb([AV(nV.TRTC.updateScreenShare),mV("screen"),wV()],YU.prototype,"updateScreenShare",1),Wb([wV()],YU.prototype,"stopScreenShare",1),Wb([AV(nV.TRTC.startRemoteVideo),pV((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),wV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],YU.prototype,"startRemoteVideo",1),Wb([AV(nV.TRTC.updateRemoteVideo),mV((e=>"v".concat(e.userId).concat(e.streamType))),wV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],YU.prototype,"updateRemoteVideo",1),Wb([AV(nV.TRTC.stopRemoteVideo),sL((e=>function(t){return $b(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)}))})),wV({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],YU.prototype,"stopRemoteVideo",1),Wb([fV((e=>"v".concat(e.userId).concat(e.streamType)))],YU.prototype,"_stopRemoteVideo",1),Wb([AV(...nV.TRTC.muteRemoteAudio),wV({getRemoteId:e=>e})],YU.prototype,"muteRemoteAudio",1),Wb([CV(...nV.TRTC.setRemoteAudioVolume),function(e,t){return sL(((r,i)=>function(){for(var i=arguments.length,n=new Array(i),o=0;o<i;o++)n[o]=arguments[o];let s=IV.get(this);s||(s=new Map,IV.set(this,s));let a=t(...n),c=s.get(a);if(!c||c<=0){r.apply(this,n);let t=setTimeout((()=>{var e;null==(e=IV.get(this))||e.delete(a)}),e);s.set(a,t)}else{clearTimeout(c);let t=window.setTimeout((()=>{var e;r.apply(this,n),null==(e=IV.get(this))||e.delete(a)}),e);s.set(a,t)}}))}(200,(e=>e)),wV({getRemoteId:e=>e})],YU.prototype,"setRemoteAudioVolume",1),Wb([kV("start"),oL((e=>{var t;return null==(t=e.afterStart)?void 0:t.call(e)})),pV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),wV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>IN[e.getName()],ignoreLog:e=>"Debug"===e.getName()})],YU.prototype,"startPlugin",1),Wb([kV("update"),mV(((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t))),wV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>AN[e.getName()]})],YU.prototype,"updatePlugin",1),Wb([kV("stop"),fV(((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),i=e.getAlias();return"*"===r?new RegExp("".concat(i,".*")):i+r})),wV({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>CN[e.getName()]})],YU.prototype,"stopPlugin",1),Wb([CV(...nV.TRTC.enableAudioVolumeEvaluation)],YU.prototype,"enableAudioVolumeEvaluation",1),Wb([wV()],YU.prototype,"getVideoSnapshot",1),Wb([wV()],YU.prototype,"_setCurrentSpeaker",1),Wb([pV((e=>"a".concat(e.userId)),(()=>!0))],YU.prototype,"_startRemoteAudio",1),Wb([sL((e=>function(t){return $b(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(Fb(Ub({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),fV((e=>"a".concat(e.userId)))],YU.prototype,"_stopRemoteAudio",1),Wb([fV("room")],YU.prototype,"_exitRoom",1),Wb([fV("screen")],YU.prototype,"_stopScreenShare",1),Wb([AV(...nV.TRTC.sendSEIMessage),Bx({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].byteLength}})],YU.prototype,"sendSEIMessage",1),Wb([AV(nV.TRTC.sendCustomMessage),Bx({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],YU.prototype,"sendCustomMessage",1),Wb([AV(nV.TRTC.create)],YU,"_create",1);var XU=YU,QU=class{constructor(){this._set=new Set,KD.on(uN.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:r}=e;if("rtc"===t.scene)return;let i=this.getKey(t.userId,r||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(i)}delete(e){let{room:t,roomId:r}=e;if("rtc"===t.scene)return;let i=this.getKey(t.userId,t.roomId||r,t.sdkAppId,t.useStringRoomId);this._set.delete(i)}getKey(e,t,r,i){return"".concat(r,"_").concat(t,"_").concat(e,"_").concat(i)}isJoined(e){let{userId:t,roomId:r,sdkAppId:i,room:n}=e;return"rtc"!==n.scene&&this._set.has(this.getKey(t,r,i,n.useStringRoomId))}};function ZU(){return $b(this,null,(function*(){let e,t;try{let t=yield FM();e=t&&t.length}catch(u){}try{let e=yield BM();t=e&&e.length}catch(u){}let r={microphone:e,camera:t},{isH264EncodeSupported:i,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=_N.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:i,h264Decode:o,vp8Encode:n,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:r},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};XD.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),XD.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var eF=Hb(Jb()),tF="1",rF="2",iF="3",nF="4",oF="5",sF="6",aF={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},cF=[aF.UPDATE_REMOTE_MUTE_STAT,aF.UPLINK_NETWORK_STATS,aF.USER_LIST_RES,aF.MUTE_RESULT,aF.SERVER_FIRST_PACKAGE_RECEIVED,aF.RECEIVE_CUSTOM_MSG],lF={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},dF="publish_change",uF="join",hF="leave",pF="quality_report",mF="mute_uplink",fF="publish",_F="publish_state_change",gF="unpublish",vF="subscribe",yF="unsubscribe",EF="subscribe_change",TF="start_publishing",SF="stop_publishing",IF="start_push_user_cdn",AF="stop_push_user_cdn",CF="start_mcu_mix",bF="stop_mcu_mix",RF="start_publish_cdn_stream",wF="update_publish_cdn_stream",kF="stop_publish_cdn_stream",DF="get_user_list",PF="change_role",NF="update_constraint_config",OF="rebuild_pc",MF="join/v2",LF="publish/v2",xF="subscribe/v3",VF="ability_status_report",UF="reconnect",FF="channel_msg",BF=new Set;var jF=class extends eF.default{constructor(e){var t,r;super(),Gb(this,"room"),Gb(this,"url"),Gb(this,"backupUrl"),Gb(this,"race"),Gb(this,"destroyed",!1),Gb(this,"_socketInUse"),Gb(this,"_socket"),Gb(this,"_backupSocket"),Gb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),Gb(this,"_currentState","DISCONNECTED"),Gb(this,"_isReconnecting",!1),Gb(this,"_seq",0),Gb(this,"_log"),Gb(this,"_lastMessageTime",-1),Gb(this,"_connnectStartTime",-1),Gb(this,"_stopConnectRetry"),Gb(this,"bytesSent",0),Gb(this,"bytesReceived",0),Gb(this,"keepAlive",!1),Gb(this,"signalDomainWhenUnifiedProxy"),Gb(this,"stopKeepAliveTimeout"),Gb(this,"rtt",0),this.room=e.room,this.race=!!kP(e.race)||e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,((null==(r=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:r.keepAliveClient)||0)-BF.size>0&&this.room.enableSPC&&(this.keepAlive=!0,BF.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=pN.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connnectStartTime=HP();let r=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&r.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield jP(r),e.unbindAndCloseSocket(e._socketInUse===e._socket?WR.BACKUP:WR.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:r,isMain:i}=e,n=new WebSocket(t);this.bindSocket(n),i?this._socket=n:this._backupSocket=n;let o=-1;return new Promise(((e,t)=>{n.onclose=t,n.onerror=t,n.onopen=()=>e(n),r&&(o=setTimeout((()=>{this.unbindAndCloseSocket(i?WR.MAIN:WR.BACKUP),t(new sR({code:nR.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),r))})).finally((()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===WR.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(gw){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(gw){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit(oF,new sR({code:nR.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(WR.MAIN),this.unbindAndCloseSocket(WR.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(oF,new sR({code:nR.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=iN(e.data);let t=JSON.parse(e.data),{cmd:r,data:i}=t,n=Object.values(aF),o=Object.keys(aF)[n.indexOf(r)],s=lF[o]||r;switch(cF.includes(r)||(this._log.debug("received ".concat(r," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),r){case aF.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=i.clientIp,this._signalInfo.signalIp=i.signalInnerIp,i.svrTime&&function(e){aR=e-(new Date).getTime();let t=new Date;t.setTime(e),pN.info("baseTime from server: ".concat(t," offset: ").concat(aR))}(i.svrTime),this._log.info("ChannelSetup Success ".concat(HP()-this._connnectStartTime)),DN.addSuccessEvent({key:521701,cost:HP()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(tF,{signalInfo:this._signalInfo});else{let e=new sR({code:nR.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:HD({key:Qw.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),DN.addFailedEvent({key:521701,error:e}),this.emit(oF,e)}break;case aF.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=i.relayOuterIp,this._signalInfo.relayInnerIp=i.relayInnerIp,this._signalInfo.relayPort=i.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=i.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(String(s),{data:t})}}reGetSignalChannelUrl(){return $b(this,null,(function*(){try{if(!this.room.joinParams)return;eP(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(fR){}}))}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?WR.MAIN:WR.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return $b(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:i,relayPort:n}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:UF,data:{roomId:e,useStringRoomId:t,relayInnerIp:i,relayOuterIp:r,relayPort:n},responseCommand:lF.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),DN.addSuccessEvent({key:521702,cost:HP()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(DN.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(fR){this._log.error(fR),this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},i=JSON.stringify(r);return this._socketInUse.send(i),this.bytesSent+=iN(i),r.seq}}sendWaitForResponse(e){let{command:t,data:r,timeout:i=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0,addReceiveTime:a=!1}=e;return new Promise(((e,c)=>{let l=setTimeout((()=>{this.off(n,d);let e=new sR({code:nR.API_CALL_TIMEOUT,message:HD({key:Qw.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),c(e)}),i),d=t=>{t.data.seq===u&&(clearTimeout(l),this.off(n,d),a&&(t.data.receiveTime=Date.now()),e(t))};this.on(n,d);let u=this.send(t,r)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:i=0,retryTimeout:n=0}=e;return qD({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(r," when connected")),this.once(iF,t))},onRetrying:e=>{this._log.warn("".concat(t||r," timeout observed, retrying [").concat(e,"/").concat(i,"]"))},settings:{retries:i,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),BF.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(WR.MAIN),this.unbindAndCloseSocket(WR.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(lF.JOIN_ROOM_RESULT,t)}),1e3*e);let t=e=>{0===e.data.code&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(lF.JOIN_ROOM_RESULT,t))};this.on(lF.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(rF,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(iF):"DISCONNECTED"===e&&this.emit(sF))}};Wb([GO({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],jF.prototype,"connect",1);var HF=Hb(Jb()),WF=0,GF=!1,zF=new Set,$F=!1,JF=class{constructor(e){Gb(this,"userId"),Gb(this,"tinyId"),Gb(this,"_sdpSemantics"),Gb(this,"_isUplink"),Gb(this,"_room"),Gb(this,"_log"),Gb(this,"_signalChannel"),Gb(this,"_isErrorObserved",!1),Gb(this,"_waitForPeerConnectionConnectedPromise"),Gb(this,"_waitForPeerConnectionConnectedPromiseReject",null),Gb(this,"_peerConnection",null),Gb(this,"_emitter",new HF.default),Gb(this,"_currentState","DISCONNECTED"),Gb(this,"_isReconnecting",!1),Gb(this,"_reconnectionCount",0),Gb(this,"_reconnectionTimer",-1),Gb(this,"_isFirstConnection",!0),Gb(this,"_prevTime",-1),Gb(this,"_localAddress"),Gb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=pN.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=HP())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,DN.addSuccessEvent({key:521705,cost:Math.min(HP()-this._prevTime,3e4)})):this._isReconnecting&&DN.addSuccessEvent({key:521706,cost:HP()-this._prevTime}),this._prevTime=-1}catch(yN){throw this._isFirstConnection?(this._isFirstConnection=!1,DN.addFailedEvent({key:521705,error:yN})):this._isReconnecting&&this._reconnectionCount>=3&&DN.addFailedEvent({key:521706,error:yN}),yN}}initialize(){let e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),zF.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new sR({code:nR.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return hw;let e=null;if(this._isUplink){if(!tO()||0===this._peerConnection.getSenders().length)return hw;e=this._peerConnection.getSenders()[0].transport}else{if(!eO()||0===this._peerConnection.getReceivers().length)return hw;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:hw}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(r)),e.target.connectionState===pw.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===pw.FAILED||e.target.connectionState===pw.CLOSED){let i="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(r),n=new sR({message:i,code:nR.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===pw.CONNECTED||e.target.connectionState===pw.COMPLETED)&&(this.logSelectedCandidate(),XD.logSuccessEvent({userId:this._room.userId,eventType:yw.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(WF=0,GF=!1,$F=!0,zF.add(this)):zF.delete(this),KD.emit(uN.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return $b(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(JN(t)){let r=e.get(t.localCandidateId),i=e.get(t.remoteCandidateId);r&&(this._log.info("local candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port," ").concat(r.networkType||""," ").concat("relay"===r.candidateType?"relayProtocol:".concat(r.relayProtocol):"")),this._localAddress="".concat(r.ip||r.address,":").concat(r.port)),i&&(this._log.info("remote candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port)),this._remoteAddress="".concat(i.protocol,":").concat(i.ip||i.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let r=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},i=e=>{let{room:r}=e;r===this._room&&(clearTimeout(o),n(),t(new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{KD.off(uN.LEAVE_SUCCESS,i,this),this._emitter.off("connection-state-changed",r,this)},o=setTimeout((()=>{n();let e=new sR({code:nR.API_CALL_TIMEOUT,message:"connection timeout"});WF+=1,(e=>WF>2&&!GF&&0===zF.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),GF=!0,this._emitter.emit("firewall-restriction")),t(e)}),Pw);KD.on(uN.LEAVE_SUCCESS,i,this),this._emitter.on("connection-state-changed",r,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(iF,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=_w()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new sR({code:this._isUplink?nR.UPLINK_RECONNECTION_FAILED:nR.DOWNLINK_RECONNECTION_FAILED,message:HD({key:this._isUplink?Qw.UPLINK_RECONNECTION_FAILED:Qw.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(iF,this.reconnect,this),-1)}on(e,t,r){this._emitter.on(e,t,r)}off(e,t,r){this._emitter.off(e,t,r)}getIsReconnecting(){return this._isReconnecting}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}setOffer(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}};Wb([fL(521712,!1)],JF.prototype,"setOffer",1),Wb([fL(521713,!1)],JF.prototype,"setAnswer",1);var qF=Hb(tR()),KF=function(e){return qF.default.parse(e)},YF=function(e){return qF.default.write(e)};function XF(e){return Object.keys(e).filter((t=>e[t]))}var QF=class extends JF{constructor(e){super(Fb(Ub({},e),{isUplink:!1})),Gb(this,"_flag",0),Gb(this,"isRobot",!1),Gb(this,"role","anchor"),Gb(this,"remoteAudioTrack"),Gb(this,"remoteVideoTrack"),Gb(this,"remoteAuxiliaryTrack"),Gb(this,"ssrc",{audio:0,video:0,auxiliary:0}),Gb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new ML(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Mx(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Lx(this._room,this)}get videoCodec(){var e,t;let r=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return r?r.includes("H264")?"h264":"vp8":"h264"}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 JP(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,i;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(r=this.remoteVideoTrack)||r.onFlagChanged(),null==(i=this.remoteAuxiliaryTrack)||i.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===WR.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,r;let i=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&i!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:i,state:e}),null==(r=this.remoteAuxiliaryTrack)||r.emit("connection-state-changed",{prevState:i,state:e})),n}onTrack(e){let t=e.streams[0],{track:r}=e,i=t.id===tw?WR.MAIN:WR.AUXILIARY;this._log.debug("ontrack ".concat(i," ").concat(r.kind));let n=WR.AUDIO;r.kind===WR.VIDEO&&(n=i===WR.MAIN?WR.VIDEO:WR.AUXILIARY);let o=this.remoteAudioTrack;n===WR.VIDEO?o=this.remoteVideoTrack:n===WR.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split("\r\n"),r=new Map;t.forEach(((e,i)=>{/^a=rtcp-fb:/.test(e)&&t[i+1]&&!/^a=rtcp-fb:/.test(t[i+1])&&r.set(i+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let i=[...r];for(let n=0;n<i.length;n++){let[e,r]=i[n];t.splice(e+n,0,r)}return t.join("\r\n")}addSPSDescription(e){let t=KF(e);return t.media.forEach((e=>{e.type===WR.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),YF(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=KF(e);return r.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),YF(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return $b(this,null,(function*(){var r,i;try{if(((null==(r=this._peerConnection)?void 0:r.connectionState)===pw.NEW||(null==(i=this._peerConnection)?void 0:i.connectionState)===pw.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(gR){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(gR.message," ").concat(JSON.stringify(this.muteState))),new sR({code:nR.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):gR}}))}unsubscribe(e){return $b(this,arguments,(function(e){var t=this;let{remoteTracks:r,streamType:i}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===i&&!t.isMainStreamSubscribed||"auxiliary"===i&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(i," stream already unsubscribed"));let e=Ub({},t.subscribeState);r.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let n="subscribe_change";Object.values(e).find((e=>!0===e))||(n="unsubscribe"),t._log.info("".concat("unsubscribe"===n?n:"subscribe"," ").concat(i," [").concat(XF(e),"]")),yield t.sendSubscription(n,e),"unsubscribe"===n&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,r={srcTinyId:this.tinyId,srcUserId:this.userId},i=yF,n=lF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},i=EF,n=lF.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:i,data:r,responseCommand:n,timeout:1e4}).then((t=>{let{data:r}=t;if(0!==r.code){let t=new sR({code:r.code,message:HD({key:Qw.ERROR_MESSAGE,data:{type:e,message:r.message}})});throw this._log.error(t),t}}))}connect(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(gw){throw e.closePeerConnection(!0),gw}}()}))}exchangeSDP(e){return $b(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,i={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:vF,commandDesc:"exchange sdp",data:i,responseCommand:lF.SUBSCRIBE_RESULT,timeout:Sw});if(!this._peerConnection){let e=new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(gw){throw this._isSDPExchanging=!1,gw}}))}createOffer(){return $b(this,null,(function*(){let e={voiceActivityDetection:!1};iO()&&this._sdpSemantics===Iw?(this._peerConnection.addTransceiver(WR.AUDIO,{direction:GR.RECVONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:GR.RECVONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:GR.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield jN();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=KF(e);return t.media.forEach((e=>{var t,r;if(e.type===WR.VIDEO){let i=new Set;e.rtp.forEach((e=>{let{payload:t,codec:r}=e;return"H264"===r&&i.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:r}=e,n=r.match(/apt=(\d+)/);n&&n[1]&&i.has(Number(n[1]))&&i.add(t)}));let n=e=>{let{payload:t}=e;return!i.has(t)};e.rtp=e.rtp.filter(n),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=null==(r=e.payloads)?void 0:r.split(" ").filter((e=>!i.has(Number(e)))).join(" ")}})),YF(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=KF(e);return t.media.forEach((e=>{e.type===WR.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),YF(t)}(t.sdp),this._sdpSemantics===Iw&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)}))}onSubscribeResult(e){return $b(this,null,(function*(){let{code:t,message:r=""}=e&&e.data||{},{type:i,sdp:n}=e&&e.data&&e.data.data||{};if(t===Cw)throw new sR({code:nR.NOT_SUPPORTED_H264,message:HD({key:Qw.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new sR({code:t,message:HD({key:Qw.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug("accept remote answer: ".concat(n)),yield this.setAnswer({type:i,sdp:n}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{KF(e).media.forEach((e=>{if(e.ssrcs)if(e.type===WR.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(tw)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(tw)})),r=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(rw)}));t&&(this.ssrc.video=Number(t.id)),r&&(this.ssrc.auxiliary=Number(r.id))}}))}catch(gw){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return $b(this,null,(function*(){if(!(zb(QF.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(gw){let t=bP(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:t,videoDelay:r}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=r}get audioReceiver(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}},ZF=QF;Wb([sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return new Promise(((t,i)=>{let n=e=>{this._emitter.off("closed",n),i(new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,r).then(t,i).finally((()=>{this._emitter.off("closed",n)}))}))}))],ZF.prototype,"subscribe",1),Wb([fL(521717,!1)],ZF.prototype,"unsubscribe",1),Wb([oL(JF.prototype.afterConnect),nL(JF.prototype.beforeConnect)],ZF.prototype,"connect",1);var eB=ZF,tB={voiceActivityDetection:!1},rB=class extends JF{constructor(e){super(Fb(Ub({},e),{isUplink:!0})),Gb(this,"localMainAudioTrack",null),Gb(this,"localMainVideoTrack",null),Gb(this,"localAuxAudioTrack",null),Gb(this,"localAuxVideoTrack",null),Gb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Gb(this,"_isPublishingAux",!1),Gb(this,"_publishingLocalAudioTrack"),Gb(this,"_publishingLocalVideoTrack"),Gb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Gb(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,r,i;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(rO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(r=o[2])||!r.track),n.auxVideo=!(null==(i=o[3])||!i.track)):o.forEach((e=>{e.track&&(e.track.kind===WR.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var r,i,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(r=this.localMainVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(i=this.localAuxVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i,isAuxiliary:n}=e;return function*(){let e;t._peerConnection||t.initialize(),r&&(t._publishingLocalAudioTrack=r),i&&(t._publishingLocalVideoTrack=i),t._isPublishingAux=n,i&&!n&&i.small&&(e=t._room.videoManager.smallTrack),t.sendMediaSettings(),iO()?yield t.publishByTransceiver({localAudioTrack:r,localVideoTrack:i,smallTrack:e,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:r,localVideoTrack:i,smallTrack:e}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n?(i&&(t.localAuxVideoTrack=i),r&&(t.localAuxAudioTrack=r)):(i&&(t.localMainVideoTrack=i),r&&(t.localMainAudioTrack=r)),t.installTrackMuteEvents(r,i),t.sendMutedFlag()}()}))}publishByTransceiver(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i,smallTrack:n,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==i?void 0:i.outMediaTrack,a=null==r?void 0:r.outMediaTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||WR.AUDIO,{direction:GR.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?WR.VIDEO:s||WR.VIDEO,{direction:GR.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||WR.VIDEO,{direction:GR.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||WR.VIDEO,{direction:GR.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==r?void 0:r.profile.bitrate)||40,type:WR.AUDIO})),s){let r=o?3:1;yield c[r].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:i.profile.bitrate,type:WR.VIDEO,videoType:o?WR.AUXILIARY:WR.BIG}),e.push(r),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:i.small.bitrate,type:WR.VIDEO,videoType:WR.SMALL}),e.push(2))}yield t.setTransceiverDirection(GR.SENDONLY,e),yield t.doPublishChange(),null==i||i.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==i||i.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i,smallTrack:n}=e;return function*(){t._log.info("publish by addtrack");let e=null==i?void 0:i.outMediaTrack,o=null==r?void 0:r.outMediaTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return r&&o&&(yield t.addTrack(r)),void(e&&(yield t.addTrack(i)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),n)){let e=new MediaStream;e.addTrack(n),t._peerConnection.addTrack(n,e)}yield t.connect()}()}))}enableSmall(e){return $b(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(GR.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(GR.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i}=e;return function*(){if(!rO())return r&&r.outMediaTrack&&!i&&t.localMainVideoTrack?(yield t.removeTrack(r),void(t.localMainAudioTrack=null)):i&&i.outMediaTrack&&!r&&t.localMainAudioTrack?(yield t.removeTrack(i),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(r,i),void t.emitConnectionStateChangedEvent("DISCONNECTED",i));let e=i&&i===t.localAuxVideoTrack,n=null==i?void 0:i.outMediaTrack,o=t._peerConnection.getSenders(),s=[];r&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localAuxAudioTrack&&!t.localMainAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=Fb(Ub({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=Fb(Ub({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(GR.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(r,i),null==i||i.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return $b(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:_F,data:t,responseCommand:lF.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:gF,commandDesc:"unpublish",responseCommand:lF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===nR.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:i,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:i=this._publishingLocalVideoTrack),dO){if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*i.profile.bitrate,i.small&&(this._mediaSettings.smallVideoWidth=i.small.width,this._mediaSettings.smallVideoHeight=i.small.height,this._mediaSettings.smallVideoFps=i.small.frameRate,this._mediaSettings.smallVideoBps=1e3*i.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=r.profile.sampleRate),i&&i.outMediaTrack&&(this._mediaSettings.videoWidth=i.profile.width,this._mediaSettings.videoHeight=i.profile.height,this._mediaSettings.videoFps=i.profile.frameRate,this._mediaSettings.videoBps=1e3*i.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:NF,data:this._mediaSettings,responseCommand:lF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return $b(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?WR.AUXILIARY:WR.MAIN," stream")),iO()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return $b(this,null,(function*(){var r;if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===WR.AUDIO)yield i[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield i[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(r=this.localMainVideoTrack)?void 0:r.small)&&(yield i[2].sender.replaceTrack(this._room.videoManager.smallTrack)),i[n].direction===GR.INACTIVE&&(yield this.setTransceiverDirection(GR.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return $b(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;rO()&&this._peerConnection.getTransceivers().findIndex((e=>"stopped"===e.direction))>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find((e=>e.track&&e.track.kind===t.kind));if(r&&r.track){this._log.warn("sender already exists, remove sender first");let e=r.track;this.removeSender(r),yield this.updateOffer("remove",e)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===WR.VIDEO&&e instanceof SL&&e.small){let e=new MediaStream,{smallTrack:t}=this._room.videoManager;e.addTrack(t),this._peerConnection.addTrack(t,e)}yield this.updateOffer("add",t)}))}isNeedToResetOfferOrder(){if(this._sdpSemantics===Aw||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=KF(e);for(let r=0;r<t.media.length;r++)if(0===Number(t.media[r].mid)&&t.media[r].type===WR.VIDEO)return!0;return!1}removeSender(e){let t=null;rO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&wP(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return $b(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?WR.AUXILIARY:WR.MAIN," stream")),iO()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return $b(this,null,(function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===WR.AUDIO)yield r[0].sender.replaceTrack(null);else{let i=t?3:1;yield r[i].sender.replaceTrack(null),1===i&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(GR.INACTIVE,[i])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return $b(this,null,(function*(){if(!_k)return;let r=!1,i=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let n=this._peerConnection.getTransceivers();if(t.forEach((t=>{n[t].direction!==e&&(n[t].direction=e,r=!0)})),r){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this.setOffer(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((r=>{if(r.match(new RegExp("a=(".concat(GR.INACTIVE,"|").concat(GR.RECVONLY,"|").concat(GR.SENDONLY,")")))&&o++,t.includes(o)){if(e===GR.INACTIVE&&r.includes("a=".concat(GR.RECVONLY)))return i=!0,"a=".concat(e);if(e===GR.SENDONLY&&r.includes("a=".concat(GR.INACTIVE)))return i=!0,"a=".concat(GR.RECVONLY)}return r})).join("\r\n");i&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:s}))}))}removeTrackBySender(e){return $b(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===WR.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===WR.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===WR.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return $b(this,null,(function*(){var t;let r,i=null==(t=this._peerConnection)?void 0:t.getSenders();if(!i||0===i.length||!e.mediaTrack)return!1;if(r=iO()?e.kind===WR.AUDIO?i[0]:i[1]:i.find((t=>t.track&&t.track.kind===e.kind)),!r)return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(n?WR.AUXILIARY:WR.MAIN," stream")),e.kind===WR.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===WR.VIDEO&&(n?i[3]&&(yield i[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0}))}updateOffer(e,t){return $b(this,null,(function*(){try{let r=yield this._peerConnection.createOffer(tB);_k&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let i=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===WR.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:i,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(n.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:dF,data:n,responseCommand:lF.UPDATE_OFFER_RESULT,timeout:Tw,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(_R){throw this._log.error(_R),_R}}))}setBandwidth(e){return $b(this,arguments,(function(e){var t=this;let{bandwidth:r,type:i,videoType:n,sdp:o}=e;return function*(){if(!cO())return o?i===WR.VIDEO?t.updateVideoBandwidthRestriction(o,r,n):t.updateAudioBandwidthRestriction(o,r):void 0;let e,s=t._peerConnection.getSenders();if(iO()){let t=0;i===WR.VIDEO&&(t=n===WR.SMALL?2:n===WR.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===i));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*r;try{return yield e.setParameters(s),t._log.info("".concat(n||"").concat(i," bandwidth ").concat(r," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return i===WR.VIDEO?t.updateVideoBandwidthRestriction(o,r,n):t.updateAudioBandwidthRestriction(o,r)}}return o}()}))}updateVideoBandwidthRestriction(e,t,r){let i="AS";_k&&(i="TIAS",t*=1e3);let n=0,o=-1;return r===WR.SMALL?n=1:r===WR.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===n?"".concat(e,"b=").concat(i,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let r="AS";return _k&&(r="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(r,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return $b(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(fR){throw this.closePeerConnection(!0),this.uninstallEvents(),fR}}))}exchangeSDP(){return $b(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(fR){throw fR}}))}createOffer(){return $b(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(tB);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(fR){throw fR}}))}doExchangeSDP(){let e={command:fF,responseCommand:lF.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof bL||this.localAuxVideoTrack instanceof bL,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:r,data:i}=e.data;return 0===t?this.acceptAnswer(i):this.checkPublishResultCode(t,r)}))}setSDPDirection(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",i=KF(e);return i.media.forEach((e=>{("all"===r||e.type===r)&&(e.direction=t)})),YF(i)}acceptAnswer(e){return $b(this,null,(function*(){var t,r,i,n,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(r=this.localMainVideoTrack)?void 0:r.profile.bitrate),o=(null==(i=this._publishingLocalAudioTrack)?void 0:i.profile.bitrate)||(null==(n=this.localMainAudioTrack)?void 0:n.profile.bitrate);if(e){let t=this._isPublishingAux?WR.AUXILIARY:WR.BIG;s=yield this.setBandwidth({bandwidth:e,type:WR.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:WR.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:WR.VIDEO,videoType:WR.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this.setAnswer(a),this._log.debug("accepted answer: ".concat(s))}catch(YB){throw this._log.error("failed to accept remote answer ".concat(YB)),YB}}))}sendMutedFlag(e){var t,r,i;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(r=this.localMainVideoTrack)||!r.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)};this._log.info("send muted state: ".concat(JSON.stringify(n))),this._signalChannel.send(mF,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return $b(this,null,(function*(){if(!(zb(rB.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:gF,responseCommand:lF.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(gw){let t=bP(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),t)}}))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&KD.emit(uN.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{KF(e).media.forEach(((e,t)=>{if(e.type===WR.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Aw&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let r=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=r:1===t&&(this.ssrc.small=r)}));let r=e.ssrcs&&e.ssrcs[0];if(!r)return;switch(t){case 1:this.ssrc.video=Number(r.id);break;case 2:this.ssrc.small=Number(r.id);break;case 3:this.ssrc.auxiliary=Number(r.id)}}}))}catch(gw){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:WR.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===WR.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===WR.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===WR.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===WR.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Cw?(this._log.error(Zw.NOT_SUPPORTED_H264ENCODE),new sR({code:nR.NOT_SUPPORTED_H264,message:HD({key:Qw.NOT_SUPPORTED_H264ENCODE})})):new sR({code:nR.UNKNOWN,message:HD({key:Qw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lF.PUBLISH_RESULT,code:e,message:t}})})}},iB=rB;Wb([sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return new Promise(((t,i)=>{let n=e=>{this._emitter.off("closed",n),i(new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,r).then(t,i).finally((()=>{this._emitter.off("closed",n)}))}))}))],iB.prototype,"publish",1),Wb([fL(521715,!1)],iB.prototype,"unpublish",1),Wb([oL(JF.prototype.afterConnect),nL(JF.prototype.beforeConnect)],iB.prototype,"connect",1);var nB=iB,oB=class{constructor(e,t){this.room=e,Gb(this,"_log"),Gb(this,"_prevReportTime",0),Gb(this,"_prevReport",{}),Gb(this,"_prevStats",null),Gb(this,"_prevEncoderImplementation",""),Gb(this,"_prevAuxEncoderImpl",""),Gb(this,"_prevQualityLimitationReason",""),Gb(this,"_prevAuxQualityLimitationReason",""),Gb(this,"_prevDecoderImplementationMap",new Map),Gb(this,"totalBytesSent",0),Gb(this,"totalBytesReceived",0),Gb(this,"_spcStats",null),this._log=t}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return $b(this,null,(function*(){var t;let r={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((t=>{var i,o,s;let a,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===WR.VIDEO){if(t.ssrc===n.video?(a=WR.VIDEO,c=e.localMainVideoTrack):t.ssrc===n.small?a=WR.SMALL:t.ssrc===n.auxiliary&&(c=e.localAuxVideoTrack,a=WR.AUXILIARY),!a)return;if(r[a].bytesSent=t.bytesSent,r[a].packetsSent=t.packetsSent,r[a].framesEncoded=t.framesEncoded,kP(t.keyFramesEncoded)||(r[a].keyFramesEncoded=t.keyFramesEncoded),kP(t.nackCount)||(r[a].nackCount=t.nackCount),kP(t.pliCount)||(r[a].pliCount=t.pliCount),kP(t.retransmittedPacketsSent)||(r[a].retransmittedPacketsSent=t.retransmittedPacketsSent),kP(t.totalEncodeTime)||(r[a].totalEncodeTime=t.totalEncodeTime),kP(t.totalPacketSendDelay)||(r[a].totalPacketSendDelay=t.totalPacketSendDelay),!kP(t.encoderImplementation)&&(a===WR.VIDEO&&this._prevEncoderImplementation!==t.encoderImplementation||a===WR.AUXILIARY&&this._prevAuxEncoderImpl!==t.encoderImplementation)){let r=2,i=this._prevEncoderImplementation;a===WR.AUXILIARY&&(r=7,i=this._prevAuxEncoderImpl),KD.emit("262",{userId:e.userId,streamType:r,prevImplementation:i,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),this[a===WR.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,this._log.info("".concat(a===WR.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===n.video?!kP(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),KD.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(i=e.localMainVideoTrack)?void 0:i.isQosClearFirst}),this._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===n.auxiliary&&!kP(t.qualityLimitationReason)&&0!==t.bytesSent&&this._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),KD.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(o=e.localAuxVideoTrack)?void 0:o.isQosClearFirst}),this._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else r.audio.bytesSent=t.bytesSent,r.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?JN(t)&&(this.totalBytesSent=t.bytesSent,PP(t.currentRoundTripTime)&&(r.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===WR.AUDIO?(r.audio.audioLevel=t.audioLevel||0,r.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(r.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===WR.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(WR.VIDEO)?r.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(WR.AUXILIARY)?r.auxiliary.fpsCapture=t.framesPerSecond:r.small.fpsCapture=t.framesPerSecond));if(!kP(t.audioLevel)&&(null==(s=e.localMainAudioTrack)?void 0:s.mediaTrack)&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(r.audio.audioLevel=t.audioLevel||0),!kP(t.frameWidth)){let i=WR.SMALL;t.trackIdentifier===e.getVideoTrackId(WR.VIDEO)||t.ssrc===n.video?i=WR.VIDEO:(t.trackIdentifier===e.getVideoTrackId(WR.AUXILIARY)||t.ssrc===n.auxiliary)&&(i=WR.AUXILIARY),r[i].frameWidth=t.frameWidth,r[i].frameHeight=t.frameHeight,r[i].framesSent=t.framesSent}})),e.localMainAudioTrack){let t=e.localMainAudioTrack.getInternalAudioLevel();r.audio.micAudioLevel=t,0===r.audio.audioLevel&&(r.audio.audioLevel=t)}this.totalBytesSent||(this.totalBytesSent+=r.audio.bytesSent+r.video.bytesSent+r.auxiliary.bytesSent),Object.keys(r).forEach((t=>{t===WR.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=r[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=r[t])):t===WR.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=r[t]):t===WR.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=r[t])}))}catch(gR){this._log.warn("failed to getStats on sender connection ".concat(gR))}return 0===r.rtt&&(r.rtt=(null==(t=this.room.networkQuality)?void 0:t.uplinkRTT)||0),r}))}getReceiverStats(e){return $b(this,null,(function*(){var t,r,i;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},o=e.getPeerConnection();if(o)try{let{ssrc:i}=e,{muteState:s,subscribeState:a}=e;(this._spcStats||(yield o.getStats())).forEach((t=>{if("inbound-rtp"===t.type){let r=(t.mediaType||t.kind)===WR.AUDIO;if(r){if(t.ssrc!==i.audio||!s.hasAudio)return;n.audio.packetsReceived=t.packetsReceived,n.audio.bytesReceived=t.bytesReceived,n.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(n.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(n.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(n.audio.concealedSamples=t.concealedSamples);let{remoteAudioTrack:r}=e;r.stat.packetsReceived=t.packetsReceived,r.stat.bytesReceived=t.bytesReceived,r.stat.packetsLost=t.packetsLost,n.audio.p2pDelay=r.stat.end2EndDelay,n.hasAudio=!0}else{if(_k&&0===t.bytesReceived)return;let r;t.ssrc===i.video&&s.hasVideo&&(n.video.packetsReceived=t.packetsReceived,n.video.bytesReceived=t.bytesReceived,n.video.packetsLost=t.packetsLost,n.video.framesReceived=t.framesReceived,n.video.framesDecoded=t.framesDecoded,n.video.fpsDecoded=t.framesPerSecond,n.hasVideo=!0,r=e.remoteVideoTrack,s.hasSmall&&a.smallVideo&&(n.isSmallSubscribed=!0),t.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==t.decoderImplementation)&&(this._log.info("".concat(n.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),KD.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,t.decoderImplementation))),t.ssrc===i.auxiliary&&s.hasAuxiliary&&(n.auxiliary.packetsReceived=t.packetsReceived,n.auxiliary.bytesReceived=t.bytesReceived,n.auxiliary.packetsLost=t.packetsLost,n.auxiliary.framesReceived=t.framesReceived,n.auxiliary.framesDecoded=t.framesDecoded,n.auxiliary.fpsDecoded=t.framesPerSecond,r=e.remoteAuxiliaryTrack,n.hasAuxiliary=!0),r&&(r.stat.packetsReceived=t.packetsReceived,r.stat.bytesReceived=t.bytesReceived,r.stat.packetsLost=t.packetsLost,r.stat.framesReceived=t.framesReceived,r.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(r.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)))}t.jitterBufferDelay&&(r?(n.audio.totalJitter=t.jitterBufferDelay,n.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===i.video&&s.hasVideo?(n.video.totalJitter=t.jitterBufferDelay,n.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===i.auxiliary&&s.hasAuxiliary&&(n.auxiliary.totalJitter=t.jitterBufferDelay,n.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&JN(t)&&(this.totalBytesReceived=t.bytesReceived,PP(t.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*t.currentRoundTripTime)));kP(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===i.video)&&(n.video.frameWidth=t.frameWidth,n.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===i.auxiliary)&&(n.auxiliary.frameWidth=t.frameWidth,n.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!kP(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=t.audioLevel||0,n.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===n.audio.audioLevel&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),kP(null==(t=e.remoteVideoTrack.player.stat)?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),kP(null==(r=e.remoteAuxiliaryTrack.player.stat)?void 0:r.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps)}catch(s){this._log.warn("failed to getStats on receiver connection ".concat(s))}return 0===n.rtt&&(n.rtt=(null==(i=this.room.networkQuality)?void 0:i.uplinkRTT)||0),n}))}getStats(e,t){return $b(this,null,(function*(){let r={},i=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:r,receiverStats:i};let t=HP(),n=yield e.getStats(),o=HP();o-t>2e3&&this._log.warn("getStats cost ".concat(o-t,"ms"));let s=[],a=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);n.forEach((e=>a.has(e.type)&&s.push(e))),this._spcStats=s}e&&(r=yield this.getSenderStats(e));for(let[e,n]of t){let e=yield this.getReceiverStats(n);i.push(e)}return{senderStats:r,receiverStats:i}}))}getDifferenceValue(e,t){if(QM(e))return t;let r=t-e;return r<0?0:r}prepareReport(e){let{stats:t,report:r,freezeMap:i}=e;var n;if(!QM(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*Xw,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*Xw),t.senderStats.audio.totalSamplesDuration&&(r.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let i=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};i.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};i.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};i.push(e)}let n={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};r.msg_up_stream_info={msg_audio_status:e,msg_video_status:i,msg_network_status:n}}let{statInterval:o}=this;r.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let r={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=r}if(e.hasVideo){let r=i.get("".concat(e.userId,"_").concat(iw)),n=r?r.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount};t.msg_video_status.push(o)}if(e.hasAuxiliary){let r=i.get("".concat(e.userId,"_").concat(nw)),n=r?r.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:n,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount};t.msg_video_status.push(o)}r.msg_down_stream_info.push(t)}));let s=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(r)),this._prevStats=JSON.parse(JSON.stringify(t)),r.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let e=s.msg_up_stream_info.msg_audio_status,t=r.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let i=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*i/o),r.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}null!=(n=s.msg_device_info)&&n.uint32_audio_capture_cost?r.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(s.msg_device_info.uint32_audio_capture_cost,r.msg_device_info.uint32_audio_capture_cost)/o):delete r.msg_device_info.uint32_audio_capture_cost}let c=s.msg_up_stream_info.msg_video_status;r.msg_up_stream_info.msg_video_status.forEach((e=>{let t=c.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let i=0,n=0,s=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(i=t.uint32_video_codec_bitrate,n=t.uint32_video_enc_fps,s=t.uint32_video_codec_fps);let a=this.getDifferenceValue(i,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*a/o),r.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(n,e.uint32_video_enc_fps)/o),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(s,e.uint32_video_codec_fps)/o),$k&&115===uD()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),kP(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),kP(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),kP(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),kP(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),kP(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/o)),kP(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/o))}));let l=s.msg_down_stream_info;r.msg_down_stream_info=r.msg_down_stream_info.filter((e=>l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid))));let d=r.msg_down_stream_info;return d.forEach((e=>{let t=l.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(QM(e.msg_audio_status)||QM(t.msg_audio_status))e.msg_audio_status={};else{let r=e.msg_audio_status,i=t.msg_audio_status,n=this.getDifferenceValue(i.uint32_audio_cache_ms_count,r.uint32_audio_cache_ms_count);delete r.uint32_audio_cache_ms_count,r.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(i.uint32_audio_cache_ms,r.uint32_audio_cache_ms)/n)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=r.uint32_audio_cache_ms),r.uint32_audio_origin_lost=this.getDifferenceValue(i.uint32_audio_origin_lost,r.uint32_audio_origin_lost),r.uint32_audio_receive=this.getDifferenceValue(i.uint32_audio_receive,r.uint32_audio_receive),r.uint32_audio_receive+=r.uint32_audio_origin_lost;let a=this.getDifferenceValue(i.uint32_audio_codec_bitrate,r.uint32_audio_codec_bitrate);r.uint32_audio_codec_bitrate=Math.round(8*a/o),r.uint32_audio_total_bitrate=Math.round(8*a/o)}if(e.msg_video_status&&t.msg_video_status){let r=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>r.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=r.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),i=t.uint32_video_receive,n=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(n,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(i,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/o);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/o),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/o);let u=this.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/u)||0}))}})),a&&t.receiverStats.forEach((e=>{if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){let t=a.receiverStats.find((t=>t.userId===e.userId));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){let r=e.audio.concealedSamples-t.audio.concealedSamples,i=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,n=Math.floor(r/i*1e3*o);if(n>1e3*o/5){let t=d.find((t=>t.msg_user_info.str_identifier===e.userId));t&&(t.msg_audio_status.uint32_audio_block_time=n)}}}})),r}getStatsReport(e){return $b(this,arguments,(function(e){var t=this;let{uplinkConnection:r,downlinkConnections:i,freezeMap:n}=e;return function*(){let e={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(r,i);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:n}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},sB=Hb(Jb());function aB(e){return new Promise((t=>$b(this,null,(function*(){let r=setTimeout((()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),i=Date.now(),n="https://".concat(e,"/?t=").concat(i);try{yield fetch(n)}catch(gR){}clearTimeout(r);let o=function(e){let t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource").reverse();for(let i of r)if(i.name===e){let e=Math.round(i.duration),r=Math.max(Math.round(i.domainLookupStart-i.startTime),0),n=i.redirectStart>0?Math.max(Math.round(i.redirectEnd-i.redirectStart),0):0,o=i.fetchStart>0?Math.max(Math.round(i.domainLookupStart-i.fetchStart),0):0,s=Math.round(i.domainLookupEnd-i.domainLookupStart),a=Math.round(i.requestStart-i.secureConnectionStart),c=Math.round(i.secureConnectionStart-i.connectStart),l=Math.round(i.responseStart-i.requestStart),d=Math.round(i.responseEnd-(i.responseStart||i.startTime));t=Fb(Ub({},t),{totalCost:e,local:r,redirect:n,httpCache:o,dns:s,tcp:c,tls:a,request:l,response:d});break}}catch(r){}return t}(n);0===o.totalCost&&(o.totalCost=Date.now()-i),t(o)}))))}var cB=class extends sB.default{constructor(e){let{signalChannel:t,room:r}=e;super(),Gb(this,"_room"),Gb(this,"_signalChannel"),Gb(this,"_log"),Gb(this,"uplinkRTT",0),Gb(this,"uplinkLoss",0),Gb(this,"downlinkRTT",0),Gb(this,"downlinkLoss",0),Gb(this,"pingResults",{}),Gb(this,"_downlinkPrevStatMap",new Map),Gb(this,"_downlinkLossAndRTTMap",new Map),Gb(this,"_interval",-1),Gb(this,"_uplinkNetworkQuality",0),Gb(this,"_downlinkNetworkQuality",0),this._room=r,this._signalChannel=t,this._log=pN.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(r," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(lF.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(rF,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,r;if(0!==e.data.code)return;let i=e.data.data;if(i.delay&&this.updateDelay(i.delay),this._room.signalChannel&&i.wsRtt&&(this._room.signalChannel.rtt=i.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let n=null==(r=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:r.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=i.expectAudPkg+i.expectVidPkg,s=i.recvAudPkg+i.recvVidPkg,a=o-s;0===o&&0===s||(this.uplinkLoss=a<=0?0:Math.round(a/o*100),this.uplinkRTT=i.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return $b(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===pw.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let n=0;n<t.length;n++){let e=t[n].getPeerConnection();if(!e)return;let{rtt:r,totalPacketsLost:i,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:i,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=i-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:i,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:r,loss:s,userId:t[n].getUserId(),audioDelay:t[n].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[n].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:r,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=r,this.downlinkLoss=i,this.downlinkNetworkQuality=this.getNetworkQuality(i,r)}))}getStat(e){return $b(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!eO())return t;let r=e.getReceivers();try{for(let e=0;e<r.length;e++)(yield r[e].getStats()).forEach((e=>{"candidate-pair"===e.type&&PP(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===WR.AUDIO||e.mediaType===WR.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return 0===t.rtt&&(t.rtt=this.uplinkRTT),t}catch(i){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((r=>{t[r]=Math.round(t[r]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==pw.DISCONNECTED&&e.connectionState!==pw.FAILED&&e.connectionState!==pw.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=VO.run(Ww,(()=>{var e;this.handleDownlinkNetworkQuality();let t=[...this._downlinkLossAndRTTMap.values()];KD.emit(uN.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:t});let r=null==(e=this._room.scheduleResult.config)?void 0:e.pingDomainInfo,i={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};r&&(i=Fb(Ub({},i),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(cB.EVENT_NETWORK_QUALITY,i);let n=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&n-cB.lastPingTime>1e3*r.interval){cB.lastPingTime=Date.now();let e=r.domain.map((e=>aB(e).then((t=>({domain:e,cost:t.totalCost})))));Promise.all(e).then((e=>{this.pingResults.isPoorNetwork=e.some((e=>e.cost>700)),this.pingResults.timestamp=n,this.pingResults.data=e,e.forEach((e=>{kvStatManager.addSuccessEvent({key:KV_REPORT_KEY_NETWORK.PING,cost:e.cost})})),this._log.warn("All ping results: ".concat(JSON.stringify(e)))})).catch((e=>{this._log.warn("Error during pinging domains: ".concat(e))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(VO.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:r,videoDelay:i,audioDelay:n}=e,o=t.get(r);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:i,audioDelay:n})}}))}},lB=cB;Gb(lB,"EVENT_NETWORK_QUALITY","0"),Gb(lB,"lastPingTime",0);var dB=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._eventMap=new Map,this._captureCostSum=0,this._captureCostCount=0,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=pN.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&wP(this[e])&&(this[e]=function(e){let{fn:t,context:r}=e;return function(){try{for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];let o=t.apply(r,i);return VP(o)?o.catch((e=>pN.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(gw){pN.error("".concat(t.name,"() error observed ").concat(gw))}}}({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:pR,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,ND().then((e=>{this._basicInfo.string_os_version=VD(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),KD.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(uN.JOIN_START,this.handleJoinStart).addEvent(uN.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(uN.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(uN.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(uN.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(uN.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(uN.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(uN.JOIN_FAILED,this.handleJoinFailed).addEvent(uN.LEAVE_START,this.handleLeaveStart).addEvent(uN.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(uN.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(uN.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(uN.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(uN.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(uN.PUBLISH_START,this.handlePublishStart).addEvent(uN.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(uN.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(uN.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(uN.PLAY_TRACK_START,this.handlePlayStart).addEvent(uN.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(uN.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:r,type:i}=e;!xP(t)||!this.hitTest(t.room)||"PLAYING"===r&&(i===WR.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(uN.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(uN.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(uN.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(uN.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;if(!this.hitTest(t))return;let n=r.hasAudio||r.hasVideo||r.hasSmall,o=r.hasAuxiliary,s=i.hasAudio||i.hasVideo||i.hasSmall,a=i.hasAuxiliary;!n&&s&&this.handleRemoteStreamAdded(i.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(i.userId,"auxiliary")})).addEvent(uN.SINGLE_CONNECTION_STAT,(e=>{let{room:t,stat:r}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=r.ice,this._pathJoinRoom.int32_dtls_cost=r.dtls,this._pathJoinRoom.int32_peer_connection_cost=r.peerConnection)}))}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach(((e,t)=>KD.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),VO.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&&(kP(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),kP(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),kP(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:r}=e;if(this.hitTest(t)&&r){let{totalCost:e,local:t,dns:i,tcp:n,tls:o,request:s,response:a}=r;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=i,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:r}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),r&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=r instanceof sR?Number(r.getExtraCode()||r.getCode()):nR.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:r}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=r.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var r;let i="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(i)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Fb(Ub({},hB),{msg_user_info:new pB({userId:e,tinyId:null==(r=this._room.remotePublishedUserMap.get(e))?void 0:r.tinyId,role:20})})};n.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(i,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:r,streamType:i,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=r,c=new pB({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(i),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===i?(r.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),r.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):r.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:r,streamType:i}=e;if(this.hitTest(t)){let e="".concat(r.userId,"_").concat(i),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!xP(t)||!this.hitTest(t.room))return;let r="".concat(t.userId,"_").concat(t.streamType),i=this._remoteStreamStatMap.get(r);0===(null==i?void 0:i.playStreamTime)&&(i.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!xP(t)||!this.hitTest(t.room))return;let r="".concat(t.userId,"_").concat(t.streamType),i=this._pathMainVideoMap.get(r);i&&0===i.statsToReport.uint64_combine_first_frame_time&&(i.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),r=Date.now(),i=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(i&&(0===i.statsToReport.uint64_render_first_frame_time&&(i.statsToReport.uint64_render_first_frame_time=r),n)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=n;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=r-i.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&n){let{statsToReport:e,playStreamTime:t,subscribedTime:i}=n;0===e.uint32_video_render_first&&t-i<=100&&(e.uint32_video_render_first=r-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),r=this._pathMainAudioMap.get(t);r&&0===r.statsToReport.uint64_play_first_frame_time&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:r,userId:i,videoDelay:n,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(s)s.totalRTT+=t,s.totalLoss+=r,n&&(s.totalVideoDelay=(s.totalVideoDelay||0)+n,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;n&&(s=n,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(i,{totalRTT:t,totalLoss:r,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_device_info:t,msg_up_stream_info:r,msg_down_stream_info:i}=e.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:t,uint32_video_width:i,uint32_video_height:n}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=t,this._localStreamStat.totalVideoWidth+=i,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:e}=r.msg_audio_status;Math.floor(e/Xw*100)>0&&(this._localStreamStat.totalAudioLevel+=e/Xw,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:r,msg_video_status:i}=e,n=t.str_identifier,o=this._room.remotePublishedUserMap.get(n);if(i.forEach((e=>{let t=2===e.uint32_video_stream_type,r=7===e.uint32_video_stream_type,i="".concat(n,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(i);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||r&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let r=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;r.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=r.stat.jitterBufferDelay),r.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(r.stat.framesDecoded/r.stat.framesReceived*xb(10,6)))}})),r){let e="".concat(n,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=r.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(r.uint32_audio_level/Xw*100)>0&&(t.totalAudioLevel+=r.uint32_audio_level/Xw,t.audioLevelCount++))}})),t.uint32_audio_capture_cost&&(this._captureCostSum+=t.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:r}=e,i={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[r.name]||(r instanceof sR?r.getExtraCode()||r.getCode():nR.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=i,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=i,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&JR))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&YR))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&KR))>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:r}=e,i=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(i){let{totalLoss:t,count:r,audioDelayCount:n,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=i;e.statsToReport.uint32_avg_down_loss=Math.floor(t/r),n&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/n),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,WR.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,WR.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,uB);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>uB&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+uB):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>uB&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+uB):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>uB&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+uB)}getReportData(){this._basicInfo.uint32_networkType=_P();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new pB({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:KP(this._signalInfo.relayIp),uint32_client_ip:KP(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*xb(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:KP(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return aN(e),e}report(){return $b(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(yN){this._log.warn(yN)}finally{this.isDestroyed&&(this._room=null)}}))}upload(e){return $b(this,null,(function*(){if(0===e.msg_path_enter_room.uint64_start_time)return;let t=Number(this._room.sdkAppId),r=yield Yw(e),i=r instanceof ArrayBuffer,n="".concat(uP(t,NR.KEY_POINT),"&gzip=").concat(+i),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,r));let s=[this.uploadKVStat(DN),this.uploadKVStat(kN)];o||s.push(Kw({url:n,body:r})),yield Promise.all(s)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return $b(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=Fb(Ub({},t.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(t);let r=yield Yw(t),i="".concat(uP(+this._room.sdkAppId,NR.KV_STAT),"&gzip=").concat(+(r instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(i,r)),n||Kw({url:i,body:r})}))}};Wb([GO({settings:{timeout:500,retries:3}})],dB.prototype,"upload",1);var uB=5e3,hB={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},pB=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},mB=dB,fB=class{constructor(){Gb(this,"_startTime"),Gb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=HP())}stop(){0===this._endTime&&(this._endTime=HP())}getDuration(){return 0===this._endTime?HP()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},_B=class{constructor(e){Gb(this,"_room",null),Gb(this,"_durationMap"),Gb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(uN.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(uN.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(uN.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;var n;let{userId:o}=i;if(!this.hitTest(t))return;r.hasAudio&&!i.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),WR.AUDIO),r.hasVideo&&!i.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),WR.VIDEO),r.hasAuxiliary&&!i.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),WR.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!r.hasAudio&&i.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,WR.AUDIO,"main"),!r.hasVideo&&i.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,WR.VIDEO,"main"),!r.hasAuxiliary&&i.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,WR.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>KD.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>KD.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:r,remotePublishedUser:i}=e;if(!this.hitTest(t))return;let{userId:n}=i,o="".concat(n,"_").concat(r);if(i.muteState.hasAudio&&"main"===r)if(i.remoteAudioTrack.isSubscribed){let e=new fB,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:n,type:r,audio:[e],video:[]})}else this.stopDurationItem(o,WR.AUDIO);if(i.muteState.hasVideo||i.muteState.hasAuxiliary)if(i.remoteVideoTrack.isSubscribed||i.remoteAuxiliaryTrack.isSubscribed){let e=new fB,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:n,type:r,audio:[],video:[e]})}else this.stopDurationItem(o,WR.VIDEO)}handleStreamStopped(e){let{room:t,streamType:r,remotePublishedUser:i}=e;if(!this.hitTest(t))return;let{userId:n}=i,o="".concat(n,"_").concat(r);this.stopDurationItem(o,WR.AUDIO),this.stopDurationItem(o,WR.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,r){let i="".concat(e,"_").concat(r),n=new fB,o=this._durationMap.get(i);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(i,{userId:e,type:r,audio:t===WR.AUDIO?[n]:[],video:t===WR.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let r=this._durationMap.get(e)[t].find((e=>0===e.endTime));r&&r.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},gB=class{constructor(e){Gb(this,"_room"),Gb(this,"_renderFreezeMap",new Map),Gb(this,"_isVideoPlayingEventFiredMap",new Map),Gb(this,"_dataFreezeMap",new Map),Gb(this,"_monitorFreezeData",new Map),Gb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(uN.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(uN.PLAY_TRACK_START,this.onPlayTrackStart).set(uN.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:r,remotePublishedUser:i}=e;if(!this.hitTest(t))return;let{userId:n}=i,o="".concat(n,"_").concat(r);this.stopDataFreeze({key:o,userId:n,type:r})})).set(uN.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:r,muteState:i}=e;if(!this.hitTest(t))return;let{userId:n}=i;if(r.hasVideo&&!i.hasVideo){let e="main",t="".concat(i.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}if(r.hasAuxiliary&&!i.hasAuxiliary){let e="auxiliary",t="".concat(i.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:n,type:e})}})).set(uN.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:r,reason:i,type:n}=e;if(xP(t)&&this.hitTest(t.room)&&n===WR.VIDEO){if("PLAYING"===r){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}i===WR.MUTE?this.onVideoTrackMuted(t):i===WR.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(uN.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>KD.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>KD.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:r}=e,i="".concat(t,"_").concat(r),n=this._dataFreezeMap.get(i),o=new fB;n?n.durationItemList.push(o):this._dataFreezeMap.set(i,{userId:t,type:r,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:r}=e,i="".concat(t,"_").concat(r);this.stopDataFreeze({key:i,userId:t,type:r})}onHearBeatReport(e){let{room:t,report:r}=e;!this.hitTest(t)||r.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:r,muteState:i}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&i.hasVideo&&!i.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&i.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:r,type:i}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let o=n.durationItemList[n.durationItemList.length-1];o.stop();let s=o.getDuration();s>Rw?this._monitorFreezeData.set(t,{userId:r,type:i,duration:s}):n.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)}),0)}handleRenderFreeze(e){return $b(this,arguments,(function(e){var t=this;let{userId:r,fps:i,type:n}=e;return function*(){let e="".concat(r,"_").concat(n),o=t._renderFreezeMap.get(e);if(i<=2){let i=HP();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:i,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:r,type:n,isFreeze:!0,freezeTimeline:[{startTime:i,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=HP();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!xP(t)||!this.hitTest(t.room)||t.kind!==WR.VIDEO||t.hasFlag)return;let r="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(r)||this._isVideoPlayingEventFiredMap.set(r,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},r=this._dataFreezeMap.get(e);if(r){if(r.isFreezing()){let e=r.durationItemList[r.durationItemList.length-1];e.stop(),e.getDuration()<Rw&&r.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(r.durationItemList),t.count=r.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),r=0,i=0;if(t)if(t.isFreeze){let e=HP()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;r=t.renderFreezeTotal+Math.min(e,5e3),i=t.freezeTimeline.length}else r=t.renderFreezeTotal;return{renderFreeze:r,count:i}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},vB=Hb(Jb(),1),yB=[1,0,0,0,1,1,0,1],EB=class extends VL{constructor(e,t){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:t}),e instanceof Nx)try{this.setTexBuffer(yB)}catch(gw){e.destroy(new sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(gw.message||gw)}))}}draw2d(e,t,r,i,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(e,t,r,i,n);return this.ctx2d.restore(),o}return!1}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},TB=class{constructor(e,t){this.node=e,this.layout=t,Gb(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}},SB=class extends VL{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Gb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new TB(e,t);this.inputs[t.zIndex]=r}resize(e,t){let r=this.inputs.reduce(((e,t)=>t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e),{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Nx&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,r)=>(!r||!r.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,r)=>(!r||!r.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:i,height:n,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:r,width:i,height:n,timestamp:s,fps:a,name:o},Ub({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,r;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof Nx))try{null==(r=this.context.ctx)||r.deleteBuffer(e.positionBuffer)}catch(i){}}))}},IB=class extends kx{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),Gb(this,"_bgTexture"),Gb(this,"_waterMarkTexture"),Gb(this,"_lastMaskTexture"),Gb(this,"_lastMaskFbo"),Gb(this,"_textureValid",!1),Gb(this,"_selfieTextureValid",!1),Gb(this,"_selfieSegmentation"),Gb(this,"wasm"),Gb(this,"_prePrograme"),Gb(this,"_segmentationMask"),Gb(this,"_weixin",!1),t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(t)}catch(_R){e.log.error(_R),e.destroy(new sR({code:nR.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(_R.message||_R)}))}}init(e){var t,r;let i=e.Wasm,n=this.context.ctx;if(this.wasm=new i.AllIn1(n),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:r,width:i,height:n}=e.waterMark;this.wasm.setWaterMark(t,r,i,n)}if(e.beautyParams){let{beauty:i,brightness:n,ruddy:o}=e.beautyParams;this.wasm.setBeauty(i,n,o,null==(t=this.context._canvas)?void 0:t.width,null==(r=this.context._canvas)?void 0:r.height)}if(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)),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)}}onPredict(e){var t;let r=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),r.activeTexture(r.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),r.drawArrays(r.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var t,r,i,n;let o=this.context.ctx,{image:s}=this;this.tryVideoFrameCallback(s);let{videoWidth:a,videoHeight:c}=s;s.width=a,s.height=c;let l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(t=this._selfieSegmentation)||t.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===a&&this.height===c&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(a,c),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(r=this._selfieSegmentation)||r.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(i=this._selfieSegmentation)||i.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,a,c):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,a,c,0)),null==(n=this._selfieSegmentation)||n.send(a,c),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},AB=class extends vB.EventEmitter{constructor(e){super(),this.room=e,Gb(this,"videoContext"),Gb(this,"_glVideoContext"),Gb(this,"_2dVideoContext"),Gb(this,"destination"),Gb(this,"smallVideoContext"),Gb(this,"smallDestination"),Gb(this,"smallTrackSource"),Gb(this,"smallImageSource"),Gb(this,"_isMirror",!1),Gb(this,"cameraTrack"),Gb(this,"cameraNode"),Gb(this,"mirrorNode"),Gb(this,"mixNode"),Gb(this,"screenTrack"),Gb(this,"screenNode"),Gb(this,"selfModel",!1),Gb(this,"blurRadius",3),Gb(this,"arTrack"),Gb(this,"Wasm"),Gb(this,"waterMarkNode"),Gb(this,"_waterMarkOption"),Gb(this,"watermarkImageList",[]),Gb(this,"_beautyParams"),Gb(this,"isUsingArTrack",!1),Gb(this,"_isMixScreen",!1),Gb(this,"_virtualBackground"),Gb(this,"_virtualBackgroundAbortCallback"),Gb(this,"virtualBackgroundInstance"),Gb(this,"_bgAssetPath"),Gb(this,"log",pN.createLogger({id:"vm"})),Gb(this,"_checkId",0),Gb(this,"_use2d",!1),Gb(this,"_autoSwitchRenderMode",!0),Gb(this,"_selfieSegmentation"),Gb(this,"encodePipeline",[]),Gb(this,"decodePipeline",[]),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ox({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode="auto"===e,this._autoSwitchRenderMode)return;let t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ox({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 Nx({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("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(fR){this.emit("error",fR)}}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=VO.run(zw,(()=>{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(),VO.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(vD||this._isMixScreen||this._isMirror||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?DN.addFailedEvent({key:t,error:e}):DN.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 Nx({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}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:i,settings:n,player:o}=r;i?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new bx(this.smallVideoContext,i,this.log)),this.smallVideoContext.frameRate=i.frameRate,this.smallDestination.resolution=i,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),vD&&o.setCanvas(e);let s=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),s=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(s?s.label:"no output track")),r.setOutputMediaStreamTrack(s)}catch(_R){this.log.error("set main output failed",_R)}}update(){return $b(this,null,(function*(){var e,t;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:i}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===SD?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof kx?(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 kx?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(r.width,r.height)):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Cx(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new IB(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()),this.videoContext.frameRate=i.frameRate,this._use2d){let r=this.cameraNode;r.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new EB(this.videoContext,this.log)),r=r.connect(this.mirrorNode),r.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new SB(this.videoContext,this.log),r.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),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),r=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),r.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,r,i,n;if(e instanceof bL)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof SL)return this.log.info("change video input",null==(r=e.mediaTrack)?void 0:r.label),this.setCameraTrack(e);if(e instanceof Mx){this.log.info("change remote input",null==(i=e.mediaTrack)?void 0:i.label);let t=e.mediaTrack;return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof bL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof SL?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Mx&&e.source&&e.source.context.destroy()}setCameraTrack(e){return $b(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return $b(this,null,(function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let i=r.getContext("2d");if(!i)throw new sR({code:nR.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort(((e,t)=>e.zIndex-t.zIndex)),this.watermarkImageList.forEach((e=>{let{image:t,x:r,y:n,width:o,height:s}=e;i.drawImage(t,r,n,o,s)})),oN(r.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setBeautyParams(e){return $b(this,null,(function*(){this._beautyParams=e,this.update()}))}stopBeauty(){return $b(this,null,(function*(){this._beautyParams=void 0,this.update()}))}setWatermark(e){return $b(this,null,(function*(){var t,r;let i;try{i=yield oN((null==e?void 0:e.imageElement)||e.imageUrl)}catch(d){throw new sR({code:nR.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:n=0,y:o=0,width:s=i.width,height:a=i.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some((e=>e.type===c))?(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==c)),this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:i,zIndex:l,type:c,imageUrl:e.imageUrl}),i=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(r=this.cameraTrack)?void 0:r.settings.height),this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(i.width,i.height),this.waterMarkNode.image=i):this.update()):(this.pushWaterMarkImageList({x:n,y:o,width:s,height:a,image:i,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,((e,t)=>"imageUrl"===e?void 0:t)))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return $b(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 $b(this,null,(function*(){var e,t,r;null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let i=yield this.getWatermarkImage(null==(t=this.cameraTrack)?void 0:t.settings.width,null==(r=this.cameraTrack)?void 0:r.settings.height);this._waterMarkOption={x:0,y:0,width:i.width,height:i.height,image:i},this.update()}))}setVirtualBackground(e){return $b(this,null,(function*(){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 oN(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}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 sR({code:nR.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._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return $b(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()}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:r}=e;var i;this.encodePipeline.includes(t)||(this.encodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:r}=e;var i;this.decodePipeline.includes(t)||(this.decodePipeline[r]=t,null==(i=this.room)||i.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}},CB=0,bB=class extends NO{constructor(e){super("room"),this.seq=++CB,this.role="anchor",this.joinParams=null,this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,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}},this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=pN.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,NP(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),NP(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),NP(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new mB({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new _B({room:this}),this.badCaseDetector=new gB({room:this}),this.audioManager=new DL(this),this.videoManager=new AB(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return $b(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return $b(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return $b(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(DP(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(AP(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:i,scheduleProxy:n,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=o,o?(iP([o,o]),SR("https://".concat(o))):(i&&SR(i),n&&iP(n))}KD.once(uN.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:rP.main,sched_back_domain:rP.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return $b(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return $b(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)t.downlinksRTT[r.userId]=r.rtt;return t}))}getRemoteVideoStats(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let r={};return e.remotePublishedUserMap.forEach((e=>{let i="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;r[e.userId]=i.stat})),r}()}))}checkDestroy(){if(this.isDestroyed)throw new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Zw.INVALID_DESTROY),new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.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,KD.emit(uN.ROOM_DESTROY,{room:this})}schedule(e,t){return $b(this,null,(function*(){var r,i;let n=HP();try{let{isCached:o,result:s,detailCost:a}=yield tP({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:pR,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(tN(s,{keysToExclude:["username","credential"]}))),o&&KD.once(uN.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=Ub(Ub({},this.scheduleResult),s),PP(null==(r=s.config)?void 0:r.retryCount)&&fw(s.config.retryCount),DP(null==(i=s.config)?void 0:i.loggerDomain)&&SR(s.config.loggerDomain),KD.emit(uN.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),DN.addSuccessEvent({key:521700,cost:HP()-n,split:50})}catch(o){throw DN.addFailedEvent({key:521700,error:o}),o}}))}},RB=Hb(Jb(),1),wB=Symbol("instance"),kB=Symbol("cacheResult"),DB=class{constructor(e,t,r){this.oldState=e,this.newState=t,this.action=r,this.aborted=!1}abort(e){this.aborted=!0,LB.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},PB=class extends Error{constructor(e,t,r){super(t),this.state=e,this.message=t,this.cause=r}};var NB=new Map;function OB(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(i,n,o)=>{let s=r.action||n;if(!r.context){let r=NB.get(i)||[];NB.has(i)||NB.set(i,r),r.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let i=this;for(var n=arguments.length,o=new Array(n),c=0;c<n;c++)o[c]=arguments[c];if(r.context&&(i=xB.get("function"==typeof r.context?r.context.call(this,...o):r.context)),i.state===t)return i[kB];i.state instanceof DB&&i.state.action==r.abortAction&&i.state.abort(i);let l=null;if(Array.isArray(e)?0==e.length?i.state instanceof DB&&i.state.abort(i):("string"!=typeof i.state||!e.includes(i.state))&&(l=new PB(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not in from config"))):e!==i.state&&(l=new PB(i._state,"".concat(i.name," ").concat(s," to ").concat(t," failed: current state ").concat(i._state," not from ").concat(e))),l){if(!r.fail){if(r.ignoreError)return l;throw l}r.fail.call(this,l)}let d=i.state,u=new DB(d,t,s);LB.call(i,u);let h=e=>{var n;return i[kB]=e,u.aborted||(LB.call(i,t),null===(n=r.success)||void 0===n||n.call(this,i[kB])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(LB.call(i,d,e),!r.fail){if(r.ignoreError)return e;throw e}r.fail.call(this,new PB(i._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var MB="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 LB(e,t){let r=this._state;this._state=e;let i=e.toString();e&&this.emit(i,r),this.emit(xB.STATECHANGED,e,r,t),this.updateDevTools({value:e,old:r,err:t instanceof Error?t.message:String(t)})}var xB=class extends RB.default{constructor(e,t,r){super(),this.name=e,this.groupName=t,this._state=xB.INIT,e||(e=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let i=r[wB];i?this.name=i.name+"-"+i.count++:r[wB]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=NB.get(e)||[],r=new Set,i=[],n=[],o=new Set,s=Object.getPrototypeOf(e);NB.has(s)&&(s.stateDiagram.forEach((e=>r.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:r,action:o}=e;"string"==typeof t?i.push({from:t,to:r,action:o}):t.length?t.forEach((e=>{i.push({from:e,to:r,action:o})})):n.push({to:r,action:o})})),i.forEach((e=>{let{from:t,to:i,action:n}=e;o.add(t),o.add(i),o.add(n+"ing"),r.add("".concat(t," --\x3e ").concat(n,"ing : ").concat(n)),r.add("".concat(n,"ing --\x3e ").concat(i," : ").concat(n," 🟢")),r.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🔴"))})),n.forEach((e=>{let{to:t,action:i}=e;r.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🟢")),o.forEach((e=>{e!==t&&r.add("".concat(e," --\x3e ").concat(i,"ing : ").concat(i))}))}));let a=[...r];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=xB.instances.get(e),t||xB.instances.set(e,t=new xB(e,void 0,Object.create(xB.prototype)))):(t=xB.instances2.get(e),t||xB.instances2.set(e,t=new xB(e.constructor.name,void 0,Object.create(xB.prototype)))),t}static getState(e){var t;return null===(t=xB.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};MB(xB.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){LB.call(this,e)}};xB.STATECHANGED="stateChanged",xB.UPDATEAFSM="updateAFSM",xB.INIT="[*]",xB.ON="on",xB.OFF="off",xB.instances=new Map,xB.instances2=new WeakMap;var VB=Hb(Jb()),UB=Hb(tR());function FB(e){var t;let r=[];for(let i=0;i<e.rtp.length;i++){if(["rtx","red","ulpfec"].includes(e.rtp[i].codec))continue;let n=e.fmtp.filter((t=>t.payload===e.rtp[i].payload))[0];r.push({payload:e.rtp[i].payload,codec:e.rtp[i].codec,fmtp:n?n.config:"",rate:e.rtp[i].rate,rtx:"rtx"===(null==(t=e.rtp[i+1])?void 0:t.codec)?e.rtp[i+1].payload:0,rtcpFb:((null==e?void 0:e.rtcpFb)||[]).filter((t=>t.payload===e.rtp[i].payload)).map((e=>{let{type:t,subtype:r}=e;return{id:t,params:r?[r]:[]}}))})}return r}var BB=(e,t)=>$b(void 0,null,(function*(){var r;let i=KF(e),n={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};n.ice.ufrag=String(i.media[0].iceUfrag),n.ice.password=i.media[0].icePwd||"",i.fingerprint&&(n.dtls.hash=i.fingerprint.type,n.dtls.fingerprint=i.fingerprint.hash,n.dtls.setup=i.setup||""),i.media[0].fingerprint&&(n.dtls.hash=i.media[0].fingerprint.type,n.dtls.fingerprint=i.media[0].fingerprint.hash),n.dtls.setup=i.media[0].setup||"";let o=i.media[0],s=i.media[1];o.ext&&(n.audio.extensions=o.ext.map((e=>({id:e.value,uri:e.uri})))),s.ext&&(n.video.extensions=s.ext.map((e=>({id:e.value,uri:e.uri}))));let a={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channel:o.rtp[0].encoding,rtcpFb:[],rtx:0};null==(r=o.rtcpFb)||r.forEach((e=>{let{payload:t,type:r,subtype:i}=e;if(t===a.payload){let e={id:r,params:[]};i&&e.params.push(i),a.rtcpFb.push(e)}})),n.audio.codecs.push(a);let c=["h264","vp8"];return t&&c.shift(),n.video.codecs=[...FB(s)].filter((e=>c.includes(e.codec.toLocaleLowerCase()))),n.video.decoders=(yield function(){return $b(this,null,(function*(){let e=new RTCPeerConnection;e.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_RECVONLY});let t=yield e.createOffer();if(!t.sdp)return[];let r=FB(KF(t.sdp).media[0]);return e.close(),r}))}()).filter((e=>["h264","vp8"].includes(e.codec.toLocaleLowerCase()))),n})),jB=e=>{let{serverAbility:t,clientAbility:r,offerSDP:i,enableCustomMessage:n}=e,o=KF(i),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:WR.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:WR.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(HB({mid:e,serverAbility:t,clientAbility:r,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),YF(s)},HB=e=>{let{mid:t,serverAbility:r,clientAbility:i,parsedOffer:n,isDownlink:o=!1}=e,s={candidates:r.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:WR.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:WR.VIDEO,setup:r.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o)(r.video.decoders||r.video.codecs).forEach((e=>{WB(s,e)}));else{let e=r.video.codecs.findIndex((e=>e.codec.toLowerCase()===(r.useVp8?"vp8":"h264"))),t=r.video.codecs[e]||i.video.codecs[0];WB(s,t)}return s},WB=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var GB=(e,t,r)=>{let i=UB.default.parse(e);return i.media.forEach(((e,n)=>{var o;(e.type===WR.AUDIO||e.type===WR.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((r,i)=>{var n;t.push(r),e.rtcpFb&&(null==(n=e.rtcpFb[i+1])?void 0:n.payload)!==r.payload&&"rrtr"!==r.type&&t.push({payload:r.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===WR.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===WR.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e),e.type===WR.VIDEO&&(n<4?(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((t=>WB(e,t)))):r&&(e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],(r.video.decoders||r.video.codecs).forEach((t=>WB(e,t)))))),(null==(o=e.payloads)?void 0:o.includes("datachannel"))&&i.groups&&e.mid&&(i.groups[0].mids=i.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),UB.default.write(i)},zB=Hb(Jb()),$B=class extends zB.EventEmitter{constructor(e){super(),this.room=e,Gb(this,"mainFpsHealth",1),Gb(this,"mainBitrateHealth",1),Gb(this,"badMainBitrateHealthCount",0),Gb(this,"lastEmitBadHealthTime",0),Gb(this,"log"),!hk&&hD&&KD.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:r,isHWCodec:i,codec:n}=e;if(!t&&7!==r&&"h264"===n){if(!i)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let t=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(this.mainFpsHealth=t)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){let{localMainVideoTrack:t}=this.room;t&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/t.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){KD.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Gb($B,"EVENT_BAD_HEALTH","bad_health");var JB=$B;function qB(e){let{seiMessageList:t,isAudio:r}=e;return new TransformStream({transform(e,i){let n=e;r?audioEncodePipeline.forEach((e=>{n=e({frame:n})})):videoEncodePipeline.forEach((e=>{n=e({frame:n,seiMessageList:t})})),i.enqueue(n)}})}function KB(e,t){return new TransformStream({transform(r,i){let n=r;videoDecodePipeline.forEach((r=>{n=r({frame:n,onSEI:r=>{r.forEach((r=>{self.postMessage({type:"sei",seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e,streamType:t})}))}})})),i.enqueue(n)}})}var YB,XB=((YB=XB||{}).TRACK="track",YB.DATA_CHANNEL_MESSAGE="data_channel_msg",YB[YB.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",YB[YB.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",YB.RECONNECTED="spc-reconnected",YB.RECONNECT_FAILED="spc-reconnect-failed",YB.ERROR="error",YB.SEI_MESSAGE="sei-message",YB),QB=0,ZB=!1,ej=new Set,tj=1,rj=class extends VB.default{constructor(e){let{signalChannel:t,room:r,enableCustomMessage:i}=e;super(),Gb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Gb(this,"currentState","DISCONNECTED"),Gb(this,"_room"),Gb(this,"_signalChannel"),Gb(this,"_peerConnection",null),Gb(this,"_datachannel",null),Gb(this,"_enableCustomMessage"),Gb(this,"_log"),Gb(this,"_downlinkMIDMap",new Map),Gb(this,"_downlinkMIDUserIDMap",new Map),Gb(this,"_reconnectionTimer",-1),Gb(this,"reconnectionCount",0),Gb(this,"clientAbility"),Gb(this,"_serverAbility",null),Gb(this,"addDownlinkQueue",new Set),Gb(this,"removeDownlinkQueue",new Set),Gb(this,"_parsedAnswer",null),Gb(this,"_updateSDPPromise",null),Gb(this,"_waitForPCConnectedPromise"),Gb(this,"clearConnectTimeout"),Gb(this,"_isSDPLogged",!1),Gb(this,"enableInsertableStreams",!1),Gb(this,"insertableStreamsAbortMap",new Map),Gb(this,"scriptTransformWorker"),Gb(this,"_isRelayTried",!1),Gb(this,"_rttOverCount",0),this._room=r,this._enableCustomMessage=i,this._signalChannel=t,this._log=pN.createLogger({id:"spc".concat(tj++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(hO?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}addAbortController(e,t){var r;null==(r=this.insertableStreamsAbortMap.get(e))||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((e=>"vp8"===e.codec.toLowerCase()))),e}get videoCodec(){var e,t;let r=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((e=>["h264","vp8"].includes(e.codec.toLowerCase())));return r?r.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((e=>"h264"===e.codec.toLowerCase()))?"h264":"vp8"}get isUsingH264(){return"h264"===this.videoCodec}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f")))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=KF(e),r={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var i;if(e.ssrcs&&!kP(e.ssrcs[0].id)){let n=Number(e.ssrcs[0].id),o=Number(null==(i=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:i.id);switch(t){case 0:r.audioSsrc=n;break;case 1:r.bigVideoSsrc=n,r.bigVideoRtxSsrc=o;break;case 2:r.smallVideoSsrc=n,r.smallVideoRtxSsrc=o;break;case 3:r.auxVideoSsrc=n,r.auxVideoRtxSsrc=o}}})),r})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){let{isAux:t}=e;this.useHWEncoder(!1,t?7:2)}initScriptTransformWorker(){pO&&(this.scriptTransformWorker=function(e){let t=[EL],r=[zV,WV,GV,HV,qB,KB],i="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map((e=>"const ".concat(e.name,"=(()=>").concat(e.toString(),")()"))).join("\n"),"\n").concat(r.map((e=>e.toString())).join("\n"),";(").concat((()=>{let e=[],t=[],r=[];self.onmessage=i=>{"sei"===i.data.type&&(i.data.isMain?(e.push(i.data.data),i.data.small&&r.push(i.data.data)):t.push(i.data.data))},self.onrtctransform=i=>{let{options:n}=i.transformer,o=n.isReceiver?KB(n.userId,n.streamType):qB({seiMessageList:n.isMain?n.small?r:e:t});i.transformer.readable.pipeThrough(o).pipeTo(i.transformer.writable)}}),")();").concat(i,"})()"),o=new Blob([n],{type:"text/javascript"}),s=URL.createObjectURL(o),a=new Worker(s);return URL.revokeObjectURL(s),a}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{"sei"===e.data.type&&this.emit("sei-message",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return $b(this,null,(function*(){var e;let t;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime?(this.stat.iceEndTime=Date.now(),DN.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):"failed"===e&&DN.addFailedEvent({key:521711})},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new nj(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(WR.AUDIO,{direction:WR.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield BB(t.sdp,(null==(e=this._room.scheduleResult.config)?void 0:e.remove264FromSDP)||!1),yield this.setOffer(t),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),DN.addSuccessEvent({key:521707}),this.clientAbility}catch(_R){throw DN.addFailedEvent({key:521707,error:_R}),this._log.error("initialize failed ".concat(_R," \noffer: ").concat(null==t?void 0:t.sdp)),_R}}))}setPriority(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((t=>{let r=t.getParameters();r.encodings[0]&&(r.encodings[0].priority=e,r.encodings[0].networkPriority=e,t.setParameters(r).catch((e=>{this._log.warn("setPriority error ",e)})))}))}catch(gw){this._log.warn("setPriority error ",gw)}}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return $b(this,null,(function*(){var r,i;try{if("CONNECTED"===this.currentState)return;let n=HP(),o={type:"answer",sdp:jB({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected();let s=(null==(r=this._room.scheduleResult.config)?void 0:r.priority)||(null==(i=this._room.joinParams)?void 0:i.priority)||new URLSearchParams(location.search).get("priority");s&&this.setPriority(s),t||DN.addSuccessEvent({key:521703,cost:HP()-n})}catch(gR){let r=gR instanceof sR&&gR.code===nR.API_CALL_ABORTED;throw r||this._log.error("connect failed: ".concat(gR),e),this.reset(),!r&&!this.isReconnecting&&(DN.addFailedEvent({key:521703,error:gR}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),gR}}))}reconnect(){return $b(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(iF,this.reconnect,this);try{this.reconnectionCount++,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:OF,responseCommand:lF.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new sR({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),DN.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),KD.emit(uN.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(fR){if(!this.isReconnecting)return;if(null!=fR&&fR.message.includes("timeout")){let e=bP(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield cN(e,(e=>{this._reconnectionTimer=e})),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(null==fR?void 0:fR.code," ").concat(fR)),DN.addFailedEvent({key:521704,error:fR}),this.reconnectionCount>=_w()&&this._log.warn("SDK has tried reconnect for ".concat(_w()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return $b(this,null,(function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())}))}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(iF,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===pw.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(r)),e.target.connectionState===pw.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===pw.FAILED||e.target.connectionState===pw.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===pw.CONNECTED||e.target.connectionState===pw.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),KD.emit(uN.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return hw;let e=null;return tO()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,eO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:hw):hw}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(XB.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return $b(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(JN(r)){let t=e.get(r.localCandidateId),i=e.get(r.remoteCandidateId);t&&(this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),t.networkType&&fP(t.networkType)),i&&this._log.info("remote candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();let r=t=>{"CONNECTED"===t.state&&(clearTimeout(o),n(),e())},i=e=>{let{room:r}=e;r===this._room&&(clearTimeout(o),n(),t(new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{KD.off(uN.LEAVE_SUCCESS,i,this),this.off(XB.CONNECTION_STATE_CHANGED,r,this)},o=setTimeout((()=>{n();let e=new sR({code:nR.API_CALL_TIMEOUT,message:"connection timeout"});QB+=1,(e=>QB>2&&!ZB&&0===ej.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),ZB=!0,this.emit(XB.FIREWALL_RESTRICTION)),t(e)}),Pw);this.clearConnectTimeout=()=>{n(),clearTimeout(o),delete this.clearConnectTimeout},KD.on(uN.LEAVE_SUCCESS,i,this),this.on(XB.CONNECTION_STATE_CHANGED,r,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return $b(this,null,(function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(gw){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(gw)),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:r,tinyId:i}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(r," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=WR.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=KF(this._peerConnection.remoteDescription.sdp));let o,s,a,c=this._parsedAnswer.media.filter((e=>{var t;return null==(t=e.ssrcs)?void 0:t.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(i)}))}));if(3===c.length)o=c[0],s=c[1],a=c[2];else if(3===n.length)o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[0]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[1]))),a=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(n[2])));else if(0===n.length){this._peerConnection.addTransceiver(WR.AUDIO,{direction:WR.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(WR.VIDEO,{direction:WR.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=HB({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:KF(this._peerConnection.localDescription.sdp),isDownlink:!0});s=JSON.parse(JSON.stringify(e)),a=JSON.parse(JSON.stringify(e)),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a)}o.direction=WR.TRANSCEIVER_DIRECTION_SENDONLY;let l="".concat(i,"-").concat(t.audio);o.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(WR.MAIN," ").concat(l,"-audio")}],s.direction=WR.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(WR.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(WR.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=WR.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(l,"-aux");a.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(WR.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(WR.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(WR.VIDEO)}],a.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(r,[o.mid,s.mid,a.mid]),this._downlinkMIDUserIDMap.set(o.mid,r),this._downlinkMIDUserIDMap.set(s.mid,r),this._downlinkMIDUserIDMap.set(a.mid,r)}removeDownlink(e){return $b(this,null,(function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(r=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=KF(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=t&&t.includes(Number(e.mid))&&(r=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),null==t||t.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(e,") done"))}))}setBandwidth(e){return $b(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:i,auxVideo:n}=e;try{if(cO()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&r?o=r:2===s&&i?o=i:3===s&&n&&(o=n),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;r&&e[1].track&&(o=this.setStartBitrate(1,r)),n&&e[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth: ".concat(o))}}))}setStartBitrate(e,t){var r,i;return!(null==(r=this._peerConnection)||!r.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=KF(this._peerConnection.remoteDescription.sdp)),null==(i=this._parsedAnswer.media[e])||!i.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]),"unlimited"===t?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=1e3*t,e.setParameters(r)}setBandwidthBySDP(e){let{audio:t,bigVideo:r,smallVideo:i,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=KF(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=KF(this._peerConnection.remoteDescription.sdp));let s=_k?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:_k?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:_k?1e3*t:t}]),r&&(o.media[1].bandwidth=[{type:s,limit:_k?1e3*r:r}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:_k?1e3*r:r}]),i&&(o.media[2].bandwidth=[{type:s,limit:_k?1e3*i:i}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:_k?1e3*i:i}]),n&&(o.media[3].bandwidth=[{type:s,limit:_k?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:_k?1e3*n:n}]);let a={type:"offer",sdp:YF(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t,r){let i=e.getParameters();(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]);let n=i.encodings[0].scaleResolutionDownBy;if(kP(n)?1===t:t===n)return;let o="setScaleResolutionDownBy ".concat(r," ").concat(t);return n&&(o+=" prevScale: ".concat(n)),this._log.warn(o),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=YF(this._parsedAnswer);return this._updateSDPPromise=new Promise(((r,i)=>$b(this,null,(function*(){var n,o;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(YB){this._log.error(YB),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(n=this._peerConnection.localDescription)?void 0:n.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==e?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(null==e?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:r,direction:i,stopped:n}=e;return{mid:t,currentDirection:r,direction:i,stopped:n}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,i(YB)}})))),this._updateSDPPromise}setTransceiverDirection(e,t){return $b(this,null,(function*(){if(!_k||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e)}));for(let i of t){let t=this._parsedAnswer.media[i].direction;e===GR.INACTIVE&&t===GR.RECVONLY&&(this._parsedAnswer.media[i].direction=e),e===GR.SENDONLY&&t===GR.INACTIVE&&(this._parsedAnswer.media[i].direction=GR.RECVONLY)}yield this.updateSDP()}))}filterSDPDirection(){return KF(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:GB(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return $b(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach((r=>{var i;if(r.type===WR.VIDEO){let n=this._serverAbility.video.codecs.find((t=>t.codec.toLowerCase()===e));n&&(null==(i=r.payloads)||!i.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],WB(r,n),t=!0)}})),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())}))}useHWEncoder(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return $b(this,null,(function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,i=[];kP(t)?i=this._parsedAnswer.media.slice(1,4):2===t?i.push(this._parsedAnswer.media[1]):3===t?i.push(this._parsedAnswer.media[2]):7===t&&i.push(this._parsedAnswer.media[3]),i.forEach((t=>{var i;if(t.type===WR.VIDEO){let n;e&&this.is42001fSupported?n=this.clientAbility.video.codecs.find((e=>e.fmtp.includes("42001f"))):e||(n=this._serverAbility.video.codecs.find((e=>e.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264")))),n&&(null==(i=t.payloads)||!i.includes(String(n.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],WB(t,n),r=!0)}})),r&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())}))}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((e=>GD(e.abort)&&e.abort("destroy"))),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}get isUsingRelay(){return"relay"===this._room.getIceTransportPolicy()}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:r}=e;var i;if("CONNECTED"!==this.currentState||this._isRelayTried&&!this._room.forceRelay||0===this._room.getIceServers().length)return;let n=this._signalChannel.rtt,o=Math.max(t,r),{rttRatioThreshold:s,rttThreshold:a}=(null==(i=this._room.scheduleResult.config)?void 0:i.useTurnTcpInfo)||{};if(!(s&&a&&n&&o))return;let c=Math.floor(o/n),l=(this._isRelayTried||c>s)&&o>a;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(r," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return $b(this,null,(function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",i=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(r));let t=Date.now();yield this.doSwitchRelay(r),this._log.warn("switchRelay ".concat(r," success")),DN.addSuccessEvent({key:i,cost:Date.now()-t})}catch(gR){this._log.warn("switchRelay ".concat(r," failed"),gR),DN.addFailedEvent({key:i,error:gR}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}}))}doSwitchRelay(e){return new Promise(((t,r)=>{let i=setTimeout((()=>{this.stopReconnection(),r(new Error("switch ".concat(e," timeout")))}),1e4);this.startReconnection().then(t,r).finally((()=>clearTimeout(i)))}))}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};Wb([pL("reconnect")],rj.prototype,"startReconnection",1),Wb([mL((e=>e.userId))],rj.prototype,"addDownlink",1),Wb([mL((e=>e))],rj.prototype,"removeDownlink",1),Wb([hL(!0)],rj.prototype,"updateSDP",1),Wb([fL(521712,!1)],rj.prototype,"setOffer",1),Wb([fL(521713,!1)],rj.prototype,"setAnswer",1);var ij=class{constructor(e){Gb(this,"tag"),Gb(this,"len"),Gb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},nj=class{constructor(e){Gb(this,"tinyId"),Gb(this,"data");let t=new DataView(e),r=0,i=[];for(;r<t.byteLength;){let n=t.getUint16(r+2),o=new ij(new Uint8Array(e).slice(r,r+2+2+n).buffer);i.push(o),r+=4+n}i.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},oj=new Set;function sj(){let e=Math.floor(4294967296*Math.random());return oj.has(e)?sj():(oj.add(e),e)}var aj=Hb(Jb()),cj=class extends aj.default{constructor(e){super(),Gb(this,"userId"),Gb(this,"tinyId"),Gb(this,"_sdpSemantics"),Gb(this,"_isUplink"),Gb(this,"_room"),Gb(this,"_log"),Gb(this,"_currentState","DISCONNECTED"),Gb(this,"_prevTime",-1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=pN.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(KD.emit(uN.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},lj=class extends cj{constructor(e){super(Fb(Ub({},e),{isUplink:!0})),Gb(this,"localMainAudioTrack",null),Gb(this,"localMainVideoTrack",null),Gb(this,"localAuxAudioTrack",null),Gb(this,"localAuxVideoTrack",null),Gb(this,"_isPublishingAux",!1),Gb(this,"_publishingLocalAudioTrack"),Gb(this,"_publishingLocalVideoTrack"),Gb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Gb(this,"_flag",0),Gb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:i,smallVideoRtxSsrc:n,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:i||0,smallRtx:n||0,auxiliary:o||0,auxiliaryRtx:s||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,i=Object.keys(t).find((e=>t[e]!==r[e]));if(i){if(!e)return void(this._checkPublishStateTimeoutId=VO.run($w,(()=>this.checkPublishState(!0)),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(i," local:").concat(t[i]," server:").concat(r[i]," ").concat(VD()," ").concat(OD())),DN.addCount({key:521e3})}VO.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,r,i;let n={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(rO()?(n.audio=!(null==(e=o[0])||!e.track),n.bigVideo=!(null==(t=o[1])||!t.track),n.smallVideo=!(null==(r=o[2])||!r.track),n.auxVideo=!(null==(i=o[3])||!i.track)):o.forEach((e=>{e.track&&(e.track.kind===WR.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&YR),bigVideo:!!(this.flag&JR),smallVideo:!!(this.flag&qR),auxVideo:!!(this.flag&KR)}}get muteState(){var e,t,r;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)}}initialize(){this.installEvents()}close(e){var t;let r=(null==(t=this._peerConnection)?void 0:t.getSenders())||[];for(let i of r)i.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var r,i,n;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(r=this.localMainVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(i=this.localAuxVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this._publishingLocalVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}))),s}onVideoEncodeFailed(e){var t,r;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),null==(r=this.singlePC)||r.switchVideoEncoder("vp8")))}publish(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;t.installEvents(),yield t.singlePC.waitForPeerConnectionConnected();let u,{publishState:h,muteState:p}=t;if(r&&(t._publishingLocalAudioTrack=r,h.audio=!0,p.audio=r.muted),i){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new sR({code:nR.NOT_SUPPORTED_H264,message:HD({key:Qw.NOT_SUPPORTED_H264ENCODE})});hk&&115===uD()&&i.profile.width*i.profile.height<=230400&&(t._log.warn("fallback video to 480p"),i.setProfile(jR["480p_2"]),yield i.applyProfile()),t._publishingLocalVideoTrack=i,n?(h.auxVideo=!0,p.auxVideo=i.muted):(h.bigVideo=!0,p.bigVideo=i.muted)}if(t._isPublishingAux=n,i&&!n&&i.small&&(u=t._room.videoManager.smallTrack,h.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:LF,responseCommand:lF.SPC_PUBLISH_RESULT,data:Fb(Ub({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:r,localVideoTrack:i,smallTrack:u,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,i){t[n?"localAuxVideoTrack":"localMainVideoTrack"]=i;let{scaleResolutionDownBy:e}=i;yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[n?3:1],e,i.streamType)}r&&(t[n?"localAuxAudioTrack":"localMainAudioTrack"]=r),yield t.singlePC.setBandwidth({audio:(null==(e=t.localMainAudioTrack)?void 0:e.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(c=null==(a=t.localMainVideoTrack)?void 0:a.small)?void 0:c.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(r,i),!n&&(t._room.preferHW||(null==(d=t._room.scheduleResult.config)?void 0:d.preferHW))&&i&&i.profile.width*i.profile.height>=921600&&t.singlePC.useHWEncoder(!0,2)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:r,smallTrack:i,isAuxiliary:n}=e;if(!iO())return;this._log.info("publish by transceiver");let o=null==r?void 0:r.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,r)=>{var i,n;let o=a[t].sender.replaceTrack(r);l.push(t),null!=(i=this.singlePC)&&i.enableInsertableStreams&&o.then((()=>this.createEncodedStreams(a[t].sender,e))),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initSenderTransfrom(a[t].sender,e),c.push(o)};s&&d(t.mediaType,0,s),o&&d(r.mediaType,n?3:1,o),i&&d(8,2,i);let u=this.singlePC.setTransceiverDirection(GR.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var r,i;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(r=this.singlePC)||r.addAbortController(e,o),(null!=(i=this.getTrackByMediaType(t))&&i.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,r)=>{var i;let n=this.getTrackByMediaType(t);r.enqueue((null==(i=this.singlePC)?void 0:i.isUsingH264)&&n?n.encodeFrame(e,8===t):e)}}),o):n.readable).pipeTo(n.writable,o).catch((e=>{this._log.debug("encoded stream error",e),"destory"!==e&&this._log.warn(e)}))}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=2!==t,i=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:r,isSmall:i}))}enableSmall(e){return $b(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(GR.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(GR.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return $b(this,arguments,(function(e){var t=this;let{localAudioTrack:r,localVideoTrack:i}=e;return function*(){let e=i&&i===t.localAuxVideoTrack,n=null==i?void 0:i.outMediaTrack,o=t._peerConnection.getSenders(),s=[];r&&(e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,!t.localMainAudioTrack&&!t.localAuxAudioTrack&&(yield o[0].replaceTrack(null),s.push(0))),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=Fb(Ub({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=Fb(Ub({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.singlePC.setTransceiverDirection(GR.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(r,i),null==i||i.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return $b(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:_F,data:t,responseCommand:lF.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)}))}doUnpublish(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:gF,commandDesc:"unpublish",responseCommand:lF.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===nR.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:i,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:i=this._publishingLocalVideoTrack),dO){if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*i.profile.bitrate,i.small&&(this._mediaSettings.smallVideoWidth=i.small.width,this._mediaSettings.smallVideoHeight=i.small.height,this._mediaSettings.smallVideoFps=i.small.frameRate,this._mediaSettings.smallVideoBps=1e3*i.small.bitrate)}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=r.profile.sampleRate),i&&i.outMediaTrack&&(this._mediaSettings.videoWidth=i.profile.width,this._mediaSettings.videoHeight=i.profile.height,this._mediaSettings.videoFps=i.profile.frameRate,this._mediaSettings.videoBps=1e3*i.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:NF,data:this._mediaSettings,responseCommand:lF.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return $b(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?WR.AUXILIARY:WR.MAIN," stream")),rO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return $b(this,null,(function*(){var r;if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===WR.AUDIO)yield i[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield i[n].sender.replaceTrack(e.outMediaTrack),1===n&&(null==(r=this.localMainVideoTrack)?void 0:r.small)&&(yield i[2].sender.replaceTrack(this._room.videoManager.smallTrack)),i[n].direction===GR.INACTIVE&&(yield this.singlePC.setTransceiverDirection(GR.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return $b(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?WR.AUXILIARY:WR.MAIN," stream")),rO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return $b(this,null,(function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===WR.AUDIO)yield r[0].sender.replaceTrack(null);else{let e=t?3:1;yield r[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(GR.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}replaceTrack(e){return $b(this,null,(function*(){var t;let r=null==(t=this._peerConnection)?void 0:t.getSenders(),i=e.outMediaTrack||e.mediaTrack;if(!r||0===r.length||!i||r.find((e=>e.track===i)))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(i.kind," track ").concat(i.id," ").concat(i.label," on ").concat(n?WR.AUXILIARY:WR.MAIN," stream")),i.kind===WR.AUDIO&&r[0]&&(yield r[0].replaceTrack(i)),i.kind===WR.VIDEO&&(!n&&r[1]&&(yield r[1].replaceTrack(i)),n&&r[3]&&(yield r[3].replaceTrack(i))),!0}))}setBandwidth(e){return $b(this,arguments,(function(e){var t=this;let{bandwidth:r,type:i,videoType:n}=e;return function*(){if(t.singlePC){let e={};i===WR.AUDIO?e.audio=r:"big"===n?e.bigVideo=r:"small"===n?e.smallVideo=r:e.auxVideo=r,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:mF,responseCommand:lF.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&KD.emit(uN.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:WR.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===WR.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===WR.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===WR.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===WR.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Cw?(this._log.error(Zw.NOT_SUPPORTED_H264ENCODE),new sR({code:nR.NOT_SUPPORTED_H264,message:HD({key:Qw.NOT_SUPPORTED_H264ENCODE})})):new sR({code:nR.UNKNOWN,message:HD({key:Qw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lF.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return $b(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};Wb([oL((function(e){let{localVideoTrack:t}=e;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],lj.prototype,"publish",1),Wb([oL((function(e){let{localVideoTrack:t}=e;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],lj.prototype,"unpublish",1);var dj=lj;function uj(e){return Object.keys(e).filter((t=>e[t]))}var hj=class extends cj{constructor(e){super(Fb(Ub({},e),{isUplink:!1})),Gb(this,"_flag",0),Gb(this,"isRobot",!1),Gb(this,"role","anchor"),Gb(this,"remoteAudioTrack"),Gb(this,"remoteVideoTrack"),Gb(this,"remoteAuxiliaryTrack"),Gb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Gb(this,"jitterBufferTimeoutId",-1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new ML(this._room,this),this.remoteVideoTrack=new Mx(this._room,this),this.remoteAuxiliaryTrack=new Lx(this._room,this),this.initialize()}get videoCodec(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return JP(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,i;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(r=this.remoteVideoTrack)||r.onFlagChanged(),null==(i=this.remoteAuxiliaryTrack)||i.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===WR.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,r;let i=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&i!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:i,state:e}),null==(r=this.remoteAuxiliaryTrack)||r.emit("connection-state-changed",{prevState:i,state:e})),n}onTrack(e){var t;let r=e.streams[0],{track:i,receiver:n}=e;if(!r.id.includes(this.tinyId))return;let o=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(i.kind));let s=WR.AUDIO;i.kind===WR.VIDEO&&(s=o===WR.MAIN?WR.VIDEO:WR.AUXILIARY);let a=this.remoteAudioTrack;s===WR.VIDEO?a=this.remoteVideoTrack:s===WR.AUXILIARY&&(a=this.remoteAuxiliaryTrack),null!=(t=this.singlePC)&&t.scriptTransformWorker&&this.initReceiverTransform(n,o,i.kind===WR.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a,n),a.setInputMediaStreamTrack(i)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let r=t.createEncodedStreams(),i=new AbortController,n={abortController:i,enqueue:t=>{var r;return null!=(r=this.singlePC)&&r.isUsingH264?e.decodeFrame(t):t}};r.readable.pipeThrough(new TransformStream({transform:(e,t)=>{let r=n.enqueue(e);r&&t.enqueue(r)}})).pipeTo(r.writable,i).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(t,i)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return $b(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(uj(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(_R){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(_R.message," ").concat(JSON.stringify(this.muteState))),new sR({code:nR.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):_R}}))}checkTrackEnded(e){var t,r,i;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(r=this.remoteVideoTrack.mediaTrack)?void 0:r.readyState)||e.auxiliary&&"ended"===(null==(i=this.remoteAuxiliaryTrack.mediaTrack)?void 0:i.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),hD&&fD<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return $b(this,arguments,(function(e){var t=this;let{remoteTracks:r,streamType:i}=e;return function*(){var e;if("main"===i&&!t.isMainStreamSubscribed||"auxiliary"===i&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(i," stream already unsubscribed"));let n=Ub({},t.subscribeState);r.forEach((e=>{switch(e.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1}}));let o="subscribe_change";Object.values(n).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(i," [").concat(uj(n),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,n),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,r={srcTinyId:this.tinyId,srcUserId:this.userId},i=yF,n=lF.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},i=EF,n=lF.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:i,data:r,responseCommand:n,timeout:1e4,retries:3}).then((t=>{let{data:r}=t;if(0!==r.code){let t=new sR({code:r.code,message:HD({key:Qw.ERROR_MESSAGE,data:{type:e,message:r.message}})});throw this._log.error(t),t}}))}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:r}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=r}onSinglePCReconnected(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return $b(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(r||!e.hasSSRC){let r={audioSsrc:sj(),bigVideoSsrc:sj(),bigVideoRtxSsrc:sj(),auxVideoSsrc:sj(),auxVideoRtxSsrc:sj()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=r;e.ssrc={audio:n,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let i=yield e._signalChannel.sendWaitForResponseWithRetry({command:xF,responseCommand:lF.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(0!==i.data.code)throw new sR({code:i.data.code,message:i.data.message})}catch(i){throw yield e.removeDownlink(),i}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{let t=e._room.scheduleResult.config;((null==t?void 0:t.jitterDelay)||(null==t?void 0:t.jitterDelayAux))&&e.setJitterBufferDelay({mainDelay:t.jitterDelay,auxDelay:t.jitterDelayAux})}}}()}))}removeDownlink(){return $b(this,null,(function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;((null==e?void 0:e.jitterDelay)||(null==e?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)}))}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:r}=e;if(!this.singlePC||!this._peerConnection||zD(t)&&zD(r))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(r));let i=this.singlePC.getReceiversByUserId(this.userId);return PP(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),PP(r)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=r,zD(t)&&(this.remoteAudioTrack.jitterBufferDelay=r)),new Promise((e=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:r,receivers:i,resolve:e})}))}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:r,receivers:i,resolve:n}=e;try{if(0===t&&0===r)return i.forEach((e=>e.jitterBufferTarget=0)),n();if(i.forEach((e=>{var i;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack||zD(t)&&e.track===this.remoteAudioTrack.outMediaTrack;if(n&&zD(r)||!n&&zD(t))return;let o=n?r||0:t,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,this._log.debug("set ".concat(n?"aux ":"").concat(null==(i=null==e?void 0:e.track)?void 0:i.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))})),!i.find((e=>{let i=e.track===this.remoteAuxiliaryTrack.outMediaTrack?r||0:t;return e.jitterBufferTarget<i})))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(r," done")),n();this.jitterBufferTimeoutId=setTimeout((()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:r,receivers:i,resolve:n})}),1e3)}catch(gR){this._log.warn("set jitterBuffer delay error: ".concat(gR)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}};Wb([hL(),sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return new Promise(((t,i)=>{let n=e=>{this.off("closed",n),i(new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,r).then(t,i).finally((()=>{this.off("closed",n)}))}))}))],hj.prototype,"subscribe",1),Wb([hL()],hj.prototype,"unsubscribe",1),Wb([mL((()=>"jitter"))],hj.prototype,"setJitterBufferDelay",1);var pj=hj;var mj=Hb(Jb());var fj=class extends mj.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,Gb(this,"log"),Gb(this,"cmdIdSeqMap",new Map),Gb(this,"messageMap",new Map),this.log=pN.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(lF.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",(e=>{[...this.messageMap.keys()].forEach((t=>{t.split("_").slice(0,-1).join("_")===e&&this.messageMap.delete(t)}))}))}send(e){let{cmdId:t,data:r}=e,i=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),n={cmdId:t,msg:btoa(String.fromCharCode(...new Uint8Array(r))),ordered:!0,reliable:!0,streamSeq:i};this.cmdIdSeqMap.set(t,i+1),this.signalChannel.send(FF,n),this.log.debug("send custom msg: ".concat(JSON.stringify(n)))}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let e={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),(e=>e.charCodeAt(0))).buffer};if(t.ordered){let t="".concat(r,"_").concat(e.cmdId),i=this.messageMap.get(t);if(i&&0!==i.lastSeq)if(Math.abs(i.lastSeq-e.seq)>fj.SEQ_INTERVAL)this.messageMap.set(t,{lastSeq:e.seq,cachedMessageMap:new Map}),this.emitMessage(e);else if(e.seq>i.lastSeq){if(e.seq===i.lastSeq+1)this.emitMessage(e);else if(!i.cachedMessageMap.has(e.seq)){let t=setTimeout((()=>this.emitMessage(e,!0)),5e3);i.cachedMessageMap.set(e.seq,{message:e,timeoutId:t})}}else this.log.debug("drop message ".concat(e.userId,"-").concat(e.cmdId,"-").concat(e.seq));else i||(i={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(t,i),setTimeout((()=>this.emitMessage(e,!0)),100)),i.cachedMessageMap.set(e.seq,{message:e})}else this.emit("message",e)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(t.srcTinyId));let r=i=>{i.tinyId===t.srcTinyId&&(this.room.off("peer-join",r),this.onReceiveMsg(e))};this.room.on("peer-join",r),cN(2e3).then((()=>this.room.off("peer-join",r)))}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var r;let i=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(i){if(t){let e=[...i.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}0!==i.lastSeq&&n.seq-i.lastSeq>1&&this.log.debug("msg lost userId: ".concat(n.userId," seq: ").concat(i.lastSeq," -> ").concat(n.seq)),i.lastSeq=n.seq,clearTimeout(null==(r=i.cachedMessageMap.get(n.seq))?void 0:r.timeoutId),i.cachedMessageMap.delete(n.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(n))),this.emit("message",n);let o=null==i?void 0:i.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},_j=fj;Gb(_j,"SEQ_INTERVAL",300);var{isString:gj,isUndefined:vj,getNetworkType:yj,isEmpty:Ej}=dR,Tj=class extends bB{constructor(e){super(e),this._heartbeat=-1,this._lastHeartBeatTime=-1,this._joinTimeout=-1,this._firstPublishedList=null,this._joinReject=null,this._isRelayChanged=!1,this.signalChannel=null,this.uplinkConnection=null,this.singlePC=null,this.enableSPC=nO,this._changeBigSmallRecords=new Map,this.forceRelay=!1,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.preferHW=!1,this._updateAudioLevelTaskId=-1,this._stats=new oB(this,this._log),this.userManager=new Fx(this.userId,this._log),this._version=pR,this.sdpSemantics=Aw,vj(e.sdpSemantics)?_N.isUnifiedPlanDefault()&&(this.sdpSemantics=Iw):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(yj())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!vj(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&nO,!vj(e.enableSPC)&&nO&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new JB(this)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,r){return $b(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var r={};for(var i in e)Ob.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&Pb)for(var i of Pb(e))t.indexOf(i)<0&&Mb.call(e,i)&&(r[i]=e[i]);return r})(e,[]);KD.emit(uN.REMOTE_PUBLISH_STATE_CHANGED,Ub({room:this},t)),this.emit("remote-publish-state-changed",Ub({},t))})),this.joinParams=e,new Promise(((t,r)=>$b(this,null,(function*(){var i,n;this._joinReject=r;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(o){if(!(o instanceof sR&&o.code===nR.SPC_INITIALIZED_FAILED))return r(o);null==(i=this.signalChannel)||i.destroy(),yield this.initialize()}let s=HP();yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),DN.addSuccessEvent({key:521708,cost:HP()-s}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(gN){DN.addFailedEvent({key:521708,error:gN}),r(gN)}this._joinReject=null}))))}))}initSinglePC(){return $b(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new rj({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{return yield this.singlePC.initialize()}catch(fR){throw this.fallbackToMPC(),new sR({code:nR.SPC_INITIALIZED_FAILED,message:null==fR?void 0:fR.message})}}}))}doJoin(e,t){return new Promise(((r,i)=>$b(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(oF,(e=>{this.clearJoinTimeout(),KD.emit(uN.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),NP(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&nO&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:UD(),netType:_P(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{i(new sR({code:nR.JOIN_ROOM_FAILED,message:HD({key:Qw.JOIN_ROOM_TIMEOUT})}))}),c),KD.emit(uN.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?MF:uF,a),this.signalChannel.once(lF.JOIN_ROOM_RESULT,(t=>{this.clearJoinTimeout();let{code:n,message:o,data:s,tinyId:a}=t.data;KD.emit(uN.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(this._log.info("Join room success, start heartbeat"),a&&(this.tinyId=a),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=s.publishers,this.singlePC&&this.singlePC.connect(Fb(Ub({},s.ability),{useVp8:s.ability.useVp8||!!e.useVp8})).catch((()=>{})),r()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(o)),i(new sR({code:nR.JOIN_ROOM_FAILED,extraCode:n,message:HD({key:Qw.JOIN_ROOM_FAILED,data:{error:o,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return $b(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let t,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then((e=>(t=e,e))))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(Fb(Ub({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),XD.logSuccessEvent({userId:this.userId,eventType:yw.REJOIN}),this.singlePC){let e=t=>{var r;"CONNECTED"===t.state&&(null==(r=this.singlePC)||r.off(XB.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof dj&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(XB.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof nB&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(gw){this._log.warn("reJoin fail ".concat(gw)),this.reset(),XD.logFailedEvent({userId:this.userId,eventType:yw.REJOIN,error:gw}),this.emit("error",new sR({code:nR.JOIN_ROOM_FAILED,message:HD({key:Qw.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return $b(this,null,(function*(){let e,{mainUrl:t,backupUrl:r}=this.getSignalChannelUrl(),i=this.signalChannel||function(e){let t=[...BF.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(i.url=t,i.backupUrl=r,i.room=this,this.signalChannel=i):(this.signalChannel=new jF({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:r,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new _j(this,this.signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new lB({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(lB.EVENT_NETWORK_QUALITY,(e=>{var t;this.emit("network-quality",e),null==(t=this.singlePC)||t.detectTCPAndUDP(e)}))),jO(this,this.signalChannel).add(rF,(e=>{KD.emit(uN.SIGNAL_CONNECTION_STATE_CHANGED,Ub({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(nF,(e=>{this.reset(),this.emit("error",e)})).add(lF.PEER_JOIN,(e=>{let{srcTinyId:t,userId:r,role:i}=e.data.data;this.userManager.addUser({userId:r,tinyId:t,role:i})})).add(lF.PEER_LEAVE,(e=>{let{userId:t,reason:r=0}=e.data.data;this.userManager.deleteUser(t,r)})).add(lF.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(lF.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:r}=t;if(XD.uploadEvent({log:"stat-banned:".concat(r),userId:this.userId}),"user_time_out"===r)return this._log.warn("".concat(r," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log["kick"===r?"error":"info"]("user was banned because of [".concat(r,"]")),this.reset(),this.emit("banned",{reason:r})})),this.signalChannel.once(tF,(e=>{this.tinyId=e.signalInfo.tinyId,KD.emit(uN.JOIN_SIGNAL_CONNECTION_END,{room:this})})),KD.emit(uN.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&KD.emit(uN.JOIN_SIGNAL_CONNECTION_END,{room:this}),n}))}setSignalChannel(e){this.signalChannel=e,e||HO(this)}leave(){return $b(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(gw){}this._log.info("leave() => leaving room"),KD.emit(uN.LEAVE_SEND_CMD,{room:this}),null==(e=this.signalChannel)||e.send(hF)}))}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=VO.run(Ww,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),VO.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return $b(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),r=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let i=null!=(e=this.signalChannel)&&e.isConnected?function(e){if(xx.has(e)){let t=xx.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 xx.delete(e),t}return[]}(this.userId):[],n=Fb(Ub({str_sdk_version:hR,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:i,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},r),{msg_device_info:Ub({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:_P()},r.msg_device_info)});if(this.heartbeatReport=n,KD.emit(uN.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(pF,n);let e=Date.now();this._lastHeartBeatTime>0&&e-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(e-this._lastHeartBeatTime)),this._lastHeartBeatTime=e,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",Fb(Ub({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter((e=>e.flag!==ew)).map((e=>{let{userId:t,srcTinyId:r,flag:i}=e;t===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=i);let n=this.remotePublishedUserMap.get(t);return n&&this.checkSubscribeBigSmallVideo(n),{userId:t,tinyId:r,flag:i}}));e.data.mixRobotList.forEach((e=>{let{userId:r,srcTinyId:i,flag:n,mixUserList:o}=e;t.unshift({userId:r,tinyId:i,flag:n,isRobot:!0,mixUserList:o})})),KD.emit(uN.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof nB&&(this.uplinkConnection=null)),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:r,flag:i,isRobot:n}=e,o=new(this.singlePC?pj:eB)({userId:t,tinyId:r,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:i,isRobot:n});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",(e=>{let r=e.getCode();r!==nR.ICE_TRANSPORT_ERROR&&(r===nR.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",Fb(Ub({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=VO.run(Ww,this.syncUserList.bind(this)))}stopSyncUserListInterval(){VO.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this.signalChannel)&&e.isConnected?this.signalChannel.sendWaitForResponse({command:DF,responseCommand:lF.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:r,message:i}=t;if(0===r)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:r,role:i}=e;return{userId:t,tinyId:r,role:i}}));throw HD({key:Qw.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lF.USER_LIST_RES,code:r,message:i}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!$F)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(0===e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===pw.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof JF&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===pw.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return $b(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),XD.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new nB({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let t of[...this.remotePublishedUserMap.values()]){let e=new eB({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(e,t.userId),this.remotePublishedUserMap.set(t.userId,e),t.isMainStreamSubscribed&&(yield e.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield e.subscribe(t.subscribeState,"auxiliary"))}}))}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),VO.clearTask(this._audioVolumeIntervalId))}switchRole(e){return $b(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:PF,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:lF.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:r,message:i}=t.data;if(0!==r)throw new sR({code:nR.SWITCH_ROLE_FAILED,message:HD({key:Qw.SWITCH_ROLE_FAILED,data:{message:i,code:r}})});this.role=e})).catch((e=>{throw e instanceof sR&&e.getCode()===nR.API_CALL_TIMEOUT&&(e=new sR({code:nR.SWITCH_ROLE_FAILED,message:HD({key:Qw.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return $b(this,null,(function*(){let e={},r={};t.forEach((t=>{t instanceof yL&&(t instanceof RL?r.audio=t:e.audio=t),t instanceof SL&&(t instanceof bL&&2===t.mediaType?r.video=t:e.video=t)}));let i=Ej(e),n=Ej(r);(!i||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new dj({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new nB({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",Fb(Ub({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==nR.ICE_TRANSPORT_ERROR&&(t===nR.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");i||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return $b(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},r={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof yL&&(t instanceof RL?r.audio=t:e.audio=t),t instanceof SL&&(t instanceof bL&&2===t.mediaType?r.video=t:e.video=t))}));try{let i=t.map((e=>e.kind)).join(",");Ej(e)||(this._log.info("unpublish() => main ".concat(i)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),Ej(r)||(this._log.info("unpublish() => aux ".concat(i)),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(i){}0===this.localTracks.size&&this.closeUplink("you unpublished")}))}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((t=>(e.unpublish(),t))):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&aO()?this.uplinkConnection.replaceTrack(e).then((t=>{t&&KD.emit(uN.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return $b(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return $b(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:WR.VIDEO,videoType:WR.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return $b(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],r=this.remotePublishedUserMap.get(e);if(!r)return;let i=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let n=Ub({},r.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),KD.emit(uN.SUBSCRIBE_START,{room:this,streamType:i,remotePublishedUser:r,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(i," [").concat(XF(n),"] prev: [").concat(XF(r.subscribeState),"]")),yield r.subscribe(n,i),this._log.info("subscribe ".concat(e," ").concat(i," done"));for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());KD.emit(uN.SUBSCRIBE_SUCCESS,{room:this,streamType:i,remotePublishedUser:r})}catch(gR){let r=gR instanceof sR?gR.getCode():nR.UNKNOWN,n=gR;throw gR instanceof sR?r===nR.REMOTE_STREAM_NOT_EXIST&&(n=new sR({code:nR.API_CALL_ABORTED,message:HD({key:Qw.API_CALL_ABORTED,data:{message:gR.message,userId:e,streamType:i}})}),this._log.warn(n)):(n=new sR({code:r,message:HD({key:Qw.SUBSCRIBE_FAILED,data:{message:gR.message,userId:e,streamType:i}})}),this._log.error(n)),n}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return $b(this,null,(function*(){let{userId:e}=t[0],r=this.remotePublishedUserMap.get(e);if(!r)return;let i=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(i));try{yield r.unsubscribe({remoteTracks:t,streamType:i})}catch(gR){this._log.warn("unsubscribe() => failed ".concat(gR))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),KD.emit(uN.UNSUBSCRIBE_SUCCESS,{room:this,streamType:i,remotePublishedUser:r})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void VO.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),KD.emit(uN.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&VO.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=VO.run(Gw,(()=>{var r;PM.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let i=[];null==(r=this.remotePublishedUserMap)||r.forEach((e=>{if(e.muteState.hasAudio){!PM.isRunning&&e.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(e):e.remoteAudioTrack.volume=0;let t=Math.floor(100*e.remoteAudioTrack.getAudioLevel());i.push({userId:e.userId,volume:t})}})),this.emit("audio-volume",i)}),{fps:1e3/e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return $b(this,null,(function*(){var r;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||-1!==this._updateAudioLevelTaskId)return;let i=null==(r=this.uplinkConnection.getPeerConnection())?void 0:r.getSenders()[0];if(!i)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=VO.run(Gw,(()=>$b(this,null,(function*(){let e=yield i.getStats();this._updateAudioLevelTaskId<0||e.forEach((e=>{"media-source"===e.type&&e.audioLevel&&(this.uplinkConnection.localMainAudioTrack.volume=e.audioLevel)}))}))),{delay:n,backgroundTask:t})}))}stopUpdateAudioLevelFromSenderStat(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),VO.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:r}=e;if(!lO||!r)return;let i=null==(t=r.getSynchronizationSources()[0])?void 0:t.audioLevel;i&&(e.remoteAudioTrack.volume=Math.min(2*i,1))}getLocalAudioStats(){return $b(this,null,(function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t}))}getLocalVideoStats(){return $b(this,null,(function*(){var e,t;let r={};return r[this.userId]=(null==(t=null==(e=this.uplinkConnection)?void 0:e.localMainVideoTrack)?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},r}))}getTransportStats(){return $b(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e}))}getRemoteVideoStats(e){return $b(this,null,(function*(){let t={};for(let[r,i]of this.remotePublishedUserMap)"main"===e&&i.muteState.hasVideo&&(t[r]=i.remoteVideoTrack.stat),"auxiliary"===e&&i.muteState.hasAuxiliary&&(t[r]=i.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return $b(this,null,(function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let r=[];Array.isArray(e)?e.forEach((e=>r.push(dR.getTurnServer(e)))):dR.isPlainObject(e)&&r.push(dR.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:CF,data:e,timeout:5e3,responseCommand:lF.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:bF,data:e,timeout:5e3,responseCommand:lF.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?TF:IF,data:e,timeout:5e3,responseCommand:t?lF.START_PUBLISH_TENCENT_CDN_RES:lF.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?SF:AF,data:e,timeout:5e3,responseCommand:t?lF.STOP_PUBLISH_TENCENT_CDN_RES:lF.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:RF,data:e,timeout:5e3,responseCommand:lF.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:wF,data:e,timeout:5e3,responseCommand:lF.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:kF,data:e,timeout:5e3,responseCommand:lF.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:VF,data:e,timeout:5e3,responseCommand:lF.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dR.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return $b(this,null,(function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:i,hasVideo:n}}=e;if(!i&&!n||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(r);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&i)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!i&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(r,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(jw-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=jw}catch(l){this._log.info("change [".concat(r,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(jw-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(r)}}))}changeType(e,t){let r={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:jw};this._changeBigSmallRecords.set(t.userId,r),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(gj(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vj(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new sR({code:nR.INVALID_PARAMETER,message:HD({key:Qw.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!vj(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(r))throw new sR({code:nR.INVALID_PARAMETER,message:HD({key:Qw.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vj(e.userDefinePushArgs)){if(!(gj(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new sR({code:nR.INVALID_PARAMETER,message:HD({key:Qw.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}Ej(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&hO)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new sR({code:nR.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}};return Wb([OB(["left",xB.INIT],"joined"),GO({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),eP(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),sL((e=>{let t=new QU;return function(r,i,n){return $b(this,null,(function*(){let o=String(r.roomId||r.strRoomId);if(this.userId=r.userId,this.sdkAppId=r.sdkAppId,this.userSig=r.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=i,r.privateMapKey=r.privateMapKey||"",this.isJoined)throw new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new sR({code:nR.INVALID_OPERATION,message:HD({key:Qw.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:o}),this.role=21===r.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),KD.emit(uN.JOIN_START,{room:this,roomId:o,params:r});let s=dR.getEnv();s||(s=OR.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(zR.OLD_CLOUD_LADDER)?s=OR.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(zR.WEBRTC)&&(s=OR.WEBRTC))),XD.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),_N.checkSystemRequirementsInternal().then((e=>{this.checkSystemResult=e,ZU.call(this)}));try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!dR.getEnv()&&(yield this.schedule(r,n));let t=yield e.call(this,r,i,n);return this.roomId=o,this._joinedTimestamp=dR.performanceNow(),KD.emit(uN.JOIN_SUCCESS,{room:this}),30===n&&!r.component&&XD.uploadEvent({log:"stat-conv-".concat(Number(bD),"-").concat(location.hostname),userId:this.userId}),t}catch(a){throw t.delete({room:this,roomId:o}),KD.emit(uN.JOIN_FAILED,{room:this,error:a}),a}}))}}))],Tj.prototype,"join",1),Wb([OB("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),sL((e=>function(){return $b(this,null,(function*(){KD.emit(uN.LEAVE_START,{room:this}),yield e.call(this),KD.emit(uN.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),pL("leave room"),zO({fnName:"publish",validateArgs:!1}),zO({fnName:"unsubscribe",validateArgs:!1})],Tj.prototype,"leave",1),Wb([hL(),sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];return $b(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(r=r.filter((e=>e.outMediaTrack&&"capture"===e.state)),!r.length))return;KD.emit("61",{room:this});let t=e.apply(this,r);return r.forEach((e=>e.publish(this,t))),t}))})),GO({settings:{retries:_w,timeout:e=>bP(e)},onError(e,t,r){var i;null!=(i=e.message)&&i.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),r(e),KD.emit(uN.PUBLISH_FAILED,{room:this}))}})],Tj.prototype,"publish",1),Wb([zO({fnName:"publish"}),function(e){return function(t,r,i){let n=i.value;return i.value=function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];let o=dL.get(this);if(o){let t=o.queue.filter(((t,i)=>{if(0===i)return!0;let n=!0;return t.args.forEach((e=>{r.find((t=>t===e))||(n=!1)})),!n||(t.reject(new sR({code:nR.API_CALL_ABORTED,message:e})),!1)}));o.queue=t}return n.apply(this,r)},i}}("api-call"),hL(),sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];let n=e.apply(this,r);return r.forEach((e=>e.unpublish())),n})),oL((function(){var e,t;0===this.localTracks.size&&tO()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],Tj.prototype,"unpublish",1),Wb([function(e){return sL(((t,r)=>function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return $b(this,null,(function*(){try{return yield t.apply(this,i)}catch(_R){e.call(this,_R)}}))}))}((e=>{if(e.code!==nR.API_CALL_ABORTED)throw e})),mL((e=>e.userId))],Tj.prototype,"replaceTrack",1),Wb([mL((function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].userId})),PL(),sL((e=>function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];let n=e.apply(this,r);return r.forEach((e=>!e.isSubscribed&&e.subscribe(n))),n})),GO({settings:{retries:_w,timeout:e=>bP(e)},onError(e,t,r,i){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),r(e),KD.emit(uN.SUBSCRIBE_FAILED,{room:this,remoteTracks:i}))}})],Tj.prototype,"subscribe",1),Wb([zO({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.singlePC||t.forEach((e=>{let t=this.remotePublishedUserMap.get(e.userId);t&&!t.isMainStreamSubscribed&&!t.isAuxStreamSubscribed&&t.close("you unsubscribed")}))}}),mL((function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return t[0].userId}))],Tj.prototype,"unsubscribe",1),XU.create=XU._create.bind(XU,Tj),XU}));
|