trtc-sdk-v5 5.6.3-beta.7 → 5.6.3
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/index.d.ts +8 -9
- package/package.json +1 -1
- package/plugins/cdn-streaming/cdn-streaming.esm.js +1 -1
- package/plugins/cdn-streaming/cdn-streaming.iife.js +1 -1
- package/plugins/cdn-streaming/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 +24 -95
- 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,S=TypeError,I=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,y=I,A=function(e){return v(y(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},N=C,D=Object.defineProperty,w=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0})}catch(i){N[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=I,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),G=Object.hasOwn||function(e,t){return j(H(e),t)},W=c,J=0,z=Math.random(),K=W(1..toString),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=G,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},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===Ie}:function(e){return"object"==typeof e?null!==e:Se(e)},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},we=ve,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},Ge=c({}.isPrototypeOf),We=je,Je=Ee,ze=Ge,Ke=Object,qe=se?function(e){return"symbol"==typeof e}:function(e){var t=We("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=ve,at=TypeError,ct=Fe,lt=ve,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,St=xe,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Nt="writable";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Nt in i&&!i[Nt]){var r=Ct(e,t);r&&r[Nt]&&(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(vt(e),t=yt(t),vt(i),St)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 Dt=Math.ceil,wt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?wt:Dt)(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,Gt=function(e){return jt(e.length)},Wt=A,Jt=Ut,zt=Gt,Kt=function(e){return function(t,i,r){var n,o=Wt(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=G,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=Ne,ci=De,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,Si=Yt,Ii=pi,vi=Me,yi="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ni=function(){try{hi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;Ni="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var r=Ei.length;r--;)delete Ni[yi][Ei[r]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},wi=_e,Oi=Di,Pi=De.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,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=De,zi=Wi,Ki=ke?function(e,t,i){return Ji.f(e,t,zi(1,i))}:function(e,t,i){return e[t]=i,e},qi=Gi,Yi=C,Qi=ve,Xi=Ki,$i=G,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=Wi,gr=A,Tr=Tt,Er=G,Sr=xe,Ir=Object.getOwnPropertyDescriptor;cr.f=pr?Ir:function(e,t){if(e=gr(e),t=Tr(t),Sr)try{return Ir(e,t)}catch(i){}if(Er(e,t))return fr(!mr(_r.f,e,t),e[t])};var vr={},yr={get exports(){return vr},set exports(e){vr=e}},Ar=ke,Rr=G,Cr=Function.prototype,br=Ar&&Object.getOwnPropertyDescriptor,kr=Rr(Cr,"name"),Nr={EXISTS:kr,PROPER:kr&&"something"===function(){}.name,CONFIGURABLE:kr&&(!Ar||Ar&&br(Cr,"name").configurable)},Dr=Ee,wr=M,Or=c(Function.toString);Dr(wr.inspectSource)||(wr.inspectSource=function(e){return Or(e)});var Pr=wr.inspectSource,Mr=c,Lr=i,xr=Ee,Vr=G,Ur=ke,Fr=Nr.CONFIGURABLE,Br=Pr,Hr=ar.enforce,jr=ar.get,Gr=String,Wr=Object.defineProperty,Jr=Mr("".slice),zr=Mr("".replace),Kr=Mr([].join),qr=Ur&&!Lr((function(){return 8!==Wr((function(){}),"length",{value:8}).length})),Yr=String(String).split("String"),Qr=yr.exports=function(e,t,i){"Symbol("===Jr(Gr(t),0,7)&&(t="["+zr(Gr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Vr(e,"name")||Fr&&e.name!==t)&&(Ur?Wr(e,"name",{value:t,configurable:!0}):e.name=t),qr&&i&&Vr(i,"arity")&&e.length!==i.arity&&Wr(e,"length",{value:i.arity});try{i&&Vr(i,"constructor")&&i.constructor?Ur&&Wr(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=De,Zr=vr,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=G,gn=_n,Tn=cr,En=De,Sn=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))}},In=i,vn=Ee,yn=/#|\.prototype\./,An=function(e,t){var i=Cn[Rn(e)];return i==kn||i!=bn&&(vn(t)?In(t):!!t)},Rn=An.normalize=function(e){return String(e).replace(yn,".").toLowerCase()},Cn=An.data={},bn=An.NATIVE="N",kn=An.POLYFILL="P",Nn=An,Dn=C,wn=cr.f,On=Ki,Pn=tn,Mn=w,Ln=Sn,xn=Nn,Vn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Dn:l?Dn[a]||Mn(a,{}):(Dn[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=G,Bn=Ee,Hn=B,jn=Un,Gn=fi("IE_PROTO"),Wn=Object,Jn=Wn.prototype,zn=jn?Wn.getPrototypeOf:function(e){var t=Hn(e);if(Fn(t,Gn))return t[Gn];var i=t.constructor;return Bn(i)&&t instanceof i?i.prototype:t instanceof Wn?Jn:null},Kn=i,qn=Ee,Yn=ve,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=De.f,ro=G,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=Di,co=Wi,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){}},So=Ce,Io=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(r){}return function(i,r){return So(i),Io(r),t?e(i,r):i.__proto__=r,i}}():void 0),yo=Vn,Ao=Fe,Ro=Ee,Co=po,bo=zn,ko=vo,No=oo,Do=Ki,wo=tn,Oo=Bi,Po=Nr.PROPER,Mo=Nr.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)),No(a,u,!0)),Po&&n==Fo&&m&&m.name!==Fo&&(Mo?Do(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 yo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&wo(p,Vo,_,{name:n}),Oo[t]=_,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,zo=Bi,Ko=ar,qo=De.f,Yo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=Ko.set,es=Ko.getterFor($o),ts=Yo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,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(RF){}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(RF){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(RF){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=vr,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,ys=Is,As=ke,Rs=_e("species"),Cs=function(e){var t=vs(e);As&&t&&!t[Rs]&&ys(t,Rs,{configurable:!0,get:function(){return this}})},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ds={};Ds[_e("toStringTag")]="z";var ws="[object z]"===String(Ds),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(RF){}}(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,Gs=function(){},Ws=[],Js=je("Reflect","construct"),zs=/^\s*(?:class|function)\b/,Ks=Us(zs.exec),qs=!zs.exec(Gs),Ys=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(RF){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(RF){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,Sa=r,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(Y),ba=C,ka=_a,Na=va,Da=Ee,wa=G,Oa=i,Pa=pi,Ma=ya,La=Me,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Ga=ba.Function,Wa=ba.MessageChannel,Ja=ba.String,za=0,Ka={},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=Da(e)?e:Ga(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))}:Wa&&!Va?(ea=(Zs=new Wa).port2,Zs.port1.onmessage=Xa,$s=Na(ea.postMessage,ea)):ba.addEventListener&&Da(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!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=va,uc=cr.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,Ic=lc.Promise,vc=uc(lc,"queueMicrotask"),yc=vc&&vc.value;if(!yc){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch(RF){throw Ac.head&&tc(),RF}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&Ic&&Ic.resolve?((nc=Ic.resolve(void 0)).constructor=Ic,oc=dc(nc.then,nc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.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}),yc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=yc,bc=function(e){try{return{error:!1,value:e()}}catch(RF){return{error:!0,value:RF}}},kc=C.Promise,Nc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!Nc&&!Ts&&"object"==typeof window&&"object"==typeof document,wc=C,Oc=kc,Pc=Ee,Mc=Nn,Lc=Pr,xc=_e,Vc=Dc,Uc=Nc,Fc=ie;Oc&&Oc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(wc.PromiseRejectionEvent),Gc=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})),Wc={CONSTRUCTOR:Gc,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=vo,nl=oo,ol=Cs,sl=et,al=Ee,cl=ve,ll=Ns,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(RF){}},ml=bc,_l=sc,fl=ar,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,Il=Wc.REJECTION_EVENT,vl=Wc.SUBCLASSING,yl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Nl=el.document,Dl=el.process,wl=Tl.f,Ol=wl,Pl=!!(Nl&&Nl.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(RF){d&&!n&&d.exit(),l(RF)}},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=Nl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),el.dispatchEvent(r)):r={promise:t,reason:i},!Il&&(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?Dl.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?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(r){e(t,r,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var r=Ll(t);r?hl((function(){var i={done:!1};try{tl(r,t,jl(Wl,i,e),jl(Gl,i,e))}catch(RF){Gl(i,RF,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(RF){Gl({done:!1},RF,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(Yc,this);var t=yl(this);try{e(jl(Wl,t),jl(Gl,t))}catch(RF){Gl(t,RF)}}).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=yl(this),r=wl(dl(this,Cl));return i.parent=!0,r.ok=!al(e)||e,r.fail=al(t)&&t,r.domain=Zc?Dl.domain:void 0,0==i.state?i.reactions.add(r):hl((function(){xl(r,i)})),r.promise})),Qc=function(){var e=new Yc,t=yl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=wl=function(e){return e===Cl||undefined===e?new Qc(e):Ol(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,vl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(RF){}rl&&rl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{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(RF){n=!0,r=RF}if("throw"===t)throw i;if(n)throw r;return ld(r),i},hd=va,pd=Fe,md=Ce,_d=Qe,fd=ql,gd=Gt,Td=Ge,Ed=ad,Sd=ed,Id=ud,vd=TypeError,yd=function(e,t){this.stopped=e,this.result=t},Ad=yd.prototype,Rd=function(e,t,i){var 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&&Id(r,"normal",e),new yd(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)r=e.iterator;else if(p)r=e;else{if(!(n=Sd(e)))throw vd(_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 yd(!1)}r=Ed(e,n)}for(c=h?e.next:r.next;!(l=pd(c,r)).done;){try{a=g(l.value)}catch(RF){Id(r,"throw",RF)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Nd[Cd]=function(){return this},Array.from(Nd,(function(){throw 2}))}catch(RF){}var Dd=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(RF){}return i},wd=kc,Od=Wc.CONSTRUCTOR||!Dd((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=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=tn,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var zd=Fe,Kd=et,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:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},ru=Vn,nu=Wc.CONSTRUCTOR,ou=iu;je("Promise"),ru({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,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=ve,uu=h,hu=_e("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},mu=Vs,_u=String,fu=function(e){if("Symbol"===mu(e))throw TypeError("Cannot convert a Symbol value to a string");return _u(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in yu||Su(e,"flags")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Nu=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},wu=De.f,Ou=i,Pu=C.RegExp,Mu=Ou((function(){var e=Pu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Lu=i,xu=C.RegExp,Vu=Lu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Uu=ke,Fu=C,Bu=c,Hu=Nn,ju=lu,Gu=Ki,Wu=rn.f,Ju=Ge,zu=pu,Ku=fu,qu=Au,Yu=Du,Qu=function(e,t,i){i in e||wu(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=tn,$u=i,Zu=G,eh=ar.enforce,th=Cs,ih=Mu,rh=Vu,nh=_e("match"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu("".charAt),dh=Bu("".replace),uh=Bu("".indexOf),hh=Bu("".slice),ph=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,mh=/a/g,_h=/a/g,fh=new oh(mh)!==mh,gh=Yu.MISSED_STICKY,Th=Yu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||rh||$u((function(){return _h[nh]=!1,oh(mh)!=mh||oh(_h)==_h||"/a/i"!=oh(mh,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,r,n,o,s,a,c=Ju(sh,this),l=zu(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=qu(h))),e=void 0===e?"":Ku(e),t=void 0===t?"":Ku(t),h=e,ih&&"dotAll"in mh&&(r=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in mh&&(n=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),rh&&(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=lh(e,r)))t+=lh(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(r||n||u.length)&&(a=eh(s),r&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=lh(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+lh(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch(RF){}return s},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,"RegExp",Sh,{constructor:!0})}th("RegExp");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=ar.get,Dh=Mu,wh=Vu,Oh=b("native-string-replace",String.prototype.replace),Ph=RegExp.prototype.exec,Mh=Ph,Lh=Ah("".charAt),xh=Ah("".indexOf),Vh=Ah("".replace),Uh=Ah("".slice),Fh=function(){var e=/a/,t=/b*/g;return yh(Ph,e,"a"),yh(Ph,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec("")[1];(Fh||Hh||Bh||Dh||wh)&&(Mh=function(e){var t,i,r,n,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Mh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,m=yh(Ch,c),_=c.source,f=0,g=d;if(p&&(m=Vh(m,"y",""),-1===xh(m,"g")&&(m+="g"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Lh(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Hh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Fh&&(r=c.lastIndex),n=yh(Ph,p?i:c,g),p?n?(n.input=Uh(n.input,f),n[0]=Uh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Fh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Hh&&n&&n.length>1&&yh(Oh,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=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var jh=Mh;Vn({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,zh=ta,Kh=ve,qh=_e("species"),Yh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(zh(t)&&(t===Yh||Jh(t.prototype))||Kh(t)&&null===(t=t[qh]))&&(t=void 0)),void 0===t?Yh:t},Xh=va,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),rp=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=Zh(c),_=$h(m),f=Xh(l,d),g=ep(_),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:r||n?n:S}},np={forEach:rp(0),map:rp(1),filter:rp(2),some:rp(3),every:rp(4),find:rp(5),findIndex:rp(6),filterReject:rp(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=np.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=rs,up=ss,hp=cp,pp=Ki,mp=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch(RF){e.forEach=hp}};for(var _p in dp)dp[_p]&&mp(lp[_p]&&lp[_p].prototype);mp(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,r,n){fp(i);var o=gp(t),s=Tp(o),a=Ep(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 Sp("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:Ip(!1),right:Ip(!0)}.left;Vn({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=tn,Rp=jh,Cp=i,bp=_e,kp=Ki,Np=bp("species"),Dp=RegExp.prototype,wp=c,Op=Mt,Pp=fu,Mp=I,Lp=wp("".charAt),xp=wp("".charCodeAt),Vp=wp("".slice),Up=function(e){return function(t,i){var r,n,o=Pp(Mp(t)),s=Op(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=xp(o,s))<55296||r>56319||s+1===a||(n=xp(o,s+1))<56320||n>57343?e?Lp(o,s):r:e?Vp(o,s,s+2):n-56320+(r-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),zp=Hp("".slice),Kp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,Yp=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=qp;return void 0!==n&&(n=jp(n),c=Kp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return zp(t,0,i);case"'":return zp(t,s);case"<":l=n[zp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Wp(c,1):r[u-1]+Wp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,em=jh,tm=TypeError,im=_a,rm=Fe,nm=c,om=function(e,t,i,r){var n=bp(e),o=!Cp((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags="",i[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===Rp||c===Dp.exec?o&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:s(i,t,r)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,n,c[1])}r&&kp(Dp[n],"sham",!0)},sm=i,am=Ce,cm=Ee,lm=T,dm=Mt,um=Ht,hm=fu,pm=I,mm=function(e,t,i){return t+(i?Bp(e,t).length:1)},_m=rt,fm=Yp,gm=function(e,t){var i=e.exec;if($p(i)){var r=Qp(i,e,t);return null!==r&&Xp(r),r}if("RegExp"===Zp(e))return Qp(em,e,t);throw tm("RegExp#exec called on incompatible receiver")},Tm=_e("replace"),Em=Math.max,Sm=Math.min,Im=nm([].concat),vm=nm([].push),ym=nm("".indexOf),Am=nm("".slice),Rm=function(e){return void 0===e?e:String(e)},Cm="$0"==="a".replace(/./,"$0"),bm=!!/./[Tm]&&""===/./[Tm]("a","$0"),km=!sm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));om("replace",(function(e,t,i){var r=bm?"$":"$0";return[function(e,i){var r=pm(this),n=lm(e)?void 0:_m(e,Tm);return n?rm(n,e,r,i):rm(t,hm(r),e,i)},function(e,n){var o=am(this),s=hm(e);if("string"==typeof n&&-1===ym(n,r)&&-1===ym(n,"$<")){var a=i(t,o,s,n);if(a.done)return a.value}var c=cm(n);c||(n=hm(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=gm(o,s);if(null===h)break;if(vm(u,h),!l)break;""===hm(h[0])&&(o.lastIndex=mm(s,um(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=hm((h=u[_])[0]),g=Em(Sm(dm(h.index),s.length),0),T=[],E=1;E<h.length;E++)vm(T,Rm(h[E]));var S=h.groups;if(c){var I=Im([f],T,g,s);void 0!==S&&vm(I,S);var v=hm(im(n,void 0,I))}else v=fm(f,s,g,T,S,n);g>=m&&(p+=Am(s,m,g)+v,m=g+f.length)}return p+Am(s,m)}]}),!km||!Cm||bm);var Nm=qt.includes,Dm=Fi;Vn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Nm(this,e,arguments.length>1?arguments[1]:void 0)}}),Dm("includes");var wm=Mt,Om=fu,Pm=I,Mm=RangeError,Lm=c,xm=Ht,Vm=fu,Um=function(e){var t=Om(Pm(this)),i="",r=wm(e);if(r<0||Infinity==r)throw Mm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},Fm=I,Bm=Lm(Um),Hm=Lm("".slice),jm=Math.ceil,Gm=function(e){return function(t,i,r){var n,o,s=Vm(Fm(t)),a=xm(i),c=s.length,l=void 0===r?" ":Vm(r);return a<=c||""==l?s:((o=Bm(l,jm((n=a-c)/l.length))).length>n&&(o=Hm(o,0,n)),e?s+o:o+s)}},Wm={start:Gm(!1),end:Gm(!0)},Jm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),zm=Wm.start;Vn({target:"String",proto:!0,forced:Jm},{padStart:function(e){return zm(this,e,arguments.length>1?arguments[1]:void 0)}});var Km=i,qm=ke,Ym=_e("iterator"),Qm=!Km((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!qm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Ym]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),Xm=tn,$m=function(e,t,i){for(var r in t)Xm(e,r,t[r],i);return e},Zm=Tt,e_=De,t_=Wi,i_=function(e,t,i){var r=Zm(t);r in e?e_.f(e,r,t_(0,i)):e[r]=i},r_=Ut,n_=Gt,o_=i_,s_=Array,a_=Math.max,c_=function(e,t,i){for(var r=n_(e),n=r_(t,r),o=r_(void 0===i?r:i,r),s=s_(a_(o-n,0)),a=0;n<o;n++,a++)o_(s,a,e[n]);return s.length=a,s},l_=c_,d_=Math.floor,u_=function(e,t){var i=e.length,r=d_(i/2);return i<8?h_(e,t):p_(e,u_(l_(e,0,r),t),u_(l_(e,r),t),t)},h_=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},p_=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},m_=u_,__=Vn,f_=C,g_=Fe,T_=c,E_=ke,S_=Qm,I_=tn,v_=Is,y_=$m,A_=oo,R_=po,C_=ar,b_=Ns,k_=Ee,N_=G,D_=va,w_=Vs,O_=Ce,P_=ve,M_=fu,L_=Di,x_=Wi,V_=ad,U_=ed,F_=Ra,B_=m_,H_=_e("iterator"),j_="URLSearchParams",G_=j_+"Iterator",W_=C_.set,J_=C_.getterFor(j_),z_=C_.getterFor(G_),K_=Object.getOwnPropertyDescriptor,q_=function(e){if(!E_)return f_[e];var t=K_(f_,e);return t&&t.value},Y_=q_("fetch"),Q_=q_("Request"),X_=q_("Headers"),$_=Q_&&Q_.prototype,Z_=X_&&X_.prototype,ef=f_.RegExp,tf=f_.TypeError,rf=f_.decodeURIComponent,nf=f_.encodeURIComponent,of=T_("".charAt),sf=T_([].join),af=T_([].push),cf=T_("".replace),lf=T_([].shift),df=T_([].splice),uf=T_("".split),hf=T_("".slice),pf=/\+/g,mf=Array(4),_f=function(e){return mf[e-1]||(mf[e-1]=ef("((?:%[\\da-f]{2}){"+e+"})","gi"))},ff=function(e){try{return rf(e)}catch(RF){return e}},gf=function(e){var t=cf(e,pf," "),i=4;try{return rf(t)}catch(RF){for(;i;)t=cf(t,_f(i--),ff);return t}},Tf=/[!'()~]|%20/g,Ef={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Sf=function(e){return Ef[e]},If=function(e){return cf(nf(e),Tf,Sf)},vf=R_((function(e,t){W_(this,{type:G_,iterator:V_(J_(e).entries),kind:t})}),"Iterator",(function(){var e=z_(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),yf=function(e){this.entries=[],this.url=null,void 0!==e&&(P_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===of(e,0)?hf(e,1):e:M_(e)))};yf.prototype={type:j_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=U_(e);if(c)for(i=(t=V_(e,c)).next;!(r=g_(i,t)).done;){if(o=(n=V_(O_(r.value))).next,(s=g_(o,n)).done||(a=g_(o,n)).done||!g_(o,n).done)throw tf("Expected sequence with length 2");af(this.entries,{key:M_(s.value),value:M_(a.value)})}else for(var l in e)N_(e,l)&&af(this.entries,{key:l,value:M_(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=uf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=uf(t,"="),af(this.entries,{key:gf(lf(i)),value:gf(sf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],af(i,If(e.key)+"="+If(e.value));return sf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Af=function(){b_(this,Rf);var e=W_(this,new yf(arguments.length>0?arguments[0]:void 0));E_||(this.length=e.entries.length)},Rf=Af.prototype;if(y_(Rf,{append:function(e,t){F_(arguments.length,2);var i=J_(this);af(i.entries,{key:M_(e),value:M_(t)}),E_||this.length++,i.updateURL()},delete:function(e){F_(arguments.length,1);for(var t=J_(this),i=t.entries,r=M_(e),n=0;n<i.length;)i[n].key===r?df(i,n,1):n++;E_||(this.length=i.length),t.updateURL()},get:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&af(r,t[n].value);return r},has:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){F_(arguments.length,1);for(var i,r=J_(this),n=r.entries,o=!1,s=M_(e),a=M_(t),c=0;c<n.length;c++)(i=n[c]).key===s&&(o?df(n,c--,1):(o=!0,i.value=a));o||af(n,{key:s,value:a}),E_||(this.length=n.length),r.updateURL()},sort:function(){var e=J_(this);B_(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=D_(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 vf(this,"keys")},values:function(){return new vf(this,"values")},entries:function(){return new vf(this,"entries")}},{enumerable:!0}),I_(Rf,H_,Rf.entries,{name:"entries"}),I_(Rf,"toString",(function(){return J_(this).serialize()}),{enumerable:!0}),E_&&v_(Rf,"size",{get:function(){return J_(this).entries.length},configurable:!0,enumerable:!0}),A_(Af,j_),__({global:!0,constructor:!0,forced:!S_},{URLSearchParams:Af}),!S_&&k_(X_)){var Cf=T_(Z_.has),bf=T_(Z_.set),kf=function(e){if(P_(e)){var t,i=e.body;if(w_(i)===j_)return t=e.headers?new X_(e.headers):new X_,Cf(t,"content-type")||bf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),L_(e,{body:x_(0,M_(i)),headers:x_(0,t)})}return e};if(k_(Y_)&&__({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Y_(e,arguments.length>1?kf(arguments[1]):{})}}),k_(Q_)){var Nf=function(e){return b_(this,$_),new Q_(e,arguments.length>1?kf(arguments[1]):{})};$_.constructor=Nf,Nf.prototype=$_,__({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Nf})}}var Df={URLSearchParams:Af,getState:J_},wf="\t\n\v\f\r \u2028\u2029\ufeff",Of=I,Pf=fu,Mf=wf,Lf=c("".replace),xf=RegExp("^["+Mf+"]+"),Vf=RegExp("(^|[^"+Mf+"])["+Mf+"]+$"),Uf=function(e){return function(t){var i=Pf(Of(t));return 1&e&&(i=Lf(i,xf,"")),2&e&&(i=Lf(i,Vf,"$1")),i}},Ff={start:Uf(1),end:Uf(2),trim:Uf(3)},Bf=Nr.PROPER,Hf=i,jf=wf,Gf=Ff.trim;Vn({target:"String",proto:!0,forced:function(e){return Hf((function(){return!!jf[e]()||"
"!=="
"[e]()||Bf&&jf[e].name!==e}))}("trim")},{trim:function(){return Gf(this)}});var Wf=Vn,Jf=ke,zf=c,Kf=G,qf=Ee,Yf=Ge,Qf=fu,Xf=Is,$f=Sn,Zf=C.Symbol,eg=Zf&&Zf.prototype;if(Jf&&qf(Zf)&&(!("description"in eg)||void 0!==Zf().description)){var tg={},ig=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Qf(arguments[0]),t=Yf(eg,this)?new Zf(e):void 0===e?Zf():Zf(e);return""===e&&(tg[t]=!0),t};$f(ig,Zf),ig.prototype=eg,eg.constructor=ig;var rg="Symbol(test)"==String(Zf("test")),ng=zf(eg.valueOf),og=zf(eg.toString),sg=/^Symbol\((.*)\)[^)]+$/,ag=zf("".replace),cg=zf("".slice);Xf(eg,"description",{configurable:!0,get:function(){var e=ng(this);if(Kf(tg,e))return"";var t=og(e),i=rg?cg(t,7,-1):ag(t,sg,"$1");return""===i?void 0:i}}),Wf({global:!0,constructor:!0,forced:!0},{Symbol:ig})}var lg=Fp.charAt,dg=fu,ug=ar,hg=jo,pg=Go,mg="String Iterator",_g=ug.set,fg=ug.getterFor(mg);hg(String,"String",(function(e){_g(this,{type:mg,string:dg(e),index:0})}),(function(){var e,t=fg(this),i=t.string,r=t.index;return r>=i.length?pg(void 0,!0):(e=lg(i,r),t.index+=e.length,pg(e,!1))}));var gg,Tg=ke,Eg=c,Sg=Fe,Ig=i,vg=oi,yg=sn,Ag=lr,Rg=B,Cg=g,bg=Object.assign,kg=Object.defineProperty,Ng=Eg([].concat),Dg=!bg||Ig((function(){if(Tg&&1!==bg({b:1},bg(kg({},"a",{enumerable:!0,get:function(){kg(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!=bg({},e)[i]||vg(bg({},t)).join("")!=r}))?function(e,t){for(var i=Rg(e),r=arguments.length,n=1,o=yg.f,s=Ag.f;r>n;)for(var a,c=Cg(arguments[n++]),l=o?Ng(vg(c),o(c)):vg(c),d=l.length,u=0;d>u;)a=l[u++],Tg&&!Sg(s,c,a)||(i[a]=c[a]);return i}:bg,wg=Ce,Og=ud,Pg=va,Mg=Fe,Lg=B,xg=function(e,t,i,r){try{return r?t(wg(i)[0],i[1]):t(i)}catch(RF){Og(e,"throw",RF)}},Vg=ql,Ug=ta,Fg=Gt,Bg=i_,Hg=ad,jg=ed,Gg=Array,Wg=c,Jg=2147483647,zg=/[^\0-\u007E]/,Kg=/[.\u3002\uFF0E\uFF61]/g,qg="Overflow: input needs wider integers to process",Yg=RangeError,Qg=Wg(Kg.exec),Xg=Math.floor,$g=String.fromCharCode,Zg=Wg("".charCodeAt),eT=Wg([].join),tT=Wg([].push),iT=Wg("".replace),rT=Wg("".split),nT=Wg("".toLowerCase),oT=function(e){return e+22+75*(e<26)},sT=function(e,t,i){var r=0;for(e=i?Xg(e/700):e>>1,e+=Xg(e/t);e>455;)e=Xg(e/35),r+=36;return Xg(r+36*e/(e+38))},aT=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=Zg(e,i++);if(n>=55296&&n<=56319&&i<r){var o=Zg(e,i++);56320==(64512&o)?tT(t,((1023&n)<<10)+(1023&o)+65536):(tT(t,n),i--)}else tT(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&&tT(t,$g(r));var c=t.length,l=c;for(c&&tT(t,"-");l<n;){var d=Jg;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>Xg((Jg-s)/u))throw Yg(qg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>Jg)throw Yg(qg);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;tT(t,$g(oT(m+_%f))),h=Xg(_/f),p+=36}tT(t,$g(oT(h))),a=sT(s,u,l==c),s=0,l++}}s++,o++}return eT(t,"")},cT=Vn,lT=ke,dT=Qm,uT=C,hT=va,pT=c,mT=tn,_T=Is,fT=Ns,gT=G,TT=Dg,ET=function(e){var t=Lg(e),i=Ug(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Pg(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=jg(t),p=0;if(!h||this===Gg&&Vg(h))for(s=Fg(t),a=i?new this(s):Gg(s);s>p;p++)u=o?n(t[p],p):t[p],Bg(a,p,u);else for(d=(l=Hg(t,h)).next,a=i?new this:[];!(c=Mg(d,l)).done;p++)u=o?xg(l,n,[c.value,p],!0):c.value,Bg(a,p,u);return a.length=p,a},ST=c_,IT=Fp.codeAt,vT=function(e){var t,i,r=[],n=rT(iT(nT(e),Kg,"."),".");for(t=0;t<n.length;t++)i=n[t],tT(r,Qg(zg,i)?"xn--"+aT(i):i);return eT(r,".")},yT=fu,AT=oo,RT=Ra,CT=Df,bT=ar,kT=bT.set,NT=bT.getterFor("URL"),DT=CT.URLSearchParams,wT=CT.getState,OT=uT.URL,PT=uT.TypeError,MT=uT.parseInt,LT=Math.floor,xT=Math.pow,VT=pT("".charAt),UT=pT(/./.exec),FT=pT([].join),BT=pT(1..toString),HT=pT([].pop),jT=pT([].push),GT=pT("".replace),WT=pT([].shift),JT=pT("".split),zT=pT("".slice),KT=pT("".toLowerCase),qT=pT([].unshift),YT="Invalid scheme",QT="Invalid host",XT="Invalid port",$T=/[a-z]/i,ZT=/[\d+-.a-z]/i,eE=/\d/,tE=/^0x/i,iE=/^[0-7]+$/,rE=/^\d+$/,nE=/^[\da-f]+$/i,oE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,sE=/[\0\t\n\r #/:<>?@[\\\]^|]/,aE=/^[\u0000-\u0020]+/,cE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,lE=/[\t\n\r]/g,dE=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)qT(t,e%256),e=LT(e/256);return FT(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+=BT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},uE={},hE=TT({},uE,{" ":1,'"':1,"<":1,">":1,"`":1}),pE=TT({},hE,{"#":1,"?":1,"{":1,"}":1}),mE=TT({},pE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),_E=function(e,t){var i=IT(e,0);return i>32&&i<127&&!gT(t,e)?e:encodeURIComponent(e)},fE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},gE=function(e,t){var i;return 2==e.length&&UT($T,VT(e,0))&&(":"==(i=VT(e,1))||!t&&"|"==i)},TE=function(e){var t;return e.length>1&&gE(zT(e,0,2))&&(2==e.length||"/"===(t=VT(e,2))||"\\"===t||"?"===t||"#"===t)},EE=function(e){return"."===e||"%2e"===KT(e)},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},wE={},OE={},PE={},ME={},LE={},xE={},VE={},UE={},FE={},BE={},HE=function(e,t,i){var r,n,o,s=yT(e);if(t){if(n=this.parse(s))throw PT(n);this.searchParams=null}else{if(void 0!==i&&(r=new HE(i,!0)),n=this.parse(s,null,r))throw PT(n);(o=wT(new DT)).bindURL(this),this.searchParams=o}};HE.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||SE,d=0,u="",h=!1,p=!1,m=!1;for(e=yT(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=GT(e,aE,""),e=GT(e,cE,"$1")),e=GT(e,lE,""),r=ET(e);d<=r.length;){switch(n=r[d],l){case SE:if(!n||!UT($T,n)){if(t)return YT;l=vE;continue}u+=KT(n),l=IE;break;case IE:if(n&&(UT(ZT,n)||"+"==n||"-"==n||"."==n))u+=KT(n);else{if(":"!=n){if(t)return YT;u="",l=vE,d=0;continue}if(t&&(c.isSpecial()!=gT(fE,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&fE[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=PE:c.isSpecial()&&i&&i.scheme==c.scheme?l=yE:c.isSpecial()?l=bE:"/"==r[d+1]?(l=AE,d++):(c.cannotBeABaseURL=!0,jT(c.path,""),l=UE)}break;case vE:if(!i||i.cannotBeABaseURL&&"#"!=n)return YT;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=ST(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=BE;break}l="file"==i.scheme?PE:RE;continue;case yE:if("/"!=n||"/"!=r[d+1]){l=RE;continue}l=kE,d++;break;case AE:if("/"==n){l=NE;break}l=VE;continue;case RE:if(c.scheme=i.scheme,n==gg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=CE;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query="",l=FE;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.path.length--,l=VE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query,c.fragment="",l=BE}break;case CE:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=VE;continue}l=NE}else l=kE;break;case bE:if(l=kE,"/"!=n||"/"!=VT(u,d+1))continue;d++;break;case kE:if("/"!=n&&"\\"!=n){l=NE;continue}break;case NE:if("@"==n){h&&(u="%40"+u),h=!0,o=ET(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=_E(f,mE);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=ET(u).length+1,u="",l=DE}else u+=n;break;case DE:case wE:if(t&&"file"==c.scheme){l=LE;continue}if(":"!=n||p){if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return QT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=xE,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return QT;if(s=c.parseHost(u))return s;if(u="",l=OE,t==wE)return}break;case OE:if(!UT(eE,n)){if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=MT(u,10);if(T>65535)return XT;c.port=c.isSpecial()&&T===fE[c.scheme]?null:T,u=""}if(t)return;l=xE;continue}return XT}u+=n;break;case PE:if(c.scheme="file","/"==n||"\\"==n)l=ME;else{if(!i||"file"!=i.scheme){l=VE;continue}if(n==gg)c.host=i.host,c.path=ST(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=ST(i.path),c.query="",l=FE;else{if("#"!=n){TE(FT(ST(r,d),""))||(c.host=i.host,c.path=ST(i.path),c.shortenPath()),l=VE;continue}c.host=i.host,c.path=ST(i.path),c.query=i.query,c.fragment="",l=BE}}break;case ME:if("/"==n||"\\"==n){l=LE;break}i&&"file"==i.scheme&&!TE(FT(ST(r,d),""))&&(gE(i.path[0],!0)?jT(c.path,i.path[0]):c.host=i.host),l=VE;continue;case LE:if(n==gg||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&gE(u))l=VE;else if(""==u){if(c.host="",t)return;l=xE}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=xE}continue}u+=n;break;case xE:if(c.isSpecial()){if(l=VE,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=gg&&(l=VE,"/"!=n))continue}else c.fragment="",l=BE;else c.query="",l=FE;break;case VE:if(n==gg||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=KT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||jT(c.path,"")):EE(u)?"/"==n||"\\"==n&&c.isSpecial()||jT(c.path,""):("file"==c.scheme&&!c.path.length&&gE(u)&&(c.host&&(c.host=""),u=VT(u,0)+":"),jT(c.path,u)),u="","file"==c.scheme&&(n==gg||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)WT(c.path);"?"==n?(c.query="",l=FE):"#"==n&&(c.fragment="",l=BE)}else u+=_E(n,pE);break;case UE:"?"==n?(c.query="",l=FE):"#"==n?(c.fragment="",l=BE):n!=gg&&(c.path[0]+=_E(n,uE));break;case FE:t||"#"!=n?n!=gg&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":_E(n,uE)):(c.fragment="",l=BE);break;case BE:n!=gg&&(c.fragment+=_E(n,hE))}d++}},parseHost:function(e){var t,i,r;if("["==VT(e,0)){if("]"!=VT(e,e.length-1))return QT;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 VT(e,u)};if(":"==h()){if(":"!=VT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&UT(nE,h());)t=16*t+MT(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(!UT(eE,h()))return;for(;UT(eE,h());){if(o=MT(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}(zT(e,1,-1)),!t)return QT;this.host=t}else if(this.isSpecial()){if(e=vT(e),UT(oE,e))return QT;if(t=function(e){var t,i,r,n,o,s,a,c=JT(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"==VT(n,0)&&(o=UT(tE,n)?16:8,n=zT(n,8==o?1:2)),""===n)s=0;else{if(!UT(10==o?rE:8==o?iE:nE,n))return e;s=MT(n,o)}jT(i,s)}for(r=0;r<t;r++)if(s=i[r],r==t-1){if(s>=xT(256,5-t))return null}else if(s>255)return null;for(a=HT(i),r=0;r<i.length;r++)a+=i[r]*xT(256,3-r);return a}(e),null===t)return QT;this.host=t}else{if(UT(sE,e))return QT;for(t="",i=ET(e),r=0;r<i.length;r++)t+=_E(i[r],uE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return gT(fE,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&gE(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+=dE(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+FT(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw PT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new jE(e.path[0]).origin}catch(RF){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+dE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(yT(e)+":",SE)},getUsername:function(){return this.username},setUsername:function(e){var t=ET(yT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=_E(t[i],mE)}},getPassword:function(){return this.password},setPassword:function(e){var t=ET(yT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=_E(t[i],mE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?dE(e):dE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,DE)},getHostname:function(){var e=this.host;return null===e?"":dE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,wE)},getPort:function(){var e=this.port;return null===e?"":yT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=yT(e))?this.port=null:this.parse(e,OE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+FT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,xE))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=yT(e))?this.query=null:("?"==VT(e,0)&&(e=zT(e,1)),this.query="",this.parse(e,FE)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=yT(e))?("#"==VT(e,0)&&(e=zT(e,1)),this.fragment="",this.parse(e,BE)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var jE=function(e){var t=fT(this,GE),i=RT(arguments.length,1)>1?arguments[1]:void 0,r=kT(t,new HE(e,!1,i));lT||(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())},GE=jE.prototype,WE=function(e,t){return{get:function(){return NT(this)[e]()},set:t&&function(e){return NT(this)[t](e)},configurable:!0,enumerable:!0}};if(lT&&(_T(GE,"href",WE("serialize","setHref")),_T(GE,"origin",WE("getOrigin")),_T(GE,"protocol",WE("getProtocol","setProtocol")),_T(GE,"username",WE("getUsername","setUsername")),_T(GE,"password",WE("getPassword","setPassword")),_T(GE,"host",WE("getHost","setHost")),_T(GE,"hostname",WE("getHostname","setHostname")),_T(GE,"port",WE("getPort","setPort")),_T(GE,"pathname",WE("getPathname","setPathname")),_T(GE,"search",WE("getSearch","setSearch")),_T(GE,"searchParams",WE("getSearchParams")),_T(GE,"hash",WE("getHash","setHash"))),mT(GE,"toJSON",(function(){return NT(this).serialize()}),{enumerable:!0}),mT(GE,"toString",(function(){return NT(this).serialize()}),{enumerable:!0}),OT){var JE=OT.createObjectURL,zE=OT.revokeObjectURL;JE&&mT(jE,"createObjectURL",hT(JE,OT)),zE&&mT(jE,"revokeObjectURL",hT(zE,OT))}AT(jE,"URL"),cT({global:!0,constructor:!0,forced:!dT,sham:!lT},{URL:jE});var KE="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qE=Mt,YE=Ht,QE=RangeError,XE=function(e){if(void 0===e)return 0;var t=qE(e),i=YE(t);if(t!==i)throw QE("Wrong length or index");return i},$E=Array,ZE=Math.abs,eS=Math.pow,tS=Math.floor,iS=Math.log,rS=Math.LN2,nS={pack:function(e,t,i){var r,n,o,s=$E(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?eS(2,-24)-eS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=ZE(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=tS(iS(e)/rS),e*(o=eS(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*eS(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*eS(2,t),r+=l):(n=e*eS(2,l-1)*eS(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+=eS(2,t),d-=s}return(l?-1:1)*i*eS(2,d-t)}},oS=B,sS=Ut,aS=Gt,cS=function(e){for(var t=oS(this),i=aS(t),r=arguments.length,n=sS(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:sS(o,i);s>n;)t[n++]=e;return t},lS=C,dS=c,uS=ke,hS=KE,pS=Nr,mS=Ki,_S=Is,fS=$m,gS=i,TS=Ns,ES=Mt,SS=Ht,IS=XE,vS=nS,yS=zn,AS=vo,RS=rn.f,CS=cS,bS=c_,kS=oo,NS=ar,DS=pS.PROPER,wS=pS.CONFIGURABLE,OS="ArrayBuffer",PS="DataView",MS="prototype",LS="Wrong index",xS=NS.getterFor(OS),VS=NS.getterFor(PS),US=NS.set,FS=lS[OS],BS=FS,HS=BS&&BS[MS],jS=lS[PS],GS=jS&&jS[MS],WS=Object.prototype,JS=lS.Array,zS=lS.RangeError,KS=dS(CS),qS=dS([].reverse),YS=vS.pack,QS=vS.unpack,XS=function(e){return[255&e]},$S=function(e){return[255&e,e>>8&255]},ZS=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},eI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},tI=function(e){return YS(e,23,4)},iI=function(e){return YS(e,52,8)},rI=function(e,t,i){_S(e[MS],t,{configurable:!0,get:function(){return i(this)[t]}})},nI=function(e,t,i,r){var n=IS(i),o=VS(e);if(n+t>o.byteLength)throw zS(LS);var s=o.bytes,a=n+o.byteOffset,c=bS(s,a,a+t);return r?c:qS(c)},oI=function(e,t,i,r,n,o){var s=IS(i),a=VS(e);if(s+t>a.byteLength)throw zS(LS);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(hS){var sI=DS&&FS.name!==OS;if(gS((function(){FS(1)}))&&gS((function(){new FS(-1)}))&&!gS((function(){return new FS,new FS(1.5),new FS(NaN),1!=FS.length||sI&&!wS})))sI&&wS&&mS(FS,"name",OS);else{(BS=function(e){return TS(this,HS),new FS(IS(e))})[MS]=HS;for(var aI,cI=RS(FS),lI=0;cI.length>lI;)(aI=cI[lI++])in BS||mS(BS,aI,FS[aI]);HS.constructor=BS}AS&&yS(GS)!==WS&&AS(GS,WS);var dI=new jS(new BS(2)),uI=dS(GS.setInt8);dI.setInt8(0,2147483648),dI.setInt8(1,2147483649),!dI.getInt8(0)&&dI.getInt8(1)||fS(GS,{setInt8:function(e,t){uI(this,e,t<<24>>24)},setUint8:function(e,t){uI(this,e,t<<24>>24)}},{unsafe:!0})}else HS=(BS=function(e){TS(this,HS);var t=IS(e);US(this,{type:OS,bytes:KS(JS(t),0),byteLength:t}),uS||(this.byteLength=t,this.detached=!1)})[MS],GS=(jS=function(e,t,i){TS(this,GS),TS(e,HS);var r=xS(e),n=r.byteLength,o=ES(t);if(o<0||o>n)throw zS("Wrong offset");if(o+(i=void 0===i?n-o:SS(i))>n)throw zS("Wrong length");US(this,{type:PS,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),uS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[MS],uS&&(rI(BS,"byteLength",xS),rI(jS,"buffer",VS),rI(jS,"byteLength",VS),rI(jS,"byteOffset",VS)),fS(GS,{getInt8:function(e){return nI(this,1,e)[0]<<24>>24},getUint8:function(e){return nI(this,1,e)[0]},getInt16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=nI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return eI(nI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return eI(nI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return QS(nI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return QS(nI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){oI(this,1,e,XS,t)},setUint8:function(e,t){oI(this,1,e,XS,t)},setInt16:function(e,t){oI(this,2,e,$S,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){oI(this,2,e,$S,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){oI(this,4,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){oI(this,4,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){oI(this,4,e,tI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){oI(this,8,e,iI,t,arguments.length>2?arguments[2]:void 0)}});kS(BS,OS),kS(jS,PS);var hI={ArrayBuffer:BS,DataView:jS},pI=Vn,mI=Ta,_I=i,fI=Ce,gI=Ut,TI=Ht,EI=da,SI=hI.ArrayBuffer,II=hI.DataView,vI=II.prototype,yI=mI(SI.prototype.slice),AI=mI(vI.getUint8),RI=mI(vI.setUint8);pI({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:_I((function(){return!new SI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(yI&&void 0===t)return yI(fI(this),e);for(var i=fI(this).byteLength,r=gI(e,i),n=gI(void 0===t?i:t,i),o=new(EI(this,SI))(TI(n-r)),s=new II(this),a=new II(o),c=0;r<n;)RI(a,c++,AI(s,r++));return o}});var CI,bI,kI,NI={},DI={get exports(){return NI},set exports(e){NI=e}},wI=KE,OI=ke,PI=C,MI=Ee,LI=ve,xI=G,VI=Vs,UI=Qe,FI=Ki,BI=tn,HI=Is,jI=Ge,GI=zn,WI=vo,JI=_e,zI=q,KI=ar.enforce,qI=ar.get,YI=PI.Int8Array,QI=YI&&YI.prototype,XI=PI.Uint8ClampedArray,$I=XI&&XI.prototype,ZI=YI&&GI(YI),ev=QI&&GI(QI),tv=Object.prototype,iv=PI.TypeError,rv=JI("toStringTag"),nv=zI("TYPED_ARRAY_TAG"),ov="TypedArrayConstructor",sv=wI&&!!WI&&"Opera"!==VI(PI.opera),av=!1,cv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},lv={BigInt64Array:8,BigUint64Array:8},dv=function(e){var t=GI(e);if(LI(t)){var i=qI(t);return i&&xI(i,ov)?i[ov]:dv(t)}},uv=function(e){if(!LI(e))return!1;var t=VI(e);return xI(cv,t)||xI(lv,t)};for(CI in cv)(kI=(bI=PI[CI])&&bI.prototype)?KI(kI)[ov]=bI:sv=!1;for(CI in lv)(kI=(bI=PI[CI])&&bI.prototype)&&(KI(kI)[ov]=bI);if((!sv||!MI(ZI)||ZI===Function.prototype)&&(ZI=function(){throw iv("Incorrect invocation")},sv))for(CI in cv)PI[CI]&&WI(PI[CI],ZI);if((!sv||!ev||ev===tv)&&(ev=ZI.prototype,sv))for(CI in cv)PI[CI]&&WI(PI[CI].prototype,ev);if(sv&&GI($I)!==ev&&WI($I,ev),OI&&!xI(ev,rv))for(CI in av=!0,HI(ev,rv,{configurable:!0,get:function(){return LI(this)?this[nv]:void 0}}),cv)PI[CI]&&FI(PI[CI],nv,CI);var hv={NATIVE_ARRAY_BUFFER_VIEWS:sv,TYPED_ARRAY_TAG:av&&nv,aTypedArray:function(e){if(uv(e))return e;throw iv("Target is not a typed array")},aTypedArrayConstructor:function(e){if(MI(e)&&(!WI||jI(ZI,e)))return e;throw iv(UI(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(OI){if(i)for(var n in cv){var o=PI[n];if(o&&xI(o.prototype,e))try{delete o.prototype[e]}catch(RF){try{o.prototype[e]=t}catch(s){}}}ev[e]&&!i||BI(ev,e,i?t:sv&&QI[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(OI){if(WI){if(i)for(r in cv)if((n=PI[r])&&xI(n,e))try{delete n[e]}catch(RF){}if(ZI[e]&&!i)return;try{return BI(ZI,e,i?t:sv&&ZI[e]||t)}catch(RF){}}for(r in cv)!(n=PI[r])||n[e]&&!i||BI(n,e,t)}},getTypedArrayConstructor:dv,isView:function(e){if(!LI(e))return!1;var t=VI(e);return"DataView"===t||xI(cv,t)||xI(lv,t)},isTypedArray:uv,TypedArray:ZI,TypedArrayPrototype:ev},pv=C,mv=i,_v=Dd,fv=hv.NATIVE_ARRAY_BUFFER_VIEWS,gv=pv.ArrayBuffer,Tv=pv.Int8Array,Ev=!fv||!mv((function(){Tv(1)}))||!mv((function(){new Tv(-1)}))||!_v((function(e){new Tv,new Tv(null),new Tv(1.5),new Tv(e)}),!0)||mv((function(){return 1!==new Tv(new gv(2),1,void 0).length})),Sv=ve,Iv=Math.floor,vv=Number.isInteger||function(e){return!Sv(e)&&isFinite(e)&&Iv(e)===e},yv=Mt,Av=RangeError,Rv=function(e){var t=yv(e);if(t<0)throw Av("The argument can't be less than 0");return t},Cv=RangeError,bv=function(e,t){var i=Rv(e);if(i%t)throw Cv("Wrong offset");return i},kv=Vs,Nv=_t,Dv=TypeError,wv=function(e){var t=Nv(e,"number");if("number"==typeof t)throw Dv("Can't convert number to bigint");return BigInt(t)},Ov=va,Pv=Fe,Mv=oa,Lv=B,xv=Gt,Vv=ad,Uv=ed,Fv=ql,Bv=function(e){var t=kv(e);return"BigInt64Array"==t||"BigUint64Array"==t},Hv=hv.aTypedArrayConstructor,jv=wv,Gv=function(e){var t,i,r,n,o,s,a,c,l=Mv(this),d=Lv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Uv(d);if(m&&!Fv(m))for(c=(a=Vv(d,m)).next,d=[];!(s=Pv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Ov(h,arguments[2])),i=xv(d),r=new(Hv(l))(i),n=Bv(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?jv(o):+o;return r},Wv=Vn,Jv=C,zv=Fe,Kv=ke,qv=Ev,Yv=hv,Qv=hI,Xv=Ns,$v=Wi,Zv=Ki,ey=vv,ty=Ht,iy=XE,ry=bv,ny=Tt,oy=G,sy=Vs,ay=ve,cy=qe,ly=Di,dy=Ge,uy=vo,hy=rn.f,py=Gv,my=np.forEach,_y=Cs,fy=Is,gy=De,Ty=cr,Ey=lu,Sy=ar.get,Iy=ar.set,vy=ar.enforce,yy=gy.f,Ay=Ty.f,Ry=Math.round,Cy=Jv.RangeError,by=Qv.ArrayBuffer,ky=by.prototype,Ny=Qv.DataView,Dy=Yv.NATIVE_ARRAY_BUFFER_VIEWS,wy=Yv.TYPED_ARRAY_TAG,Oy=Yv.TypedArray,Py=Yv.TypedArrayPrototype,My=Yv.aTypedArrayConstructor,Ly=Yv.isTypedArray,xy="BYTES_PER_ELEMENT",Vy="Wrong length",Uy=function(e,t){My(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},Fy=function(e,t){fy(e,t,{configurable:!0,get:function(){return Sy(this)[t]}})},By=function(e){var t;return dy(ky,e)||"ArrayBuffer"==(t=sy(e))||"SharedArrayBuffer"==t},Hy=function(e,t){return Ly(e)&&!cy(t)&&t in e&&ey(+t)&&t>=0},jy=function(e,t){return t=ny(t),Hy(e,t)?$v(2,e[t]):Ay(e,t)},Gy=function(e,t,i){return t=ny(t),!(Hy(e,t)&&ay(i)&&oy(i,"value"))||oy(i,"get")||oy(i,"set")||i.configurable||oy(i,"writable")&&!i.writable||oy(i,"enumerable")&&!i.enumerable?yy(e,t,i):(e[t]=i.value,e)};Kv?(Dy||(Ty.f=jy,gy.f=Gy,Fy(Py,"buffer"),Fy(Py,"byteOffset"),Fy(Py,"byteLength"),Fy(Py,"length")),Wv({target:"Object",stat:!0,forced:!Dy},{getOwnPropertyDescriptor:jy,defineProperty:Gy}),DI.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=Jv[n],c=a,l=c&&c.prototype,d={},u=function(e,t){yy(e,t,{get:function(){return function(e,t){var i=Sy(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=Sy(e);i&&(n=(n=Ry(n))<0?0:n>255?255:255&n),o.view[s](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};Dy?qv&&(c=t((function(e,t,i,n){return Xv(e,l),Ey(ay(t)?By(t)?void 0!==n?new a(t,ry(i,r),n):void 0!==i?new a(t,ry(i,r)):new a(t):Ly(t)?Uy(c,t):zv(py,c,t):new a(iy(t)),e,c)})),uy&&uy(c,Oy),my(hy(a),(function(e){e in c||Zv(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){Xv(e,l);var o,s,a,d=0,h=0;if(ay(t)){if(!By(t))return Ly(t)?Uy(c,t):zv(py,c,t);o=t,h=ry(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw Cy(Vy);if((s=p-h)<0)throw Cy(Vy)}else if((s=ty(n)*r)+h>p)throw Cy(Vy);a=s/r}else a=iy(t),o=new by(s=a*r);for(Iy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Ny(o)});d<a;)u(e,d++)})),uy&&uy(c,Oy),l=c.prototype=ly(Py)),l.constructor!==c&&Zv(l,"constructor",c),vy(l).TypedArrayConstructor=c,wy&&Zv(l,wy,n);var h=c!=a;d[n]=c,Wv({global:!0,constructor:!0,forced:h,sham:!Dy},d),xy in c||Zv(c,xy,r),xy in l||Zv(l,xy,r),_y(n)}):DI.exports=function(){},NI("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var Wy=cS,Jy=wv,zy=Vs,Ky=Fe,qy=i,Yy=hv.aTypedArray,Qy=hv.exportTypedArrayMethod,Xy=c("".slice);Qy("fill",(function(e){var t=arguments.length;Yy(this);var i="Big"===Xy(zy(this),0,3)?Jy(e):+e;return Ky(Wy,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),qy((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var $y=C,Zy=Fe,eA=hv,tA=Gt,iA=bv,rA=B,nA=i,oA=$y.RangeError,sA=$y.Int8Array,aA=sA&&sA.prototype,cA=aA&&aA.set,lA=eA.aTypedArray,dA=eA.exportTypedArrayMethod,uA=!nA((function(){var e=new Uint8ClampedArray(2);return Zy(cA,e,{length:1,0:3},1),3!==e[1]})),hA=uA&&eA.NATIVE_ARRAY_BUFFER_VIEWS&&nA((function(){var e=new sA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));dA("set",(function(e){lA(this);var t=iA(arguments.length>1?arguments[1]:void 0,1),i=rA(e);if(uA)return Zy(cA,this,i,t);var r=this.length,n=tA(i),o=0;if(n+t>r)throw oA("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!uA||hA);var pA=Y.match(/firefox\/(\d+)/i),mA=!!pA&&+pA[1],_A=/MSIE|Trident/.test(Y),fA=Y.match(/AppleWebKit\/(\d+)\./),gA=!!fA&&+fA[1],TA=Ta,EA=i,SA=et,IA=m_,vA=mA,yA=_A,AA=ie,RA=gA,CA=hv.aTypedArray,bA=hv.exportTypedArrayMethod,kA=C.Uint16Array,NA=kA&&TA(kA.prototype.sort),DA=!(!NA||EA((function(){NA(new kA(2),null)}))&&EA((function(){NA(new kA(2),{})}))),wA=!!NA&&!EA((function(){if(AA)return AA<74;if(vA)return vA<67;if(yA)return!0;if(RA)return RA<602;var e,t,i=new kA(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(NA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));bA("sort",(function(e){return void 0!==e&&SA(e),wA?NA(this,e):IA(CA(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))}),!wA||DA),NI("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var OA=Vn,PA=kc,MA=i,LA=je,xA=Ee,VA=da,UA=iu,FA=tn,BA=PA&&PA.prototype;if(OA({target:"Promise",proto:!0,real:!0,forced:!!PA&&MA((function(){BA.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=VA(this,LA("Promise")),i=xA(e);return this.then(i?function(i){return UA(t,e()).then((function(){return i}))}:e,i?function(i){return UA(t,e()).then((function(){throw i}))}:e)}}),xA(PA)){var HA=LA("Promise").prototype.finally;BA.finally!==HA&&FA(BA,"finally",HA,{unsafe:!0})}var jA=Cs,GA="ArrayBuffer",WA=hI[GA];Vn({global:!0,constructor:!0,forced:C[GA]!==WA},{ArrayBuffer:WA}),jA(GA);var JA=Vn,zA=Wh,KA=c([].reverse),qA=[1,2];JA({target:"Array",proto:!0,forced:String(qA)===String(qA.reverse())},{reverse:function(){return zA(this)&&(this.length=this.length),KA(this)}});var YA=C;Vn({global:!0,forced:YA.globalThis!==YA},{globalThis:YA});var QA=Qe,XA=TypeError,$A=Vn,ZA=c,eR=et,tR=B,iR=Gt,rR=function(e,t){if(!delete e[t])throw XA("Cannot delete property "+QA(t)+" of "+QA(e))},nR=fu,oR=i,sR=m_,aR=sp,cR=mA,lR=_A,dR=ie,uR=gA,hR=[],pR=ZA(hR.sort),mR=ZA(hR.push),_R=oR((function(){hR.sort(void 0)})),fR=oR((function(){hR.sort(null)})),gR=aR("sort"),TR=!oR((function(){if(dR)return dR<70;if(!(cR&&cR>3)){if(lR)return!0;if(uR)return uR<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++)hR.push({k:t+r,v:i})}for(hR.sort((function(e,t){return t.v-e.v})),r=0;r<hR.length;r++)t=hR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));$A({target:"Array",proto:!0,forced:_R||!fR||!gR||!TR},{sort:function(e){void 0!==e&&eR(e);var t=tR(this);if(TR)return void 0===e?pR(t):pR(t,e);var i,r,n=[],o=iR(t);for(r=0;r<o;r++)r in t&&mR(n,t[r]);for(sR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:nR(t)>nR(i)?1:-1}}(e)),i=iR(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)rR(t,r++);return t}});var ER=Vn,SR=Fe,IR=c,vR=I,yR=Ee,AR=T,RR=pu,CR=fu,bR=rt,kR=Au,NR=Yp,DR=_e("replace"),wR=TypeError,OR=IR("".indexOf);IR("".replace);var PR=IR("".slice),MR=Math.max,LR=function(e,t,i){return i>e.length?-1:""===t?i:OR(e,t,i)};ER({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d=vR(this),u=0,h=0,p="";if(!AR(e)){if(RR(e)&&(i=CR(vR(kR(e))),!~OR(i,"g")))throw wR("`.replaceAll` does not allow non-global regexes");if(r=bR(e,DR))return SR(r,e,d,t)}for(n=CR(d),o=CR(e),(s=yR(t))||(t=CR(t)),a=o.length,c=MR(1,a),u=LR(n,o,0);-1!==u;)l=s?CR(t(o,u,n)):NR(o,n,u,[],void 0,t),p+=PR(n,h,u)+l,h=u+a,u=LR(n,o,u+c);return h<n.length&&(p+=PR(n,h)),p}}),(0,hv.exportTypedArrayStaticMethod)("from",Gv,Ev);let xR=!0,VR=!0;function UR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function FR(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 BR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(xR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function HR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(VR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function jR(){if("object"==typeof window){if(xR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function GR(e,t){VR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function WR(e){return"[object Object]"===Object.prototype.toString.call(e)}function JR(e){return WR(e)?Object.keys(e).reduce((function(t,i){const r=WR(e[i]),n=r?JR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function zR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?zR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{zR(e,e.get(t),i)}))})))}function KR(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&&zR(e,i,n)}))})),n}const qR=jR;function YR(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),qR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return qR("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 QR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function XR(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 FR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function $R(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 ZR(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 eC(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=>KR(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}),FR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>KR(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 tC(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 iC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return tC(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 rC(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 nC(e,t){FR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var oC=Object.freeze({__proto__:null,shimMediaStream:QR,shimOnTrack:XR,shimGetSendersWithDtmf:$R,shimGetStats:ZR,shimSenderReceiverGetStats:eC,shimAddTrackRemoveTrackWithNative:tC,shimAddTrackRemoveTrack:iC,shimPeerConnection:rC,fixNegotiationNeeded:nC,shimGetUserMedia:YR,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 sC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){GR("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 aC(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 cC(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(Ob){if("TypeError"!==Ob.name)throw Ob;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function lC(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 dC(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}),FR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function uC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){GR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function hC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function pC(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 mC(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 _C(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 fC(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 gC=Object.freeze({__proto__:null,shimOnTrack:aC,shimPeerConnection:cC,shimSenderGetStats:lC,shimReceiverGetStats:dC,shimRemoveStream:uC,shimRTCDataChannel:hC,shimAddTransceiver:pC,shimGetParameters:mC,shimCreateOffer:_C,shimCreateAnswer:fC,shimGetUserMedia:sC,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 TC(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 EC(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 SC(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 IC(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(vC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function vC(e){return e&&void 0!==e.video?Object.assign({},e,{video:JR(e.video)}):e}function yC(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?(GR("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 AC(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 RC(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 CC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var bC=Object.freeze({__proto__:null,shimLocalStreamsAPI:TC,shimRemoteStreamsAPI:EC,shimCallbacksAPI:SC,shimGetUserMedia:IC,shimConstraints:vC,shimRTCIceServerUrls:yC,shimTrackEventTransceiver:AC,shimCreateOfferLegacy:RC,shimAudioContext:CC}),kC={},NC={get exports(){return kC},set exports(e){kC=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}(NC);var DC=kC,wC=e({__proto__:null,default:DC},[kC]);function OC(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=DC.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,FR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function PC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||FR(e,"icecandidate",(e=>{if(e.candidate){const t=DC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function MC(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=DC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=DC.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=DC.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 LC(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},FR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function xC(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 VC(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 UC(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 FC(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 BC=Object.freeze({__proto__:null,shimRTCIceCandidate:OC,shimRTCIceCandidateRelayProtocol:PC,shimMaxMessageSize:MC,shimSendThrowTypeError:LC,shimConnectionState:xC,removeExtmapAllowMixed:VC,shimAddIceCandidateNullOrEmpty:UC,shimParameterlessSetLocalDescription:FC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=jR,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=UR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=UR(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=UR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:BC,extractVersion:UR,disableLog:BR,disableWarnings:HR,sdp:wC};switch(r.browser){case"chrome":if(!oC||!rC||!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=oC,UC(e,r),FC(e),YR(e,r),QR(e),rC(e,r),XR(e),iC(e,r),$R(e),ZR(e),eC(e),nC(e,r),OC(e),PC(e),xC(e),MC(e,r),LC(e),VC(e,r);break;case"firefox":if(!gC||!cC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=gC,UC(e,r),FC(e),sC(e,r),cC(e,r),aC(e),uC(e),lC(e),dC(e),hC(e),pC(e),mC(e),_C(e),fC(e),OC(e),xC(e),MC(e,r),LC(e);break;case"safari":if(!bC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=bC,UC(e,r),FC(e),yC(e),RC(e),SC(e),TC(e),EC(e),AC(e),IC(e),CC(e),OC(e),PC(e),MC(e,r),LC(e),VC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var HC,jC=Object.create,GC=Object.defineProperty,WC=Object.defineProperties,JC=Object.getOwnPropertyDescriptor,zC=Object.getOwnPropertyDescriptors,KC=Object.getOwnPropertyNames,qC=Object.getOwnPropertySymbols,YC=Object.getPrototypeOf,QC=Object.prototype.hasOwnProperty,XC=Object.prototype.propertyIsEnumerable,$C=Reflect.get,ZC=Math.pow,eb=(e,t,i)=>t in e?GC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,tb=(e,t)=>{for(var i in t||(t={}))QC.call(t,i)&&eb(e,i,t[i]);if(qC)for(var i of qC(t))XC.call(t,i)&&eb(e,i,t[i]);return e},ib=(e,t)=>WC(e,zC(t)),rb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),nb=(e,t)=>{for(var i in t)GC(e,i,{get:t[i],enumerable:!0})},ob=(e,t,i)=>(i=null!=e?jC(YC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of KC(t))!QC.call(e,n)&&n!==i&&GC(e,n,{get:()=>t[n],enumerable:!(r=JC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:GC(i,"default",{value:e,enumerable:!0}),e)),sb=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?JC(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&&GC(t,i,o),o},ab=(e,t,i)=>(eb(e,"symbol"!=typeof t?t+"":t,i),i),cb=(e,t,i)=>$C(YC(e),i,t),lb=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(t){n(t)}},s=e=>{try{a(i.throw(e))}catch(t){n(t)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),db=rb(((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)})),ub=rb(((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")}))}))})),hb=rb((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=ub(),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}}))}))}})),pb=rb(((e,t)=>{var i=ub(),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"}})),mb=rb((e=>{var t=hb(),i=pb();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})),_b=rb(((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")}))}))})),fb=rb((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=_b(),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}}))}))}})),gb=rb(((e,t)=>{var i=_b(),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"}})),Tb=rb((e=>{var t=fb(),i=gb();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})),Eb=ob(db()),Sb=((HC=Sb||{})[HC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",HC[HC.INVALID_OPERATION=4097]="INVALID_OPERATION",HC[HC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",HC[HC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",HC[HC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",HC[HC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",HC[HC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",HC[HC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",HC[HC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",HC[HC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",HC[HC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",HC[HC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",HC[HC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",HC[HC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",HC[HC.CLIENT_BANNED=16448]="CLIENT_BANNED",HC[HC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",HC[HC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",HC[HC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",HC[HC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",HC[HC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",HC[HC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",HC[HC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",HC[HC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",HC[HC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",HC[HC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",HC[HC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",HC[HC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",HC[HC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",HC[HC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",HC[HC.UNKNOWN=65535]="UNKNOWN",HC),Ib=Sb,vb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Ib.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in Ib)if(Ib[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),ab(this,"code"),ab(this,"extraCode"),ab(this,"message"),ab(this,"originMessage"),ab(this,"name"),ab(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}},yb=vb,Ab=((new Date).getTime(),0),Rb=function(){return(new Date).getTime()+Ab},Cb=function(){let e=new Date;return e.setTime(Rb()),e.toLocaleString()},bb={};nb(bb,{bytes2ms:()=>Rw,convertObjectNumberToInt:()=>_O,copyProperties:()=>Aw,deepClone:()=>nO,deepMerge:()=>rO,fibonacci:()=>Ow,formatedTime:()=>cO,getAbilityConfigUrl:()=>hw,getConstructorName:()=>zw,getContainerFromElement:()=>sO,getEnv:()=>fw,getInternalVersion:()=>Xw,getLoggerUrl:()=>Tw,getMuteStateFromFlag:()=>eO,getNetworkType:()=>Sw,getNumNetworkType:()=>yw,getReconnectionTimeout:()=>Pw,getStringByteLength:()=>uO,getTurnServer:()=>tO,getUint32Version:()=>mO,getValueType:()=>Mw,getViewListFromView:()=>oO,glog:()=>Nw,ipv4ToUint32:()=>iO,isArray:()=>Hw,isAudioWorkletSupported:()=>Kw,isBoolean:()=>Fw,isConstructor:()=>Jw,isEmpty:()=>Zw,isFunction:()=>Lw,isLangChinese:()=>Dw,isMediaStreamTrack:()=>jw,isNumber:()=>Uw,isObject:()=>Bw,isOverseaSdkAppId:()=>gw,isPlainObject:()=>ww,isPortrait:()=>hO,isPromise:()=>Ww,isRemoteTrack:()=>Gw,isString:()=>Vw,isUndefined:()=>xw,loadImage:()=>pO,ms2bytes:()=>bw,ms2samples:()=>kw,performanceNow:()=>Yw,promiseAny:()=>qw,samples2ms:()=>Cw,setNetworkType:()=>vw,stringify:()=>lO,stringifyIncludeValue:()=>dO});var kb={};nb(kb,{AUDIO_MUTE_BIT:()=>mk,AUDIO_STAT_BIT:()=>pk,AUX_STAT_BIT:()=>hk,AUX_STREAM_MSID:()=>gk,BACKEND_ENV:()=>ck,BASE_DOC_URL:()=>Wb,BASE_HOST:()=>Bb,CAPABILITIES_KEYS:()=>cN,CLASS_NAME:()=>Yk,CLOUD_CONSOLE_URL:()=>Gb,DATA_FREEZE_TIMING:()=>jk,DOC_URL:()=>Jb,DTLS_STATE_UNKNOWN:()=>bk,ENV_NAME:()=>Qb,EXCHANGE_SDP_TIMEOUT:()=>Vk,INTERVAL:()=>sN,IS_WORKER:()=>Lb,IS_WORKLET:()=>xb,KIBANA_EVENT:()=>Mk,LOCAL_STREAM_PUBLISH_STATE:()=>Hk,LOGGER_CMD_TYPE:()=>Yb,LOGGER_DOMAIN:()=>zb,LOGGER_DOMAIN_OVERSEA:()=>Kb,LOG_LEVEL:()=>Xb,LOG_LEVEL_NAME:()=>eN,MAIN_STREAM_MSID:()=>fk,MICROPHONE_COMMUNICATIONS:()=>Zk,MICROPHONE_DEFAULT:()=>Xk,NAME:()=>sk,NETWORK_TYPE:()=>ek,NOT_SUPPORTED_H264:()=>Bk,PAUSED_RETRY_COUNT:()=>Qk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>zk,PEER_CONNECTION_STATE:()=>kk,PEER_LEAVE_REASON:()=>tN,RAF:()=>oN,RECOVER_CAPTURE_INTERVAL:()=>rN,REMOTE_STREAM_TYPE_AUX:()=>Ek,REMOTE_STREAM_TYPE_MAIN:()=>Tk,RENDER_FREEZE_TIMING:()=>Gk,RIC:()=>nN,SCHEDULE_DOMAIN:()=>Kk,SCHEDULE_TIMEOUT:()=>qk,SDP_SEMANTICS_PLAN_B:()=>Fk,SDP_SEMANTICS_UNIFIED_PLAN:()=>Uk,SECOND_HOST:()=>Hb,SIGNAL_PING_PONG_INTERVAL:()=>Zb,SIGNAL_PING_TIMEOUT:()=>$b,SIGNAL_RECONNECTION_COUNT:()=>Pk,SMALL_STAT_BIT:()=>uk,SPEAKER_DEFAULT:()=>$k,STORAGE_EXPIRES_TIME:()=>tk,STREAM_TYPE_BIG:()=>Wk,STREAM_TYPE_SMALL:()=>Jk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>iN,SYNC_USER_LIST_INTERVAL:()=>Lk,Scene:()=>lk,Switch:()=>ik,THIRD_HOST:()=>jb,TIMEOUT:()=>aN,TRANSPORT_DIRECTION:()=>ak,TRTC_ERROR_ASSISTANCE:()=>qb,TRTC_QUALITY_BAD:()=>Ak,TRTC_QUALITY_DISCONNECTED:()=>Ck,TRTC_QUALITY_EXCELLENT:()=>Ik,TRTC_QUALITY_GOOD:()=>vk,TRTC_QUALITY_POOR:()=>yk,TRTC_QUALITY_UNKNOWN:()=>Sk,TRTC_QUALITY_VERY_BAD:()=>Rk,UPDATE_OFFER_TIMEOUT:()=>xk,VIDEO_MUTE_BIT:()=>_k,VIDEO_STAT_BIT:()=>dk,audioProfileMap:()=>rk,getRetryCount:()=>wk,getScriptDir:()=>Vb,innerVersion:()=>Nb,loggerProxy:()=>Ub,screenProfileMap:()=>ok,setLoggerProxy:()=>Fb,setRetryCount:()=>Dk,setVersion:()=>wb,version:()=>Db,videoProfileMap:()=>nk});var Nb="4.15.00.1600",Db="5.0.0";function wb(e){Db=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));Nb="".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 Ob,Pb,Mb,Lb="undefined"!=typeof importScripts,xb="undefined"!=typeof registerProcessor,Vb=()=>{let e=Lb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Ub="",Fb=e=>Ub=e,Bb="web.sdk.qcloud.com",Hb="web.sdk.tencent.cn",jb="web.sdk.cloud.tencent.cn",Gb="https://console.cloud.tencent.com/trtc",Wb="https://".concat(Bb,"/trtc/webrtc/v5/doc"),Jb="".concat(Wb,"/zh-cn/"),zb="https://yun.tim.qq.com",Kb="https://apisgp.my-imcloud.com",qb="trtc_error_assistance",Yb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Qb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xb=((Mb=Xb||{})[Mb.TRACE=0]="TRACE",Mb[Mb.DEBUG=1]="DEBUG",Mb[Mb.INFO=2]="INFO",Mb[Mb.WARN=3]="WARN",Mb[Mb.ERROR=4]="ERROR",Mb[Mb.NONE=5]="NONE",Mb),$b=18e3,Zb=2e3,ek={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},tk=6048e5,ik=((Pb=ik||{}).USEAINS="useAINS",Pb.ENABLEDEBUG="enableDebug",Pb.USEV2="useV2",Pb.USEWT="useWt",Pb),rk={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}},nk={"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}},ok={"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}},sk={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"},ak={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ck={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},lk=((Ob=lk||{}).LIVE="live",Ob.RTC="rtc",Ob),dk=1,uk=2,hk=4,pk=8,mk=64,_k=16,fk="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",gk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Tk=sk.MAIN,Ek=sk.AUXILIARY,Sk=0,Ik=1,vk=2,yk=3,Ak=4,Rk=5,Ck=6,bk="unknown",kk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Nk=1/0;function Dk(e){Nk=e}function wk(){return Nk}var Ok,Pk=30,Mk={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"},Lk=1e4,xk=1e4,Vk=1e4,Uk="unified-plan",Fk="plan-b",Bk=1028,Hk=((Ok=Hk||{})[Ok.UNPUBLISH=-1]="UNPUBLISH",Ok[Ok.PUBLISHING=0]="PUBLISHING",Ok[Ok.PUBLISHED=1]="PUBLISHED",Ok),jk=500,Gk=1e3,Wk=sk.BIG,Jk=sk.SMALL,zk=1e4,Kk={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},qk=2e3,Yk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Qk=5,Xk="default",$k=Xk,Zk="communications",eN=Object.keys(Xb),tN=["normal leave","timeout leave","kick","role change"],iN=10,rN=2e3,nN="ric",oN="raf",sN="interval",aN="timeout",cN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function lN(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 dN(e){return lb(this,null,(function*(){let t=Yw(),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 IO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(Yw()-t,"ms")),r}catch(Ok){return i}}))}var uN=1e8,hN={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"},pN={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(Mw(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(Mw(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=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_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,"()")},mN={};nb(mN,{ANDROID_VERSION:()=>bN,CHROME_MAJOR_VERSION:()=>kD,CHROME_VERSION:()=>ND,EDGE_VERSION:()=>MN,EDG_MAJOR_VERSION:()=>VN,EDG_VERSION:()=>xN,FIREFOX_MAJOR_VERSION:()=>ON,FIREFOX_VERSION:()=>wN,HUAWEI_VERSION:()=>gD,IE_VERSION:()=>qN,IOS_MAIN_VERSION:()=>LD,IOS_VERSION:()=>MD,IPADQQB_VERSION:()=>oD,IS_ANDROID:()=>CN,IS_ANDROID_WEBVIEW:()=>PD,IS_ANY_SAFARI:()=>wD,IS_CHROME:()=>CD,IS_CHROME_OS:()=>lD,IS_CHROMIUM_BASE:()=>RD,IS_EDG:()=>LN,IS_EDGE:()=>PN,IS_ELECTRON:()=>hD,IS_FIREFOX:()=>DN,IS_HEADLESS_CHROME:()=>bD,IS_HUAWEI:()=>fD,IS_HUAWEIBROWSER:()=>_D,IS_IE:()=>KN,IS_IE8:()=>zN,IS_IOS:()=>RN,IS_IOS_13_OR_14:()=>UD,IS_IOS_15_1:()=>VD,IS_IPAD:()=>IN,IS_IPADQQB:()=>nD,IS_IPAD_PRO:()=>vN,IS_IPHONE:()=>yN,IS_IPOD:()=>AN,IS_LINUX:()=>cD,IS_LOCAL:()=>FD,IS_MAC:()=>aD,IS_MACQQB:()=>iD,IS_MIBROWSER:()=>pD,IS_MQQB:()=>$N,IS_NATIVE_ANDROID:()=>NN,IS_OLD_ANDROID:()=>kN,IS_OPPOBROWSER:()=>SD,IS_SAFARI:()=>DD,IS_SAFARI_15_1:()=>xD,IS_SAMSUNGBROWSER:()=>TD,IS_SOGOU:()=>BN,IS_SOGOUM:()=>UN,IS_TBS:()=>jN,IS_UCBROWSER:()=>uD,IS_VIVOBROWSER:()=>vD,IS_WECHAT:()=>YN,IS_WIN:()=>sD,IS_WQQB:()=>eD,IS_WX:()=>dD,IS_X5MQQB:()=>XN,IS_XWEB:()=>WN,MACQQB_VERSION:()=>rD,MI_VERSION:()=>mD,MQQB_VERSION:()=>ZN,OPPO_VERSION:()=>ID,SAFARI_VERSION:()=>OD,SAMSUNG_VERSION:()=>ED,SOGOUM_VERSION:()=>FN,SOGOU_VERSION:()=>HN,TBS_VERSION:()=>GN,USER_AGENT:()=>_N,VIVO_VERSION:()=>yD,WECHAT_VERSION:()=>QN,WQQB_VERSION:()=>tD,XWEB_VERSION:()=>JN,browserInfo:()=>HD,getBrowserInfo:()=>jD,getChromeMajorVersion:()=>AD,getDeviceModel:()=>JD,getOSName:()=>KD,getOSString:()=>qD,getOSType:()=>QD,getTerminalType:()=>YD,getUserAgentData:()=>WD,isLocalStorageEnabled:()=>BD});var _N="undefined"==typeof navigator?"":navigator.userAgent,fN=e=>new RegExp(e,"i").test(_N),gN=e=>{if(fN(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=_N.match(t);if(i&&i[1])return i[1]}return""},TN=e=>{if(fN(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=_N.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},EN=/AppleWebKit\/([\d.]+)/i.exec(_N),SN=EN?parseFloat(EN[1]):NaN,IN=fN("iPad"),vN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&fN("Macintosh"),yN=fN("iPhone")&&!IN,AN=fN("iPod"),RN=yN||IN||AN||vN,CN=fN("Android"),bN=function(){if(CN){let e=_N.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}(),kN=CN&&fN("webkit")&&bN<2.3,NN=CN&&bN<5&&SN<537,DN=fN("Firefox"),wN=gN("Firefox"),ON=TN("Firefox"),PN=fN("Edge"),MN=gN("Edge"),LN=fN("Edg"),xN=gN("Edg"),VN=TN("Edg"),UN=fN("SogouMobileBrowser"),FN=gN("SogouMobileBrowser"),BN=fN("MetaSr\\s"),HN=gN("MetaSr\\s"),jN=fN("TBS"),GN=gN("TBS"),WN=fN("XWEB"),JN=gN("XWEB"),zN=fN("MSIE\\s8\\.0"),KN=fN("MSIE\\/\\d+"),qN=function(){if(KN){let e=/MSIE\s(\d+)\.\d/.exec(_N),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(_N)&&/rv:11.0/.test(_N)&&(t=11),t}return NaN}(),YN=fN("(micromessenger|webbrowser)"),QN=gN("MicroMessenger"),XN=!jN&&fN("MQQBrowser")&&fN("COVC"),$N=!jN&&fN("MQQBrowser")&&!fN("COVC"),ZN=$N||XN?gN("MQQBrowser"):"",eD=!jN&&fN(" QQBrowser"),tD=gN(" QQBrowser"),iD=!jN&&fN("QQBrowserLite"),rD=gN("QQBrowserLite"),nD=!jN&&fN("MQBHD"),oD=gN("MQBHD"),sD=fN("Windows"),aD=!RN&&fN("MAC OS X"),cD=!CN&&fN("Linux"),lD=fN("CrOS"),dD=fN("MicroMessenger"),uD=fN("UCBrowser"),hD=fN("Electron"),pD=fN("MiuiBrowser"),mD=gN("MiuiBrowser"),_D=fN("HuaweiBrowser"),fD=fN("Huawei"),gD=gN("HuaweiBrowser"),TD=fN("SamsungBrowser"),ED=gN("SamsungBrowser"),SD=fN("HeyTapBrowser"),ID=gN("HeyTapBrowser"),vD=fN("VivoBrowser"),yD=gN("VivoBrowser"),AD=()=>TN("Chrome"),RD=fN("Chrome"),CD=!PN&&!BN&&!UN&&!jN&&!WN&&!LN&&!eD&&!pD&&!_D&&!TD&&!SD&&!vD&&RD,bD=fN("HeadlessChrome"),kD=AD(),ND=gN("Chrome"),DD=!RD&&!$N&&!XN&&!iD&&!nD&&fN("Safari"),wD=DD||RN,OD=gN("Version"),PD=/Android.*(wv|.0.0.0)/.test(_N),MD=(()=>{if(vN)return OD;if(RN){let e=_N.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),LD=Number(MD.split(".")[0]),xD="15.1"===OD,VD="15.1"===MD,UD=(()=>{let e=Number(MD.split(".")[0]);return 14===e||13===e})(),FD="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),BD=(()=>{let e;return()=>{if(xw(e))try{e=!!window.localStorage}catch(oM){e=!1}return e}})(),HD=jD();function jD(){let e=new Map([[DN,["Firefox",wN]],[LN,["Edg",xN]],[CD,["Chrome",ND]],[DD,["Safari",OD]],[jN,["TBS",GN]],[WN,["XWEB",JN]],[YN&&yN,["WeChat",QN]],[eD,["QQ(Win)",tD]],[$N,["QQ(Mobile)",ZN]],[XN,["QQ(Mobile X5)",ZN]],[iD,["QQ(Mac)",rD]],[nD,["QQ(iPad)",oD]],[pD,["MI",mD]],[_D,["HW",gD]],[TD,["Samsung",ED]],[SD,["OPPO",ID]],[vD,["VIVO",yD]],[PN,["EDGE",MN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var GD=null;function WD(){return lb(this,null,(function*(){if(GD)return GD;if(!navigator.userAgentData||!Lw(navigator.userAgentData.getHighEntropyValues))return null;try{return GD=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(EF){return null}}))}function JD(){return(null==GD?void 0:GD.model)||""}var zD=new Map([[CN,"Android"],[RN,"iOS"],[sD,"Windows"],[aD,"MacOS"],[cD,"Linux"],[lD,"ChromeOS"]]),KD=function(){return zD.get(!0)?zD.get(!0):GD?GD.platform:"unknown"},qD=()=>{let e=KD();return e+="/".concat(HD.name,"/").concat(DD?HD.version:HD.version.split(".")[0]),null!=GD&&GD.platformVersion&&(e+="/".concat(GD.platformVersion)),null!=GD&&GD.architecture&&(e+="/".concat(GD.architecture)),e};function YD(){return CN?4:yN?2:IN?3:aD?12:sD?5:cD?13:1}function QD(){return CN?"Android":yN?"iPhone":IN?"iPad":aD?"Mac":sD?"Windows":cD?"Linux":"unknown"}var XD=(e,t)=>t?"".concat(Wb,"/").concat(e,"/").concat(t):"".concat(Wb,"/").concat(e,"/index.html"),$D=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(qb);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 ZD(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";Lw(pN[t])?o=pN[t](i):Vw(pN[t])&&(o=pN[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=$D();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(Lw(l[t])?a=l[t](i):Vw(l[t])&&(a=l[t]));let d=o;return Dw()&&(c&&c[t]&&(Lw(c[t])?s=c[t](i):Vw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(XD("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(XD("en",a),"\n")),d}var ew,tw=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)=>lb(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<(Lw(d)?d():d)?(h++,m=1,Lw(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),Lw(u)?u(h):u)):(t(),Lw(o)&&o.call(this,f))};Lw(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},iw=new(ob(db(),1).default),rw=((ew=rw||{}).ROOM_DESTROY="1",ew.JOIN_START="21",ew.JOIN_SCHEDULE_SUCCESS="22",ew.JOIN_SIGNAL_CONNECTION_START="23",ew.JOIN_SIGNAL_CONNECTION_END="24",ew.JOIN_SEND_CMD="25",ew.JOIN_RECEIVED_CMD_RES="26",ew.JOIN_SUCCESS="27",ew.JOIN_FAILED="28",ew.LEAVE_START="51",ew.LEAVE_SEND_CMD="52",ew.LEAVE_SUCCESS="53",ew.PUBLISH_START="61",ew.SEND_FIRST_VIDEO_FRAME="62",ew.PUBLISH_FAILED="63",ew.SUBSCRIBE_START="81",ew.SUBSCRIBE_SUCCESS="82",ew.SUBSCRIBE_FAILED="84",ew.UNSUBSCRIBE_SUCCESS="83",ew.LOCAL_TRACK_CAPTURE_START="101",ew.LOCAL_TRACK_CAPTURE_SUCCESS="102",ew.LOCAL_TRACK_CAPTURE_FAILED="103",ew.LOCAL_TRACK_PUBLISHED="104",ew.LOCAL_TRACK_UNPUBLISHED="105",ew.LOCAL_TRACK_REPLACED="106",ew.SWITCH_DEVICE_SUCCESS="107",ew.TRACK_MUTED="108",ew.TRACK_UNMUTED="109",ew.REMOTE_TRACK_SUBSCRIBED="110",ew.REMOTE_TRACK_UNSUBSCRIBED="111",ew.PLAY_TRACK_START="151",ew.PLAYER_STATE_CHANGED="152",ew.VIDEO_LOADED_DATA="153",ew.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",ew.SIGNAL_CONNECTION_STATE_CHANGED="201",ew.PEER_CONNECTION_STATE_CHANGED="202",ew.SINGLE_CONNECTION_STAT="203",ew.SPC_RECONNECTED="204",ew.HEARTBEAT_REPORT="251",ew.RECEIVED_PUBLISHED_USER_LIST="252",ew.REMOTE_PUBLISH_STATE_CHANGED="253",ew.AUDIO_LEVEL_INTERVAL="260",ew.NETWORK_QUALITY="261",ew),nw=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Db,env:Qb.QCLOUD,browserVersion:HD.name+HD.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){FD||!IO.isAbleToUpload||this._configs.env===Qb.QCLOUD&&this.uploadEventToKibana(ib(tb({},e),{result:"success"}))}logFailedEvent(e){if(FD||!IO.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)||Ib.UNKNOWN};this._configs.env===Qb.QCLOUD&&this.uploadEventToKibana(ib(tb({},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:Cb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Db,log:t};r&&(n.errorInfo=r.message),this.sendRequest(Tw(this._configs.sdkAppId,Yb.LOG),n)}sendRequest(e,t){IO.isAbleToUpload?lN({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},ow=null,sw=!0;function aw(e){Fw(e)&&e!==sw&&(sw=e,IO.info("setIsNeedToSchedule ".concat(e)))}function cw(e){return lb(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(!sw&&ow)return{isCached:!0,result:ow};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=Yw(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;qw([_w((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=2&&(a[0]=uw(i,sk.MAIN,!0)),n())}))(uw(i,sk.MAIN),e,{get timeout(){return 1e3*Ow(2+t.count[0])}}),_w((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]=uw(i,sk.BACKUP,!0)),n())}))(uw(i,sk.BACKUP),e,{get timeout(){return 1e3*Ow(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Fb(h.config.loggerDomain),Fw(h.config.scheduleCache)&&aw(!h.config.scheduleCache)),e.delta=Yw()-u;let p=function(e,t,i){let r=performance.getEntriesByType("resource"),n=uw(e,sk.MAIN),o=uw(e,sk.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of r)if(a.startTime>=i&&(a.name===n||a.name===o)&&a.transferSize>0){let e=a.name===n?sk.MAIN:sk.BACKUP,i=Math.round(a.duration),r=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[r,o,c,l,d,u];nw.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=ib(tb({},s),{totalCost:i,local:r,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,u);return ow=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=Hw(d)?d[0]:d,t=Uw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new yb({code:Ib.SCHEDULE_FAILED,extraCode:t,message:ZD({key:hN.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw IO.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")),iw.on("28",(()=>aw(!0))),iw.on("63",(()=>aw(!0))),iw.on("84",(()=>aw(!0))),iw.on("201",(e=>{"RECONNECTING"===e.state&&aw(!0)})),iw.on("202",(e=>{"RECONNECTING"===e.state&&aw(!0)}));var lw={main:"",backup:""};function dw(e){Hw(e)?(lw.main=e[0],lw.backup=e[1]):lw.main=e}function uw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(lw[t]||pw(e,t,i),"/api/v1/config")}function hw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk.MAIN;return"https://".concat(lw[t]||pw(e,t),"/api/v1/trtcAutoConf")}function pw(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sk.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return gw(e)?i===sk.MAIN?Kk.MAIN_OVERSEA:Kk.BACKUP_OVERSEA:(t=gw(e)?r?i===sk.MAIN?Kk.MAIN_OVERSEA_OLD:Kk.BACKUP_OVERSEA_OLD:i===sk.MAIN?Kk.MAIN_OVERSEA:Kk.BACKUP_OVERSEA:i===sk.MAIN?Kk.MAIN:Kk.BACKUP,t)}function mw(e,t,i){return new Promise(((r,n)=>{lN({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 _w=(e,t)=>tw({retryFunction:mw,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var fw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},gw=e=>Number(e)<14e8,Tw=function(e,t){let i;i=Ub||(gw(e)?Kb:zb);let r=Math.floor(Math.random()*ZC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},Ew="unknown";function Sw(){if("unknown"!==Ew)return Ew;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&&(Ew=Iw(r,n)),Ew}function Iw(e,t){if(ek[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function vw(e){Ew=Iw(e)}function yw(){return ek[Sw()]}function Aw(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 Rw(e){return Cw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Cw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function bw(e){return 4*kw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function kw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var Nw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},Dw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},ww=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 Ow(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:Ow(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function Pw(e){return e>8?3e4:1e3*Ow(e)}function Mw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Lw=e=>"function"==typeof e,xw=e=>void 0===e,Vw=e=>"string"==typeof e,Uw=e=>"number"==typeof e,Fw=e=>"boolean"==typeof e,Bw=e=>"object"===Mw(e),Hw=e=>"array"===Mw(e),jw=e=>Mw(e)==="MediaStreamTrack".toLowerCase(),Gw=e=>e.isRemote,Ww=e=>"promise"===Mw(e),Jw=e=>Lw(e)&&e.prototype.constructor===e,zw=e=>Jw(e)?e.prototype.constructor.name:"",Kw="undefined"!=typeof AudioWorkletNode;function qw(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 Yw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Qw=e=>+e<10?"0".concat(e):e,Xw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Qw(i[1])+Qw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},$w=Object.prototype.hasOwnProperty;function Zw(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(ww(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($w.call(e,t))return!1;return!0}return!1}function eO(e,t){return{userId:t,hasAudio:!!(e&pk),hasVideo:!!(e&dk),hasAuxiliary:!!(e&hk),hasSmall:!!(e&uk),audioMuted:!!(e&mk),videoMuted:!!(e&_k),audioAvailable:!(!(e&pk)||e&mk),videoAvailable:!(!(e&dk)||e&_k)}}function tO(e){let t={urls:"turn:".concat(e.url)};return!xw(e.username)&&!xw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",xw(e.credentialType)||(t.credentialType=e.credentialType)),t}function iO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Vw(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 rO=function(e,t,i,r){if(!Bw(e)||!Bw(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],!(xw(t[n])||i&&i.includes(n)))if(Bw(e[n])&&Bw(t[n]))o+=rO(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=nO(t[n]),o+=1)}return o};function nO(e){if(Hw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=nO(e)})),t}if(Bw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=nO(e[i])})),t}return e}var oO=e=>{let t=[];if(Hw(e))t=[...e];else if(Vw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},sO=e=>Vw(e)?document.getElementById(e):e,aO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),cO=()=>aO.format(new Date);function lO(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Hw(e))return"[".concat(e.map((e=>lO(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!ww(e)||!Hw(i)&&!Hw(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]=ww(e[s])||Hw(e[s])?JSON.parse(lO(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(Ok){return"{}"}}function dO(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)})),lO(e,{keysToInclude:i})}function uO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var hO=()=>{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},pO=e=>lb(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(Vw(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}))})),mO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},_O=e=>(Object.keys(e).forEach((t=>{Uw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(ww(e[t])||Hw(e[t]))&&_O(e[t])})),e),fO=Object.prototype.hasOwnProperty;function gO(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(fO.call(e,t))return!1;return!0}return!1}var TO=class{constructor(e){ab(this,"userId"),ab(this,"remoteUserId"),ab(this,"id"),ab(this,"sdkAppId"),ab(this,"type"),ab(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):"","]")),IO.log(e,t,void 0===this.userId||gO(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)}},EO=rw,SO=!(RN||CN||bD),IO=new class{constructor(){ab(this,"_isEnableUploadLog",!0),ab(this,"_localJoinedUser",new Map),ab(this,"_queue",[]),ab(this,"_timeoutId",-1),ab(this,"_logLevel",1),ab(this,"_logLevelToUpload",2),!Lb&&!xb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){iw.on(EO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&Xb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),iw.on(EO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),iw.once(EO.JOIN_FAILED,(()=>{this.startUpload()})),iw.on(EO.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(Vw(i.userId)&&Uw(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 lb(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:Cb(),sdkAppId:String(r),userId:i,version:Db,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(Pb){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return tw({retryFunction:()=>lN({url:Tw(t,Yb.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(Rb());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(Xb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){xw(Xb[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(Vw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(Ob){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;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=Xb[e])?void 0:o.toLowerCase())||"info";SO?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[s](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new TO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Xb[t]&&(this._logLevelToUpload=t)}},vO=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)}))},yO=new class{constructor(){ab(this,"_prefix","TRTC"),ab(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){BD()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(BD())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(oM){IO.warn(oM)}}getItem(e){if(!BD())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(Ob){IO.warn(Ob)}}setItem(e,t){if(BD())try{let i={expiresIn:Date.now()+tk,value:t};this._queue.set(this.getRealKey(e),i)}catch(Ok){IO.warn(Ok)}}deleteItem(e){if(!BD())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(Ob){return IO.warn(Ob),!1}}clear(){if(BD())try{localStorage.clear()}catch(oM){IO.warn(oM)}}},AO={};nb(AO,{HTTPS_API:()=>BO,IS_GET_CAPABILITIES_SUPPORTED:()=>rP,IS_GET_SETTINGS_SUPPORTED:()=>iP,IS_SEI_SUPPORTED:()=>nP,IS_SPC_SUPPORTED:()=>$O,basis:()=>lP,checkSystemRequirementsInternal:()=>VO,decodeSupportStatus:()=>xO,encodeSupportStatus:()=>LO,getBrowserInfo:()=>kO,getDisplayResolution:()=>jO,isAddTransceiverSupported:()=>XO,isBrowserSupported:()=>NO,isGetReceiversSupported:()=>qO,isGetSendersSupported:()=>YO,isGetTransceiversSupported:()=>QO,isGetUserMediaSupported:()=>GO,isMediaDevicesSupported:()=>wO,isMediaSessionSupported:()=>aP,isMediaStreamTrackProcessorSupported:()=>MO,isReplaceTrackSupported:()=>eP,isScreenCaptureApiAvailable:()=>FO,isSelectedCandidatePair:()=>HO,isSetParametersSupported:()=>tP,isSmallStreamAPISupported:()=>JO,isSmallStreamSupported:()=>zO,isStopTransceiverSupported:()=>ZO,isTRTCSupported:()=>UO,isUnifiedPlanDefault:()=>KO,isUsedInHttpProtocol:()=>PO,isWebAudioSupported:()=>WO,isWebCodecSupported:()=>sP,isWebCodecsSupported:()=>DO,isWebRTCSupported:()=>oP,isWebTransportSupported:()=>cP});var RO=ob(mb(),1),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([[DN,["Firefox",wN]],[LN,["Edg",xN]],[CD,["Chrome",ND]],[DD,["Safari",OD]],[jN,["TBS",GN]],[WN,["XWEB",JN]],[YN&&yN,["WeChat",QN]],[eD,["QQ(Win)",tD]],[$N,["QQ(Mobile)",ZN]],[XN,["QQ(Mobile X5)",ZN]],[iD,["QQ(Mac)",rD]],[nD,["QQ(iPad)",oD]],[pD,["MI",mD]],[_D,["HW",gD]],[TD,["Samsung",ED]],[SD,["OPPO",ID]],[vD,["VIVO",yD]],[PN,["EDGE",MN]],[UN,["SogouMobile",FN]],[BN,["Sogou",HN]]]);function kO(){let e=bO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var NO=function(){return!(uD||PN||LN&&VN<80||DN&&ON<56)},DO=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},wO=function(){if(!navigator.mediaDevices)return PO()||IO.error(pN.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&&!FD&&(OO||IO.error(ZD({key:hN.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 lb(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(sk.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(Ok){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},xO=function(){return lb(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(Ok){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},VO=function(){return lb(this,null,(function*(){if(CO.result&&CO.detail.isH264EncodeSupported&&CO.detail.isVp8EncodeSupported&&CO.detail.isH264DecodeSupported&&CO.detail.isVp8DecodeSupported)return CO;let e=NO(),t=oP(),i=DO(),r=wO(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield LO(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield xO();if(!n||!o){let e=yield LO();IO.warn("detect encode again h264:".concat(n," vp8:").concat(o," result: ").concat(JSON.stringify(e))),n=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(n&&s&&(SD||vD||PD)&&!jN&&AD()<79){let{encode:e,decode:t}=yield function(){return lb(this,null,(function*(){return new Promise((e=>lb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{IO.warn("start detect h264 supported by encoding and decoding canvas stream");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=640,r.height=480;let o=setInterval((()=>{n.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),3e3);let c=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=RO.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=RO.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>lb(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getStats(),n=yield d.getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===sk.VIDEO&&e.framesEncoded>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===sk.VIDEO&&e.framesDecoded>0&&(t.decode=!0)}))}))),500)}catch(r){i(),IO.warn(r),e(t)}}))))}))}();n=e,s=t}return CO.result=e&&t&&r&&(n||o)&&(s||a),CO.detail.isBrowserSupported=e,CO.detail.isWebRTCSupported=t,CO.detail.isWebCodecsSupported=i,CO.detail.isMediaDevicesSupported=r,CO.detail.isScreenShareSupported=FO(),CO.detail.isSmallStreamSupported=zO(),CO.detail.isH264EncodeSupported=n,CO.detail.isVp8EncodeSupported=o,CO.detail.isH264DecodeSupported=s,CO.detail.isVp8DecodeSupported=a,CO.result||IO.error("".concat(navigator.userAgent," ").concat(dO(CO.detail,!1))),yO.setItem(dP,{ua:navigator.userAgent,checkResult:CO}),CO}))},UO=function(){return CO.result},FO=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)};var BO=(e,t,i)=>{"http:"===location.protocol&&!FD&&(e[t]=()=>{throw new yb({code:Ib.INVALID_OPERATION,message:pN.NOT_SUPPORTED_HTTP})})},HO=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(Fw(e.selected)&&!e.selected)};function jO(){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 WO(){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 JO(){return"captureStream"in HTMLCanvasElement.prototype}function zO(){return!(YN||RN||kD&&kD<63)&&!(!NO()||!JO())}var KO=function(){if(xw(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Uk}),e.addTransceiver(sk.AUDIO),t=!0}catch(Ob){}return null==e||e.close(),t};function qO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function YO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function QO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function XO(){return 11!==LD&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var $O=!(!XO()||RD&&kD<74);function ZO(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function eP(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function tP(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&YO()}var iP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,rP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,nP="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&AD()>=86,oP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function sP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return xw(window.AudioDecoder)||(e.AudioDecoder=!0),xw(window.AudioEncoder)||(e.AudioEncoder=!0),xw(window.VideoDecoder)||(e.VideoDecoder=!0),xw(window.VideoEncoder)||(e.VideoEncoder=!0),xw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function aP(){return"mediaSession"in navigator&&!xw(navigator.mediaSession.setActionHandler)}function cP(){return!xw(window.WebTransport)}function lP(){let e={browser:"".concat(HD.name,"/").concat(HD.version),os:KD(),displayResolution:jO(),isScreenShareSupported:FO(),isWebRTCSupported:oP(),isGetUserMediaSupported:GO(),isWebAudioSupported:WO(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:sP(),isMediaSessionSupported:aP(),isWebTransportSupported:cP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var dP="checkResult";!function(){PO();let e=yO.getItem(dP);e&&e.ua===navigator.userAgent&&(CO=e.checkResult),VO()}();var uP=ob(db(),1),hP=Symbol("instance"),pP=Symbol("cacheResult"),mP=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,EP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},_P=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var fP=new Map;function gP(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=fP.get(r)||[];fP.has(r)||fP.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=SP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[pP]:Promise.resolve(r[pP]);r.state instanceof mP&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof mP&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new _P(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 _P(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 mP(u,t,s);EP.call(r,h);let p=e=>{var n;return r[pP]=e,h.aborted||(EP.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[pP])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return EP.call(r,u,e),d(new _P(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 TP="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 EP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(SP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var SP=class extends uP.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=SP.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[hP];r?this.name=r.name+"-"+r.count++:i[hP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=fP.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);fP.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=SP.instances.get(e),t||SP.instances.set(e,t=new SP(e,void 0,Object.create(SP.prototype)))):(t=SP.instances2.get(e),t||SP.instances2.set(e,t=new SP(e.constructor.name,void 0,Object.create(SP.prototype)))),t}static getState(e){var t;return null===(t=SP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};TP(SP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){EP.call(this,e)}};SP.STATECHANGED="stateChanged",SP.UPDATEAFSM="updateAFSM",SP.INIT="[*]",SP.ON="on",SP.OFF="off",SP.instances=new Map,SP.instances2=new WeakMap;var IP=(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)},vP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},yP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),AP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:aN,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=tb(e===sN?{delay:2e3,count:0,backgroundTask:!0}:e===nN?{delay:1e4,count:0}:e===oN?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),Bw(t)&&(i=tb(tb({},i),t)),Lw(e)&&(t=e,e=aN);let r=tb({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=Yw(),r=()=>{if(t=Yw()-i,t>=e.delay&&(i=Yw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=IP(r,{timeout:e.delay})};return e.ricID=IP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=Yw(),r=()=>document.hidden&&e.backgroundTask?(t=Yw()-i,i=Yw(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=Yw()-i,t>=e.delay&&(i=Yw()-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=Yw()-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&&yP(r),n&&vP(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)}};AP.taskMap=new Map,AP.currentTaskID=1;var RP=AP;sk.SEI_MESSAGE;var CP={LOADED_DATA:sk.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},bP={};nb(bP,{create:()=>NP,remove:()=>DP});var kP=new WeakMap;function NP(e,t){kP.has(e)||kP.set(e,[]);let i=kP.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 DP(e){let t=kP.get(e);t&&(t.forEach((e=>e())),kP.delete(e))}var wP=class extends SP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,ab(this,"id"),ab(this,"element",null),ab(this,"track"),ab(this,"url"),ab(this,"attr"),ab(this,"muted"),ab(this,"_log"),ab(this,"_pausedRetryCount"),ab(this,"_isElementPlayingFired",!1),ab(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Qk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return lb(this,null,(function*(){if(!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(Ob){let t=ZD({key:hN.PLAY_FAILED,data:{media:this.kind,error:Ob}});if(this.track&&!this.track.muted&&this._log.warn(Ob),t.includes("NotAllowedError"))throw new yb({code:Ib.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.element.remove(),this.element.srcObject=null,this.element=null),this.handleStopped(sk.ENDED),this._interval>0&&RP.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():VD?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 NP(this.element,this.element).add(sk.PLAYING,e).add(sk.ENDED,e).add(sk.PAUSE,e).add(sk.ERROR,e).add(sk.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==bP||bP.create(this.track,this.track).add(sk.ENDED,e).add(sk.MUTE,e).add(sk.UNMUTE,e),this.track.readyState===sk.ENDED&&this.handleTrackEvent({type:sk.ENDED}),this.track.muted&&this.handleTrackEvent({type:sk.MUTE})}}bindAutoPlayEvent(){iw.on(EO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&DP(this.track)}unbindEvents(){this.element&&DP(this.element),this.unbindTrackEvents(),iw.off(EO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case sk.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(sk.PLAYING),this._interval&&(RP.clearTask(this._interval),this._interval=-1);break;case sk.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(sk.ENDED);break;case sk.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(sk.PAUSE),RN&&(this._interval=RP.run(aN,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case sk.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),nw.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Mk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),this.emit(CP.ERROR,this.element.error)}break;case sk.LOADEDDATA:this.kind===sk.VIDEO&&this.emit(CP.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case sk.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(sk.ENDED);break;case sk.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(sk.MUTE);break;case sk.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(sk.UNMUTE)}}handlePlaying(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(CP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};sb([gP([],"PLAYING",{sync:!0})],wP.prototype,"handlePlaying",1),sb([gP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],wP.prototype,"handlePaused",1),sb([gP([],"STOPPED",{sync:!0})],wP.prototype,"handleStopped",1);var OP="trtc_autoplay",PP="".concat(OP,"_mask"),MP="".concat(OP,"_wrapper"),LP="".concat(OP,"_header"),xP="".concat(OP,"_content"),VP="".concat(OP,"_action_wrapper"),UP="".concat(OP,"_question"),FP="".concat(OP,"_collapse"),BP="".concat(OP,"_action_confirm"),HP="".concat(OP,"_detail"),jP="#2473E8",GP="dialog",WP="".concat(GP,"-show"),JP="".concat(GP,"-1"),zP="".concat(GP,"-2"),KP=!1,qP=()=>!!document.querySelector(".".concat(MP)),YP="".concat(Wb,"/").concat(Dw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),QP="<br><a href='".concat(YP,"' target='_blank'>").concat(Dw()?"其他方案?":"Any other solution?","</a>"),XP="".concat(Dw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(QP):"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(QP)),$P=class{constructor(){if(ab(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),ab(this,"_dialogNode",null),ab(this,"_bodyPosition",""),ab(this,"_showDetail",!1),ab(this,"_isCollapseClicked",!1),ab(this,"_isQuestionClicked",!1),Dw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!KP){let e=document.createElement("style");e.innerHTML=".".concat(PP,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(PP," div:not(.").concat(VP,"){display:block !important;}.").concat(MP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(MP," a{color:").concat(jP,";}.").concat(LP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(xP,"{margin:8px 0;}.").concat(VP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(FP,"{margin-right:auto;cursor:pointer}.").concat(UP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(BP,"{margin-left:8px;color:#fff;background:").concat(jP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(BP,":hover{opacity:0.9;}.").concat(FP,",.").concat(BP,",.").concat(xP,",.").concat(UP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(MP,"{width:80vw;}}"),document.head.appendChild(e),KP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(PP,"\"><div class='").concat(MP,"'><div class='").concat(LP,"'>").concat(location.host,"</div><div class='").concat(xP,"'>").concat(this.content,"</div><div class='").concat(HP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(XP,"</div><div class='").concat(VP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=BP,t.innerText=Dw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=UP,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=FP,r.innerText="".concat(Dw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(VP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){qP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(MP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",IO.info("show autoplay dialog"),nw.uploadEvent({log:WP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){IO.warn("confirm clicked, try resume stream"),iw.emit(EO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(HP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||nw.uploadEvent({log:JP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(YP,"_blank"),this._isQuestionClicked||nw.uploadEvent({log:zP}),this._isQuestionClicked=!0}},ZP=class extends wP{constructor(e){super(e,sk.VIDEO),ab(this,"viewMirror",!1),ab(this,"objectFit"),ab(this,"container"),ab(this,"canvas"),this.container=e.container,this.canvas=e.canvas,xw(e.viewMirror)||(this.viewMirror=e.viewMirror),xw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(sk.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(sk.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(sk.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===sk.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&&!qP()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let e=this.element.style.transform;i===sk.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===sk.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}setCanvas(e){var t,i;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&(null==(i=this.container)||i.appendChild(e)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}stop(){var e;super.stop(),null==(e=this.canvas)||e.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(CP.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}};function eM(e,t){return lb(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),IO.info("worklet addModule success")}catch(Ob){throw IO.info("worklet addModule catch error. ".concat(Ob.message)),Ob}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var tM=new window.AudioContext({sampleRate:48e3}),iM=()=>{"suspended"===tM.state?(tM.resume(),document.addEventListener("click",iM)):"interrupted"===tM.state?tM.resume():document.removeEventListener("click",iM)};document.addEventListener("click",iM),tM.onstatechange=()=>{IO.info("context state: ".concat(tM.state)),iM()};var rM,nM,oM,sM=e=>tM,aM=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=IO.createLogger({id:"kv"}),e&&(iw.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===sk.AUDIO?hM.START_MICROPHONE:pM.START_CAMERA,cost:i})})),iw.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===sk.AUDIO?hM.START_MICROPHONE:pM.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:mO(this.version||Db),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(Uw(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=Ib.UNKNOWN;Uw(i)?r=i:(!xw(i.extraCode)||!xw(i.code))&&(r=i.extraCode||i.code),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},cM=((nM=cM||{})[nM.enterRoom=500700]="enterRoom",nM[nM.exitRoom=500701]="exitRoom",nM[nM.switchRole=500702]="switchRole",nM[nM.destroy=500703]="destroy",nM[nM.startLocalAudio=500704]="startLocalAudio",nM[nM.updateLocalAudio=500705]="updateLocalAudio",nM[nM.stopLocalAudio=500706]="stopLocalAudio",nM[nM.startLocalVideo=500707]="startLocalVideo",nM[nM.updateLocalVideo=500708]="updateLocalVideo",nM[nM.stopLocalVideo=500709]="stopLocalVideo",nM[nM.startScreenShare=500710]="startScreenShare",nM[nM.updateScreenShare=500711]="updateScreenShare",nM[nM.stopScreenShare=500712]="stopScreenShare",nM[nM.startRemoteVideo=500713]="startRemoteVideo",nM[nM.updateRemoteVideo=500714]="updateRemoteVideo",nM[nM.stopRemoteVideo=500715]="stopRemoteVideo",nM[nM.muteRemoteAudio=500716]="muteRemoteAudio",nM[nM.setRemoteAudioVolume=500717]="setRemoteAudioVolume",nM[nM.use=500718]="use",nM[nM.sendSEIMessage=5e5]="sendSEIMessage",nM[nM.sendCustomMessage=500001]="sendCustomMessage",nM),lM=((rM=lM||{})[rM.AudioMixer=550700]="AudioMixer",rM[rM.AIDenoiser=551700]="AIDenoiser",rM[rM.VirtualBackground=570700]="VirtualBackground",rM[rM.Beauty=571700]="Beauty",rM[rM.Watermark=572700]="Watermark",rM),dM=(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))(dM||{}),uM=(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))(uM||{}),hM=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(hM||{}),pM=((oM=pM||{})[oM.START_CAMERA=511700]="START_CAMERA",oM),mM=new aM(!0),_M=new aM(!1),fM=mM,gM=class{constructor(){this.pre=new Set,this.next=new Set,this.connectedNodes=new Set}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}setNode(e){var t;if(!this.node)try{null==(t=this.context)||t.addMixWeight(),this.node=e,this.preNodeReconnect(),this.reconnect(),fM.addSuccessEvent({key:502701})}catch(Ok){IO.error(Ok),fM.addFailedEvent({key:502701,error:Ok})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),fM.addSuccessEvent({key:502702})}catch(Ob){IO.error(Ob),fM.addFailedEvent({key:502702,error:Ob})}}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}},TM=class extends gM{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}},EM=class{constructor(){this.source=new gM,this.gain=new gM,this.destination=new gM}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t,i=sM();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;{let r=new MediaStream;r.addTrack(e),t=i.createMediaStreamSource(r)}}return t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},SM=class extends EM{constructor(e){super(),this.context=e,this.denoiser=new gM,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()}},IM=class{constructor(){this.audioContext=sM(),this.destination=this.audioContext.createMediaStreamDestination(),this.inputs=new Set,this.mixWeight=0,this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach((e=>e.remove()))}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}};var vM=class{constructor(e){ab(this,"_volume",0),ab(this,"_log"),ab(this,"_scriptProcessorNode",null),ab(this,"_audioWorkletNode",null),ab(this,"_interval",200),ab(this,"ready",this.preload());let{log:t}=e;this._log=t,iw.on(EO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return vM.workletReady||(vM.workletReady=eM(vM.audioContext,URL.createObjectURL(new Blob(['\nclass VolumeMeter extends AudioWorkletProcessor {\n constructor() {\n super();\n this.volume = 0;\n this.intervalTime = 200;\n this.tick = this.intervalTime;\n this.isStop = false;\n this.cache = [];\n this.sentFirstInfo1 = false;\n this.unmute = false;\n this.port.onmessage = (event) => {\n const { data } = event;\n switch (data.name) {\n case "chunk":\n this.cache.push.apply(this.cache, data.data);\n if (!this.sentFirstInfo1) {\n this.port.postMessage({ cl: data.data.length });\n this.sentFirstInfo1 = true;\n }\n break;\n case "setIntervalTime":\n this.intervalTime = data.intervalTime;\n break;\n case "unmute":\n this.unmute = true;\n break;\n case "stop":\n this.isStop = true;\n break;\n }\n };\n }\n process(inputs, outputs) {\n const input = inputs[0];\n const output = outputs[0];\n if(!input && !output) {\n return true;\n }\n if (this.isStop) {\n return false;\n }\n const l = output? output[0].length:0;\n const cl = this.cache.length;\n \n if (cl > l) {\n output[0].set(this.cache.slice(0, l));\n this.cache = this.cache.slice(l);\n } else if (this.unmute) {\n output[0].set(input[0]);\n }\n const firstChannel = cl > l ? output[0] : input[0];\n if(!firstChannel){\n return true;\n }\n let sum = 0;\n let rms;\n for (let i = 0; i < firstChannel.length; ++i) {\n sum += firstChannel[i] * firstChannel[i];\n }\n rms = Math.sqrt(sum / firstChannel.length);\n this.volume = Math.max(rms, this.volume * 0.95);\n this.tick -= firstChannel.length;\n if (this.tick < 0) {\n this.tick += (this.intervalTime / 1000) * sampleRate;\n this.port.postMessage({ volume: this.volume, cacheLen: cl,outputLen: l });\n }\n return true;\n }\n}\nregisterProcessor("volume-meter", VolumeMeter);\n'],{type:"application/javascript"})))),vM.workletReady.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(vM.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=t=>{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(oM){nw.logFailedEvent({userId:this._log.userId,eventType:Mk.LOAD_WORKLET,error:oM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=sM().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{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(oM){this._log.error("volumeMeter init script processor error: ".concat(oM))}}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,iw.off(EO.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})}},yM=vM;ab(yM,"audioContext",sM()),ab(yM,"workletReady");var AM=class extends gM{constructor(e){super(),ab(this,"_volumeMeter"),this._volumeMeter=new yM(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return lb(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()}}},RM=ob(db(),1),CM=e=>t=>t.deviceId===e,bM=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";ab(this,"kind"),ab(this,"type"),ab(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&&DM(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(CM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");IO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(CM(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");IO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},kM=class extends RM.EventEmitter{constructor(){super(),ab(this,"audioInputs",new bM(sk.AUDIO)),ab(this,"videoInputs",new bM(sk.VIDEO)),ab(this,"audioOutputs",new bM(sk.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||RP.run(sN,(()=>{this.update()}),{delay:1e4}))}init(){wM().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return lb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield wM(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},NM=xb||Lb?null:new kM;function DM(e){return e.deviceId===e.groupId&&""===e.groupId}function wM(){return lb(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=>{DM(e)&&(e.kind===sk.AUDIO_INPUT?i.audio=!0:e.kind===sk.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(Pb){IO.debug("capture before getDevices failed: ",Pb)}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&&xM.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function OM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return NM.update(e?1:0).then((e=>e.audioInputs.devices))}function PM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return NM.update(e?2:0).then((e=>e.videoInputs.devices))}var MM=!1;function LM(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return lb(this,null,(function*(){return NM.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var xM=new Set;function VM(e,t){return lb(this,null,(function*(){let i=(yield OM()).find((e=>e.deviceId===Xk));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var UM=class extends EM{constructor(e){super(),this.log=e,ab(this,"volumeMeter"),ab(this,"analyser",new TM),this.volumeMeter=new AM({log:this.log})}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode()}},FM=class extends wP{constructor(e){super(e,sk.AUDIO),ab(this,"_outputDeviceId"),ab(this,"_volume",1),ab(this,"_destination",sM().createMediaStreamDestination()),ab(this,"pipeline"),ab(this,"volumeMeterMode","worklet"),this.pipeline=new UM(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===MD||"15.3"===MD||"15.4"===MD)&&this.muted)return void this._log.info("audioElement is muted.");let e=new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,this.bindElementEvents()}play(){return lb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?yield this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(sM().createAnalyser()),this.setVolume(this._volume),function(){lb(this,null,(function*(){try{MM||(MM=!0,IO.info("speakers:".concat((yield LM()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(EF){}}))}(),cb(FM.prototype,this,"play").call(this)}))}stop(){this.pipeline.destory(),super.stop()}setSinkId(e){return lb(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()}},BM=class extends FM{constructor(e){super(e),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(CP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this.pipeline.replaceSource(e),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e]))):this.pipeline.source.deleteNode())}setSourceNode(e){!e||this.pipeline.source.node===e||(this.pipeline.replaceSource(e),e instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch((()=>{})),this.setVolume(this._volume)))}setVolume(e){this._volume=e,this.element&&(this.element.volume=e)}},HM=class extends FM{constructor(e){super(e),ab(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i;(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(CP.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?(this.element?this._log.info("set element volume: ".concat(e)):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),DP(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(){this.pipeline.destory(),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop()}},jM=class extends SP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?HM:ZP)}=e;var s;super(),ab(this,"id",vO()),ab(this,"userId",""),ab(this,"isRemote"),ab(this,"mediaType"),ab(this,"room"),ab(this,"user"),ab(this,"_log"),ab(this,"_inputTrack"),ab(this,"_outputTrack"),ab(this,"isPlayCalled"),ab(this,"container",null),ab(this,"player"),ab(this,"subVideoPlayerMap"),ab(this,"muted",!1),ab(this,"abortCtrl"),ab(this,"objectFit","cover"),ab(this,"mirror"),ab(this,"isScreen",!1),ab(this,"manager"),ab(this,"trackSettings"),this.userId=t||"",this.mediaType=r,this._log=IO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof aL?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof aL}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(CP.PLAYER_STATE_CHANGED,(e=>{iw.emit(EO.PLAYER_STATE_CHANGED,tb({track:this},e)),this.emit("player-state-changed",e)})),this.kind===sk.VIDEO&&(this.player.on(CP.LOADED_DATA,(()=>{iw.emit(EO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(CP.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onPlayerError&&this.player.on(CP.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||IO}get kind(){return 1===this.mediaType?sk.AUDIO:sk.VIDEO}get strMediaType(){return 4===this.mediaType?sk.VIDEO:2===this.mediaType?sk.SCREEN:sk.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}play(e,t){return lb(this,null,(function*(){let i=Hw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!xw(t.muted)&&this.setPlayerMute(t.muted),t&&!xw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof ZP&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Hw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!xw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===sk.VIDEO)&&this.setPlayerMute(!0),t&&!xw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ZP&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof ZP&&this.player.setContainer(i)),iw.emit(EO.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(),Hw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(rM){throw this.handleAutoPlayFailed(),this.emit("error",rM),rM}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==sk.VIDEO||xw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Fw(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 lb(this,null,(function*(){if(!this._outputTrack||this.kind===sk.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&&(xw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ZP({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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop()),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return lb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),iw.emit(e?EO.TRACK_MUTED:EO.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((()=>this.handleAutoPlayFailed())),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new $P;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof ZP?this.player.getVideoFrame():""}};sb([gP([],SP.INIT,{sync:!0})],jM.prototype,"close",1);var GM=Object.prototype.hasOwnProperty;var WM=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(ww(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(GM.call(e,t))return!1;return!0}return!1},JM=tw({retryFunction:function(e){return lb(this,null,(function*(){let t=function(e){return{audio:KM(e),video:qM(e)}}(e);IO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield OM(),IO.info("microphones: ".concat(lO(i,{keysToInclude:n})))),t.video&&(r=yield PM(),IO.info("cameras: ".concat(lO(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return rP&&e.getTracks().forEach((e=>{IO.info("".concat(e.kind," capabilities: ").concat(lO(e.getCapabilities(),{keysToInclude:cN})))})),e}catch(rM){let{message:n}=rM;throw"NotFoundError"===rM.name&&(e.video&&r&&0===r.length&&(n=ZD({key:hN.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=ZD({key:hN.MICROPHONE_NOT_FOUND}))),new yb({code:Ib.INITIALIZE_FAILED,name:rM.name,message:n,constraint:rM.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,(!DD||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&zM(n[0].microphoneId,!1),n[0].cameraId&&zM(n[0].cameraId,!0)},onRetrying:e=>{IO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{nw.logFailedEvent({eventType:Mk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{nw.logSuccessEvent({eventType:Mk.GET_USER_MEDIA_RETRY}),nw.uploadEvent({log:"stat-".concat(Mk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function zM(e,t){return lb(this,null,(function*(){let i=(t?yield PM():yield OM()).find((t=>t.deviceId===e));i&&Lw(i.getCapabilities)&&IO.warn(lO(i.getCapabilities(),{keysToInclude:cN}))}))}function KM(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!WM(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(Uw(e.channelCount)&&(t.channelCount=e.channelCount),Fw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),Fw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Fw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!WM(t)||t)}function qM(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&&!WM(i)?i:(e.width&&(i.width={ideal:e.width},t&&!DN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!DN&&(i.height.max=e.height)),DN&&aD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!WM(i)||i)}var YM=JM;function QM(e){return $M(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return lb(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function XM(e){return $M(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return lb(this,null,(function*(){return e.call(this,t.apply(this,r))}))}))}function $M(e){return function(t,i,r){return r.value=e(r.value,i),r}}var ZM=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&IO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{IO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),eL=0,tL=class{constructor(){this.log=IO.createLogger({id:"fq".concat(++eL)}),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=tb({},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()}))}},iL=new WeakMap,rL=new WeakMap;function nL(){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=iL.get(this)||new tL;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return iL.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function oL(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=iL.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=rL.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new yb({code:Ib.API_CALL_ABORTED,message:e}))})),iL.delete(this),rL.delete(this),n.apply(this,a)},r}}function sL(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=rL.get(this)||new Map,s=r.get(o(t))||new tL;return r.set(o(t),s),rL.set(this,r),s.push({fn:n,args:t,context:this})},r}}var aL=class extends jM{constructor(e,t){super({mediaType:e,PlayerClass:t}),ab(this,"isRemote",!1),ab(this,"deviceId"),ab(this,"groupId",""),ab(this,"label",""),ab(this,"_isRecapturing",!1),ab(this,"_lastRecaptureTime",0),ab(this,"_onMuteTimeoutId",-1),ab(this,"profile"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get enableEncodeFrame(){return!1}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){NP(e,e).add(sk.MUTE,this.onTrackMuted).add(sk.UNMUTE,this.onTrackUnmuted).add(sk.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===sk.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){DP(e)}setStateToCapture(){}capture(e){return lb(this,null,(function*(){var t;try{let i,r=Yw();iw.emit(EO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield YM(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),iw.emit(EO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Yw()-r}),i}catch(Pb){throw iw.emit(EO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Pb}),this.log.error("getUserMedia error observed ".concat(Pb)),Pb}}))}setInputMediaStreamTrack(e){this.state===SP.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),iw.emit(EO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return lb(this,null,(function*(){if(this.mediaTrack&&iP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return lb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==sk.AUDIO||t!==Xk||(yield VM(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),wM().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===sk.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(sk.AUDIO_INPUT);return!!xM.has(i)}(this.mediaTrack)||this.kind===sk.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(sk.VIDEO_INPUT);return!!xM.has(i)}(this.mediaTrack)||this._isRecapturing||e&&aD&&DD)}onTrackMuted(){if(ZM(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<rN)return void setTimeout((()=>this.onTrackMuted()),rN);this._onMuteTimeoutId=setTimeout((()=>lb(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((RN||CN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return lb(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<rN)return void setTimeout((()=>this.onTrackEnded()),rN);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return lb(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 OM():yield PM()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return lb(this,null,(function*(){let e=this instanceof hL;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(cL.get(t)||0)+1;if(cL.set(t,i),i>=3){let r=e?(yield PM()).find((e=>!cL.has(e.deviceId))):(yield OM()).find((e=>!cL.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)}};sb([gP(SP.INIT,"capture",{ignoreError:!0,sync:!0})],aL.prototype,"setStateToCapture",1),sb([nL()],aL.prototype,"capture",1),sb([gP("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),iw.emit(EO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===Ib.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],aL.prototype,"publish",1),sb([$M((e=>function(){return lb(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"})}))})),gP([],"capture",{sync:!0})],aL.prototype,"unpublish",1);var cL=new Map;iw.on(EO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&cL.delete(e.track.deviceId)}));var lL=class extends aL{constructor(e){super(1,BM),ab(this,"mediaType",1),ab(this,"volume",0),ab(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ab(this,"playerMuted",!0),ab(this,"pipeline"),this.manager=e,this.pipeline=new SM(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 lb(this,null,(function*(){yield cb(lL.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};fM.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),fM.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),fM.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.replaceSource(e),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return lb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Xk)return;if(yield VM(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),iw.emit(EO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(Ok){throw this.log.error("switch microphone failed ".concat(Ok)),this.deviceId&&this.recapture(this.deviceId),Ok}}}))}listenDeviceChange(){NM&&!NM.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&NM.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return lb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield OM();t[0]?this.recapture(t[0].deviceId):NM.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return lb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!xw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!xw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!xw(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&&fM.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;kD<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(fM.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(),NM.off("audioInputAdded",this.handleMicrophoneAdded,this),NM.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return lb(this,null,(function*(){try{yield cb(lL.prototype,this,"recapture").call(this,e)}catch(Ok){let i=(yield OM()).find((t=>t.deviceId!==e));if(!i)throw Ok;yield cb(lL.prototype,this,"recapture").call(this,i.deviceId)}}))}},dL=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}},uL=class{constructor(){ab(this,"_seiMessageList",[]),ab(this,"_smallSeiMessageList",[]),ab(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 dL(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}},hL=class extends aL{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,ZP),ab(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),ab(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),ab(this,"small"),ab(this,"isNeedToSetBandwidth"),ab(this,"muteImage"),ab(this,"manager"),ab(this,"_seiCodec",new uL),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(ib(tb({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(iP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}setMute(e){return lb(this,null,(function*(){var t,i,r;if(Vw(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,cb(hL.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,cb(hL.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!1,customSource:n}=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,customSource:n})}setProfile(e){let t=tb({},e),i=t.width>t.height;t.width*t.height<=19200&&CN&&RD&&(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&&UD&&(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(ib(tb({},this.profile),{width:1920,height:1080})))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:sk.VIDEO,videoType:sk.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return iP&&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:hO()&&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 lb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),iw.emit(EO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(Ok){throw this.log.error("switch camera failed ".concat(Ok)),this.deviceId&&this.recapture(this.deviceId),Ok}}))}listenDeviceChange(){NM&&!NM.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&NM.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return lb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield PM();t[0]?this.recapture(t[0].deviceId):NM.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return lb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}encodeFrame(e,t){try{let i=this._seiCodec.encode(e,!!t);i&&this._log.debug("".concat(i," sei sent"))}catch(Pb){this._log.warn(Pb)}return e}get enableEncodeFrame(){var e;return!(null==(e=this.room)||!e.enableSEI)&&nP}sendSEI(e,t){this._seiCodec.sendSEI(e,Object.assign({small:!!this.small},t))}play(e,t){return lb(this,null,(function*(){return xw(this.mirror)&&!this.isScreen&&this.setMirror("view"),cb(hL.prototype,this,"play").call(this,e,t)}))}close(){NM.off("videoInputAdded",this.handleCameraAdded,this),NM.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return lb(this,null,(function*(){try{yield cb(hL.prototype,this,"recapture").call(this,e)}catch(Ok){let i=(yield PM()).find((t=>t.deviceId!==e));if(!i)throw Ok;yield cb(hL.prototype,this,"recapture").call(this,i.deviceId)}}))}},pL=vO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:pL,exposeOrigin:!0,permittedOrigins:["*"]})}catch(EF){}var mL,_L=function(e){return lb(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:DD?{max:e.width}:{ideal:e.width,max:e.width},height:DD?{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);IO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(CD&&kD<74||DD||DN)&&IO.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(rM){IO.warn("screen applyConstraints failed: ".concat(rM))}e.captureElement&&(yield function(e,t){return lb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&Lw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==pL)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){IO.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 xw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);IO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},fL=class extends hL{constructor(e){super(e,2),ab(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),ab(this,"objectFit","contain"),ab(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return lb(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 _L({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 yb?e:new yb({code:Ib.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return lb(this,null,(function*(){throw new Error("Method not implemented.")}))}},gL=class extends lL{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var TL=class extends IM{constructor(e){super(),this.room=e,ab(this,"_localAudioTrack"),ab(this,"_localScreenAudioTrack"),ab(this,"log",IO.createLogger({id:"am"})),ab(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let 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=function(e){return lb(this,null,(function*(){let t=sM();mL||(mL=eM(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield mL;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()}})}))}(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}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){var t;if(e instanceof gL)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof lL)this._localAudioTrack=e,this.destination.channelCount=(null==(t=e.trackSettings)?void 0:t.channelCount)||1,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof vL)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof gL?delete this._localScreenAudioTrack:e instanceof lL&&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()}};function EL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return $M(((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 yb({code:Ib.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});IO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var SL=class extends jM{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ab(this,"tinyId"),ab(this,"isRemote",!0),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===SL.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed:".concat(this.isSubscribed," hasFlag:").concat(this.hasFlag," hasTrack:").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}},IL=SL;ab(IL,"STATE_SUBSCRIBE","subscribe"),sb([EL(5,1)],IL.prototype,"waitHasMediaTrack",1),sb([gP(SP.INIT,IL.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),iw.emit(EO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],IL.prototype,"subscribe",1),sb([gP(IL.STATE_SUBSCRIBE,SP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),iw.emit(EO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],IL.prototype,"unsubscribe",1);var vL=class extends IL{constructor(e,t){super(e,t,1),ab(this,"volume",0),ab(this,"mediaType",1),ab(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),ab(this,"audioDecoder"),this.manager=e.audioManager}onPlayerError(){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let e=new AudioDecoder({error:e=>this._log.error(e),output:e=>{this.player.write(e)}});e.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info("audioDecoder state:".concat(e.state)),this.audioDecoder=e}}get enableDecodeFrame(){var e,t;return(null==(t=null==(e=this.player.element)?void 0:e.error)?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&nP&&sP().AudioDecoder}decodeFrame(e){var t;return"configured"===(null==(t=this.audioDecoder)?void 0:t.state)&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},yL=class extends IL{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ab(this,"mediaType",4),ab(this,"source"),ab(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}get enableDecodeFrame(){return!!this.room.enableSEI&&nP}decodeFrame(e){try{if("empty"===e.type||0===e.data.byteLength)return e;let t=new DataView(e.data);if(1!==t.getInt32(0)||6!==t.getInt8(4))return e;let i=[],r=0,n=-1,o=-1;for(let s=0;s<e.data.byteLength;s++){let a=t.getUint8(s);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=s-r;if(-1===n?n=a:-1===o&&(o=a,i.push(new dL(new DataView(t.buffer.slice(n,o)))),n=a,o=-1),6!==t.getUint8(s+1)){e.data=t.buffer.slice(a);break}}r=0}else r=0}this._log.debug("".concat(i.length," sei received")),i.reverse().forEach((e=>{this.room.emit("sei-message",{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:this.user.userId,streamType:2===this.mediaType?"auxiliary":"main"})}))}catch(Ok){this._log.warn(Ok)}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)}},AL=class extends yL{constructor(e,t){super(e,t,2),ab(this,"mediaType",2),ab(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function RL(){}var CL=e=>e(),bL=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,kL=1,NL=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new ML(e,this,this.streamId++);return LL.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},DL=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=RL,this.error=RL,this.next=RL,this.dispose=RL,this.subscribe=RL,this.doDefer()}subscribe(e){return e instanceof NL?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(CL),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}},wL=class extends DL{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}};function OL(e,t,i){if(bL()){let r=Object.defineProperties(Object.setPrototypeOf(e,NL.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}});LL.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof NL&&LL.addSource(r,t)}return r}return e}function PL(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var ML=class extends wL{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{LL.defer(this.source,this.id)}))}next(e){LL.next(this.source,this.id,e),this.sink.next(e)}complete(){LL.complete(this.source,this.id),this.sink.complete()}error(e){LL.complete(this.source,this.id,e),this.sink.error(e)}},LL={addSource(e,t){PL("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){PL("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;PL("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){PL("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){PL("defer",{id:e.id,streamId:t})},pipe(e){PL("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){PL("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=kL++),PL("create",{name:e.toString(),id:e.id})}},xL=class extends DL{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};var VL=function(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 NL){let n=OL((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,LL.pipe(n),n}return t=>i(new e(t,...r))}}}(class extends wL{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return OL((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),VL((()=>performance.now())),function(){return e=>{let t=new xL(e);if(e instanceof NL){let i=OL((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,LL.pipe(i),i}return OL(t.add.bind(t),"share",arguments)}}());var UL=new Map;function FL(e,t){let i=ib(tb({},t),{timestamp:Rb()});UL.has(e)?UL.get(e).push(i):UL.set(e,[i])}iw.on(EO.JOIN_SUCCESS,(e=>{let{room:t}=e;FL(t.userId,{eventId:32788,eventDesc:"join room"})})),iw.on(EO.LEAVE_START,(e=>{let{room:t}=e;FL(t.userId,{eventId:32789,eventDesc:"leave room"})})),iw.on(EO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),FL(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),iw.on(EO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),FL(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),iw.on(EO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===sk.AUDIO?FL(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):FL(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),iw.on(EO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===sk.AUDIO?FL(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):FL(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),iw.on(EO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&FL(t.room.userId,{eventId:32777,eventDesc:"".concat(sk.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&FL(t.room.userId,{eventId:32776,eventDesc:"".concat(sk.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&FL(t.room.userId,{eventId:32803,eventDesc:"".concat(sk.SUBSCRIBE," ").concat(sk.SMALL_VIDEO),remoteUserId:t.userId}))})),iw.on(EO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&FL(t.room.userId,{eventId:32779,eventDesc:"".concat(sk.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&FL(t.room.userId,{eventId:32778,eventDesc:"".concat(sk.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&FL(t.room.userId,{eventId:32804,eventDesc:"".concat(sk.UNSUBSCRIBE," ").concat(sk.SMALL_VIDEO),remoteUserId:t.userId}))})),iw.on(EO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&FL(t.room.userId,{eventId:t.kind===sk.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===sk.VIDEO?"camera":"microphone")})})),iw.on(EO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&FL(t.room.userId,{eventId:t.kind===sk.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),iw.on(EO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===n?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===n?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&FL(r.userId,{eventId:t,eventDesc:i})})),iw.on(EO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===n?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===n&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&FL(r.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var BL=ob(db(),1),HL=class extends BL.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,ab(this,"userMap",new Map),ab(this,"remotePublishedUserMap",new Map)}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,"]");xw(t)||(r+=":".concat(tN[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=eO(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:eO(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function jL(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return $M(((e,n)=>{let o=new Map;return iw.on(EO.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 yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.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 GL,WL=!0,JL={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"},zL={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},KL=((GL=KL||{})[GL.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",GL[GL.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",GL[GL.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",GL[GL.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",GL[GL.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",GL[GL.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",GL[GL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",GL[GL.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",GL[GL.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",GL[GL.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",GL[GL.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",GL[GL.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",GL[GL.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",GL[GL.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",GL[GL.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",GL[GL.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",GL[GL.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",GL[GL.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",GL[GL.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",GL[GL.INVALID_OPERATION=5100]="INVALID_OPERATION",GL[GL.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",GL[GL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",GL[GL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",GL[GL.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",GL[GL.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",GL[GL.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",GL[GL.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",GL[GL.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",GL[GL.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",GL[GL.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",GL[GL.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",GL[GL.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",GL[GL.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",GL[GL.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",GL[GL.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",GL[GL.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",GL[GL.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",GL[GL.DEVICE_ERROR=5300]="DEVICE_ERROR",GL[GL.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",GL[GL.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",GL[GL.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",GL[GL.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",GL[GL.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",GL[GL.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",GL[GL.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",GL[GL.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",GL[GL.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",GL[GL.SERVER_ERROR=5400]="SERVER_ERROR",GL[GL.NEED_TO_BUY=5401]="NEED_TO_BUY",GL[GL.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",GL[GL.OPERATION_FAILED=5500]="OPERATION_FAILED",GL[GL.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",GL[GL.REJOIN_FAILED=5502]="REJOIN_FAILED",GL[GL.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",GL[GL.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",GL[GL.OPERATION_ABORT=5998]="OPERATION_ABORT",GL[GL.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",GL);var qL=ib(tb({},pN),{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(Mw(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(Mw(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."),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=YL(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=YL(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=YL(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=YL(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=YL(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=YL(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=YL(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 YL(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var QL=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=KL[i];try{t=qL[a]}catch(o){t=qL.UNKNOWN_ERROR}return Lw(t)?s=t(r):Vw(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:i||t,params:tb({fnName:o,error:s},n)}),super(c),ab(this,"name","RtcError"),ab(this,"code"),ab(this,"extraCode"),ab(this,"functionName"),ab(this,"message"),ab(this,"handler"),ab(this,"originError"),this.name=KL[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");sD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):aD&&(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 yb){let{stack:n}=e,o={code:zL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case Ib.INVALID_PARAMETER:o.code=zL.INVALID_PARAMETER,o.message=e.message;break;case Ib.INVALID_OPERATION:o.code=zL.INVALID_OPERATION;break;case Ib.NOT_SUPPORTED:case Ib.NOT_SUPPORTED_H264:o.code=zL.ENV_NOT_SUPPORTED,e.getCode()===Ib.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(pN.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Ib.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case Ib.SERVER_TIMEOUT:case Ib.SWITCH_ROLE_FAILED:o.code=zL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case Ib.API_CALL_ABORTED:o.code=zL.OPERATION_ABORT;break;case Ib.DEVICE_NOT_FOUND:case Ib.DEVICE_AUTO_RECOVER_FAILED:case Ib.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 Ib.UNKNOWN:break;default:o.code=zL.OPERATION_FAILED}r=new QL(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof QL)return e;r=new QL({code:zL.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var XL=QL,$L={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}}},ZL={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}}},ex={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(Vw(e)&&!document.getElementById(e))throw new XL({code:zL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},tx={name:"userId",required:!0,type:"string"},ix={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[JL.AUDIO_PROFILE_STANDARD,JL.AUDIO_PROFILE_STANDARD_STEREO,JL.AUDIO_PROFILE_HIGH,JL.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function rx(e,t){if(!e)throw new XL({code:zL.INVALID_OPERATION,extraCode:5101,fnName:t})}function nx(e,t,i){if(!e)throw new XL({code:zL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var ox={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 XL({code:zL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(Vw(e.roomId))throw new XL({code:zL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new XL({code:zL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new XL({code:zL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new XL({code:zL.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:ex,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:$L},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&PO())throw new XL({code:zL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ib(tb({},ex),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:$L}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:ix},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&PO())throw new XL({code:zL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:ix}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ex,publish:{type:"boolean"},option:ZL},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&PO())throw new XL({code:zL.ENV_NOT_SUPPORTED,extraCode:5201});if(!FO())throw new XL({code:zL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ex,publish:{type:"boolean"},option:ZL}},muteRemoteAudio:[tx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[tx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ex,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){rx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(nx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new XL({code:zL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ib(tb({},ex),{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){rx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(nx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new XL({code:zL.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&&xw(e.streamType))throw new XL({code:zL.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){rx(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(!nP)throw new XL({code:zL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new XL({code:zL.INVALID_OPERATION,messageParams:{key:hN.SEI_DISABLED}});if(e.byteLength>1e3)throw new XL({code:zL.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new XL({code:zL.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});rx(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},auxiliary:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new XL({code:zL.INVALID_PARAMETER,messageParams:{key:hN.SEI_BEFORE_PUBLISH},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 XL({code:zL.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new XL({code:zL.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(rx(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new XL({code:zL.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},sx={TRTC:ox},ax=class extends Error{};function cx(e,t){let i=nO(e);for(let r=0;r<t.length;r++)rO(i[r],t[r]);return i}function lx(e){this._resolve=Promise.resolve(e)}function dx(e){this._reject=Promise.reject(e)}var ux=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=cx;let i=ux.instances.get(e);i?i.set(t,this):ux.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=ux.instances.get(e);return i&&i.get(t)||new ux(e,t)}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 ax("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:lx,reject:dx};try{switch(this.state){case 1:if(0===e)throw new ax("already started");break;case 4:if(2===e)throw new ax("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 ax("already start");break;case 3:switch(e.type){case 2:throw new ax("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ax("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new ax("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 ax("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ax("start not allowed after update");case 0:throw new ax("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new ax("keep start")),new ax("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}},hx=ux;hx.instances=new WeakMap;var px=new WeakMap,mx=(e,t)=>{if(t instanceof ax){let{stack:i}=t;t=new XL({code:zL.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function _x(e,t){return $M(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=hx.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(mx.bind(null,r))}))}function fx(e,t){let{merge:i,debounce:r}=t||{};return $M(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=hx.get(this,"string"==typeof e?e:e.call(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=px.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(mx.bind(null,n)).then(r,o)}),e);px.has(this)?null==(l=px.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):px.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(mx.bind(null,n))}))}function gx(e){return $M(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return hx.get(this,"string"==typeof e?e:e.call(this,...n)).action(3,t.bind(this),n).catch(mx.bind(null,i))}))}var Tx={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"};function Ex(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function Sx(e){return e===JL.QOS_PREFERENCE_CLEAR?"detail":e===JL.QOS_PREFERENCE_SMOOTH?"motion":""}var Ix=new WeakMap;function vx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=tw({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=Ix.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=Ix.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;Lw(r)&&r.call(this,t,i),null!=(n=Ix.get(e))&&n.has(o)&&(Ix.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=Ix.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}):Ix.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=Ix.get(e))?void 0:t.delete(o)}))},s}}function yx(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=Ix.get(e))&&n.has(t)){let{stopRetry:n,args:s}=Ix.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=Ix.get(e))||o.delete(t))}return s.apply(this,c)},o}}var Ax=class{constructor(){ab(this,"_log"),this._log=IO.createLogger({id:"fd"})}download(e,t){return lb(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=Yw();if(t=Lw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=Yw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),fM.addSuccessEvent({key:522700,cost:Yw()-r}),t.data}catch(Pb){throw this._log.error("failed to download: ".concat(e,", error: ").concat(Pb)),fM.addFailedEvent({key:522700,error:Pb}),Pb}}))}downloadWithFetch(e,t){return lb(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(Ok){throw Ok}}))}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 lb(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Yw(),r=null,n=null;if(Lw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&Lw(fetch))try{let i=fetch(e);r=(yield WebAssembly.instantiateStreaming(i,t)).instance}catch(Mb){n=Mb}if(!r)try{let i=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(i,t)).instance}catch(Mb){n=Mb}if(r){let t=Yw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),fM.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),fM.addFailedEvent({key:522701,error:n}),n}))}};sb([vx({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],Ax.prototype,"download",1);var Rx=new Ax;var Cx=new WeakMap;function bx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return $M(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Nx.call(this,t,n,i,this._name)}catch(Pb){return Promise.reject(Pb)}return e.apply(this,n)}))}function kx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return $M(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Nx.call(this,t,n,i,this._name)}catch(Pb){throw Pb}return e.apply(this,n)}))}function Nx(e,t,i,r){if(Hw(e))for(let n=0;n<e.length;n++)Dx.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Dx.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function Dx(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:zL.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(xw(i)){if(t.required)throw new XL(s(5001));if(xw(t.defaultValue))return void(Lw(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),Lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),Vw(t.type[r])&&Mw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new XL({code:zL.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Jw(e)?zw(e):Vw(e)?e:Mw(e)))},value:i}})}else if(!xw(t.type)&&Mw(i)!==t.type)throw new XL(s(5002));if(!1===t.allowEmpty){let e=Uw(i)&&(0===i||Number.isNaN(i)),t=Vw(i)&&""===i.trim();if(e||t)throw new XL(s(5003))}if(t.notLessThanZero&&Uw(i)&&i<0)throw new XL(s(5006));if(!xw(t.min)&&Uw(i)&&i<t.min)throw new XL(s(5007));if(!xw(t.max)&&Uw(i)&&i>t.max)throw new XL(s(5008));if(Vw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new XL(s(5004))}else if(Lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new XL(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new XL(s(5005));let{properties:a}=t;ww(a)&&Bw(i)&&Object.keys(a).forEach((e=>{Dx.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;ww(c)&&Hw(i)&&i.forEach(((e,t)=>{Dx.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),Lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function wx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=(()=>""),replaceArg:i,getKVReportKey:r}=e;return $M(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];function c(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...s);if(s[e.argIndex]===t)return e.value}if(t===s||e in s)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(Mw(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(Mw(t))}}let l=this._log||IO;s.length>0?l.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>c(e,t,["userSig","privateMapKey"]))))):l.info("".concat(n,"()"));let d=r?r(...s):cM[n];try{let i=e.apply(this,s),r=Yw();return Ww(i)?i.then((e=>(l.info("".concat(n,"() success ").concat(t.call(this,...s))),fM.addSuccessEvent({key:d,cost:Yw()-r}),e))).catch((e=>{throw e=XL.convertFrom.call(this,e,n,1===s.length?s[0]:s),l.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e," params: ").concat(JSON.stringify(s,c))),fM.addFailedEvent({key:d,error:e}),e})):(fM.addSuccessEvent({key:d}),i)}catch(u){throw u=XL.convertFrom.call(this,u,n),l.error("".concat(n,"() failed ").concat(u," params: ").concat(JSON.stringify(s,c))),fM.addFailedEvent({key:d,error:u}),u}}))}var Ox=e=>$M(((t,i)=>function(r,n){return lb(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new XL({code:zL.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});return Nx.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),Px=0,Mx=class{constructor(e,t){ab(this,"player"),ab(this,"publisher"),ab(this,"mixInput"),this.mixInput=new SM(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),e.loop&&(this.loop=e.loop),e.volume&&(this.volume=e.volume),this.mixInput.connect()}reset(){this.seek(0),this.mixInput.connect()}seek(e){!this.player||e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e)}play(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}pause(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}stop(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}setOperation(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}},Lx=class{constructor(e){this.core=e,ab(this,"log"),ab(this,"mixedMusicMap",new Map),ab(this,"cacheMusicMap",new Map),Px+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Px)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(Px)),this.core=e}getName(){return Lx.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return Lx.startValidateRule;case"update":return Lx.updateValidateRule;case"stop":return Lx.stopValidateRule}}start(e){return lb(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 Mx(e,t.audioManager),this.cacheMusicMap.set(i,n)),yield n.play(),this.mixedMusicMap.set(i,n),this.log.info("start mix audio track ".concat(i," success.")),fM.addEnum({key:502700,value:3})}))}update(e){return lb(this,null,(function*(){let{id:t,volume:i,loop:r,operation:n,seekFrom:o}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let s=this.mixedMusicMap.get(t);s?(xw(i)||(s.volume=i),xw(r)||(s.loop=r),xw(n)||s.setOperation(n),xw(o)||s.seek(o)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return lb(this,arguments,(function(e){var t=this;let{id:i}=e;return function*(){var e;t.mixedMusicMap.has(i)&&(t.log.info("remove music source, music id: ".concat(i)),null==(e=t.mixedMusicMap.get(i))||e.stop(),t.mixedMusicMap.delete(i)),"*"===i&&t.destroyAllMusic()}()}))}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>this.stop({id:t})))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},xx=Lx;ab(xx,"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 XL({code:zL.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new XL({code:zL.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i})}}),ab(xx,"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"]}}}),ab(xx,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),ab(xx,"Name","AudioMixer");var Vx=e=>(e=Number(e))>0&&e<14e8,Ux=0,Fx=class{constructor(e){this.core=e,ab(this,"log"),ab(this,"preloadPromise"),ab(this,"audioContext",sM()),ab(this,"workletNode"),Ux+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Ux)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(Ux)),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 XL({code:zL.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return this.preloadPromise||(this.preloadPromise=this.doPreload(e)),this.preloadPromise}doPreload(e){return lb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield eM(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return Fx.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return Fx.startValidateRule(this.core);case"update":return Fx.updateValidateRule;case"stop":return Fx.stopValidateRule}}start(e){return lb(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 lb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="https://".concat(function(e){let t;return t=Vx(e)?Hx.MAIN_OVERSEA:Hx.MAIN,t}(t),"/api/v1/audioAiAuth?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)}}()}))}(ib(tb({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new XL({code:zL.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 lb(this,null,(function*(){}))}stop(){return lb(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(){}},Bx=Fx;ab(Bx,"updateValidateRule",{type:"object"}),ab(Bx,"stopValidateRule",{type:"object"}),ab(Bx,"Name","AIDenoiser");var Hx={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var jx=ob(db(),1),Gx=class extends jx.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 lb(this,null,(function*(){if(!this.observer&&"PressureObserver"in globalThis)try{this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3})}catch(Ob){IO.info("PressureDetector start error:",Ob)}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&IO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;null==(e=this.observer)||e.disconnect(),this.observer=null}},Wx=new Gx,Jx=0,zx=new Set,Kx=null;wb("5.6.3-beta.7");var qx={RtcError:XL,ErrorCode:zL,ErrorCodeDictionary:KL},Yx=class extends Eb.EventEmitter{constructor(e,t){super(),ab(this,"_room"),ab(this,"_eventListened",new Set),ab(this,"_localVideoTrack",null),ab(this,"_localAudioTrack",null),ab(this,"_localScreenTrack",null),ab(this,"_localScreenAudioTrack",null),ab(this,"_localVideoConfig",null),ab(this,"_localScreenConfig",null),ab(this,"_localAudioConfig",null),ab(this,"_remoteVideoConfigMap",new Map),ab(this,"_remoteAudioConfigMap",new Map),ab(this,"_remoteAudioMuteMap",new Map),ab(this,"_mediaTrackMap",new WeakMap),ab(this,"_log",IO.createLogger({id:"t".concat(++Jx)})),ab(this,"_plugins",new Map),ab(this,"_networkQuality",null),ab(this,"_speakerId"),this._room=new e(tb({logger:this._log,frameWorkType:Yx.frameWorkType},t)),this._log.debug(JSON.stringify(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(xx,t.assetsPath),this._use(Bx,t.assetsPath),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(Tx.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{let{reason:t,error:i}=e;this._log.error(new XL({code:zL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),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(Pb){let i=ZD({key:hN.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return IO.warn("".concat(i,"\n\n").concat(Pb.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;WL&&(WL=!1,5!==IO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Wb,"/en/index.html")),console.info("* Changelog: ".concat(Wb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),IO.info("TRTC Web SDK Version:",Db),IO.info("UA:",navigator.userAgent),IO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),WD().then((e=>{if(e){let t="UAData: ".concat(e.platform,"/").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=" ".concat(e.architecture,"/").concat(e.bitness)),e.mobile&&(t+=" mobile"),e.model&&(t+=" model: ".concat(e.model)),e.fullVersionList&&(t+=" ".concat(e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(","))),IO.info(t)}})));let r=new Yx(e,t||{});return zx.add(r),Wx.start(),r}_listenEvents(){NP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(Tx.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(Tx.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(Tx.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(Tx.ERROR,XL.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(Tx.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(Tx.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{NP(t,t).add("player-state-changed",(i=>{let r=ib(tb({},i),{userId:e.userId});t.kind===sk.VIDEO&&(r.streamType=Ex(t.streamType)),this.emit(t.kind===sk.AUDIO?Tx.AUDIO_PLAY_STATE_CHANGED:Tx.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===Ib.PLAY_NOT_ALLOWED&&this.emit(Tx.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{DP(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?Tx.REMOTE_AUDIO_AVAILABLE:Tx.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?Tx.REMOTE_VIDEO_AVAILABLE:Tx.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?Tx.REMOTE_VIDEO_AVAILABLE:Tx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))})).add("firewall-restriction",(()=>{this.emit(Tx.ERROR,new XL({code:zL.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(Tx.SEI_MESSAGE,ib(tb({},e),{streamType:Ex(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,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)/uN},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)/uN},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(Tx.STATISTICS,l)})).add("custom-message",(e=>{this.emit(Tx.CUSTOM_MESSAGE,e)})),NP(this,NM).add("audioInputAdded",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>lb(this,null,(function*(){if(this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Kx&&Kx.deviceId===$k){let e=(yield LM()).find((e=>e.deviceId===$k));e&&Kx.groupId!==e.groupId&&(Kx=e,this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>lb(this,null,(function*(){this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield LM())[0];t&&Kx&&(Kx.deviceId===e.deviceId||Kx.deviceId===$k&&Kx.groupId!==t.groupId)&&(Kx=t,this.emit(Tx.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(function(e,t,i){return{room:e,assetsPath:i,fileDownloader:Rx,innerEmitter:iw,constants:kb,environment:mN,utils:bb,eventLogger:nw,log:e.getLogger(),errorModule:t,kvStatManager:fM,clearStarted(t,i){let r=t.getAlias(),n=hx.instances.get(e);if(n)if(i){let e=n.get(r+i);if(!e)return;e.started=!1}else n.forEach(((e,t)=>{t.startsWith(r)&&(e.started=!1)}))}}}(this._room,qx,t));this._plugins.set(e.Name,i)}enterRoom(e){return lb(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),!Vw(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,Fw(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,Yx.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return lb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return lb(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(){DP(this),this.removeAllListeners(),this._room.destroy(),zx.delete(this),0===zx.size&&Wx.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 lb(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 lL(e._room.audioManager),s={},a={muted:!0};n&&(xw(n.microphoneId)?xw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&Uw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),xw(n.profile)||(Vw(n.profile)?rk[n.profile]&&o.setProfile(rk[n.profile]):o.setProfile(n.profile)),Uw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),xw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),xw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),xw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(Tx.ERROR,new XL({code:zL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=XL.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,ib(tb({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),xw(r)||o.setMute(r),NP(o,o).add("player-state-changed",(t=>{e.emit(Tx.AUDIO_PLAY_STATE_CHANGED,ib(tb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=ib(tb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return lb(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):xw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),xw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),xw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!xw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),xw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),rO(this._localAudioConfig,e)}))}stopLocalAudio(){return lb(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),DP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return lb(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 hL(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:xw(o.useFrontCamera)?xw(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?sk.FACING_MODE_USER:sk.FACING_MODE_ENVIRONMENT,xw(o.profile)||(Vw(o.profile)?nk[o.profile]&&s.setProfile(nk[o.profile]):s.setProfile(o.profile)),xw(o.fillMode)||(c.objectFit=o.fillMode),xw(o.mirror)||(c.mirror=o.mirror),xw(o.small)||(zO()?Vw(o.small)?s.small=nk[o.small]:!0===o.small?s.small=nk["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(Tx.ERROR,new XL({code:zL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=XL.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,ib(tb({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),xw(n)||(yield s.setMute(n)),s.mediaTrack)if(null!=o&&o.qosPreference){let e=Sx(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=Sx(JL.QOS_PREFERENCE_SMOOTH));NP(s,s).add("player-state-changed",(t=>{e.emit(Tx.VIDEO_PLAY_STATE_CHANGED,ib(tb({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=ib(tb({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return lb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(xw(n.profile)||(Vw(n.profile)?nk[n.profile]&&this._localVideoTrack.setProfile(nk[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&xw(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):xw(n.useFrontCamera)?xw(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?sk.FACING_MODE_USER:sk.FACING_MODE_ENVIRONMENT),xw(n.fillMode)||(o.objectFit=n.fillMode),xw(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=Sx(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(n.small){let e=!this._localVideoTrack.small;zO()?(!0===n.small?this._localVideoTrack.small=nk["120p"]:Vw(n.small)?this._localVideoTrack.small=nk[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&&!xw(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),xw(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),rO(this._localVideoConfig,e)}))}stopLocalVideo(){return lb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),DP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return lb(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 fL(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=XL.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,ib(tb({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null,a={},c={};n&&(xw(n.profile)||(Vw(n.profile)?ok[n.profile]&&o.setProfile(ok[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),xw(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=Sx(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=Sx(JL.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(sk.ENDED,(()=>{e._stopScreenShare(),e.emit(Tx.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new gL(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),NP(o,o).add("player-state-changed",(t=>{e.emit(Tx.VIDEO_PLAY_STATE_CHANGED,ib(tb({},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=ib(tb({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return lb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(xw(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=Sx(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!xw(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}),rO(this._localScreenConfig,e)}))}stopScreenShare(){return lb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return lb(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&&(xw(n.fillMode)||(a.objectFit=n.fillMode),xw(n.mirror)||(a.mirror=n.mirror),"main"===r&&!xw(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&&!xw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return lb(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&&(xw(s.fillMode)||(l.objectFit=s.fillMode),xw(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&&!xw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),rO(h,e);let p=xw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=xw(r)?h.view:r,_=xw(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 lb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return lb(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 lb(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._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return lb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return lb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return lb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let r,n="main";if(Vw(e)?r=e:(r=e.userId,e.streamType&&(n=e.streamType)),!r)return"sub"===n?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(r);if(e)return e.remoteAudioTrack.mediaTrack}return null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}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)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return lb(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(xw(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o})}catch($U){throw this._remoteAudioConfigMap.delete(t),$U}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return lb(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 lb(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),xw(t)&&n&&n.view&&!Zw(i)){let e=oO(n.view);e.length>0&&(yield r.play(e,i))}if(!xw(t)){let e=oO(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return lb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:r}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(Mb){}xw(t.muted)||i.setPlayerMute(t.muted),xw(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e)))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit(Tx.TRACK,{userId:t,streamType:Ex(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(xw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(Ex(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Hw(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(oO(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 lb(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._room.remotePublishedUserMap.forEach((e=>{DP(e.remoteAudioTrack),DP(e.remoteVideoTrack),DP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return lb(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),DP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return lb(this,null,(function*(){if(Kx&&!DM(Kx))this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:Kx});else{let e=yield LM();if(e[0]&&!DM(e[0]))Kx=e[0],this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!Kx||DM(Kx))&&(this._initActiveSpeaker(),iw.off("102",this._initActiveSpeaker))};iw.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){this._room.sendSEI(e,t||{seiPayloadType:243}),fM.addCount({key:5e5,useUV:!0})}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),fM.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){IO.setLogLevel(e),xw(t)||(t?IO.enableUploadLog():IO.disableUploadLog())}static isSupported(){return VO()}static getCameraList(){return PM(!0)}static getMicrophoneList(){return OM(!0)}static getSpeakerList(){return LM(!0)}static setCurrentSpeaker(e){return lb(this,null,(function*(){(yield LM()).forEach((t=>{t.deviceId===e&&(zx.forEach((i=>{i.setCurrentSpeaker(e),i.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),Kx=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(_M.version=s),t){case"count":_M.addCount({key:i,useUV:o});break;case"enum":_M.addEnum({key:i,value:r,useUV:o});break;case"number":_M.addNumber({key:i,value:r,split:n})}}},Qx=Yx;ab(Qx,"_loggerManager",IO),ab(Qx,"EVENT",Tx),ab(Qx,"ERROR_CODE",zL),ab(Qx,"TYPE",JL),ab(Qx,"frameWorkType",30),sb([wx({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"}})})],Qx.prototype,"use",1),sb([bx(sx.TRTC.enterRoom),_x("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})),$M((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),wx()],Qx.prototype,"enterRoom",1),sb([wx()],Qx.prototype,"exitRoom",1),sb([bx(sx.TRTC.switchRole),fx("room",{merge:(e,t)=>t}),wx()],Qx.prototype,"switchRole",1),sb([wx()],Qx.prototype,"destroy",1),sb([bx(sx.TRTC.startLocalAudio),_x("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)})),wx()],Qx.prototype,"startLocalAudio",1),sb([bx(sx.TRTC.updateLocalAudio),fx("audio",{debounce:{delay:200,getKey:()=>"".concat(Jx,"-localAudio"),isNeedToDebounce:e=>{var t;return!xw(null==(t=e.option)?void 0:t.captureVolume)}}}),wx()],Qx.prototype,"updateLocalAudio",1),sb([gx("audio"),wx()],Qx.prototype,"stopLocalAudio",1),sb([bx(sx.TRTC.startLocalVideo),_x("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)})),wx()],Qx.prototype,"startLocalVideo",1),sb([bx(sx.TRTC.updateLocalVideo),fx("video"),wx()],Qx.prototype,"updateLocalVideo",1),sb([gx("video"),wx()],Qx.prototype,"stopLocalVideo",1),sb([bx(sx.TRTC.startScreenShare),_x("screen",(()=>!0)),wx()],Qx.prototype,"startScreenShare",1),sb([bx(sx.TRTC.updateScreenShare),fx("screen"),wx()],Qx.prototype,"updateScreenShare",1),sb([wx()],Qx.prototype,"stopScreenShare",1),sb([bx(sx.TRTC.startRemoteVideo),_x((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Qx.prototype,"startRemoteVideo",1),sb([bx(sx.TRTC.updateRemoteVideo),fx((e=>"v".concat(e.userId).concat(e.streamType))),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Qx.prototype,"updateRemoteVideo",1),sb([bx(sx.TRTC.stopRemoteVideo),$M((e=>function(t){return lb(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)}))})),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Qx.prototype,"stopRemoteVideo",1),sb([gx((e=>"v".concat(e.userId).concat(e.streamType)))],Qx.prototype,"_stopRemoteVideo",1),sb([bx(...sx.TRTC.muteRemoteAudio),wx({getRemoteId:e=>e})],Qx.prototype,"muteRemoteAudio",1),sb([kx(...sx.TRTC.setRemoteAudioVolume),function(e,t){return $M(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var s,a;let c=null==(s=Cx.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);Cx.has(this)?null==(a=Cx.get(this))||a.set(t(...n),l):Cx.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),wx({getRemoteId:e=>e})],Qx.prototype,"setRemoteAudioVolume",1),sb([Ox("start"),_x(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>lM[e.getName()]})],Qx.prototype,"startPlugin",1),sb([Ox("update"),fx(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dM[e.getName()]})],Qx.prototype,"updatePlugin",1),sb([Ox("stop"),gx(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>uM[e.getName()]})],Qx.prototype,"stopPlugin",1),sb([kx(...sx.TRTC.enableAudioVolumeEvaluation)],Qx.prototype,"enableAudioVolumeEvaluation",1),sb([wx()],Qx.prototype,"getVideoSnapshot",1),sb([wx()],Qx.prototype,"setCurrentSpeaker",1),sb([_x((e=>"a".concat(e.userId)),(()=>!0))],Qx.prototype,"_startRemoteAudio",1),sb([$M((e=>function(t){return lb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(ib(tb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),gx((e=>"a".concat(e.userId)))],Qx.prototype,"_stopRemoteAudio",1),sb([gx("room")],Qx.prototype,"_exitRoom",1),sb([gx("screen")],Qx.prototype,"_stopScreenShare",1),sb([bx(...sx.TRTC.sendSEIMessage),jL({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}})],Qx.prototype,"sendSEIMessage",1),sb([bx(sx.TRTC.sendCustomMessage),jL({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Qx.prototype,"sendCustomMessage",1),sb([bx(sx.TRTC.create)],Qx,"_create",1);var Xx=Qx,$x=class{constructor(){this._set=new Set,iw.on(EO.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 Zx(){return lb(this,null,(function*(){let e,t;try{let t=yield OM();e=t&&t.length}catch(u){}try{let e=yield PM();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=AO.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};nw.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),nw.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var eV=ob(db(),1),tV=Symbol("instance"),iV=Symbol("cacheResult"),rV=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,cV.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},nV=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var oV=new Map;function sV(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=oV.get(r)||[];oV.has(r)||oV.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=lV.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[iV];r.state instanceof rV&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof rV&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new nV(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 nV(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 rV(d,t,s);cV.call(r,u);let h=e=>{var n;return r[iV]=e,u.aborted||(cV.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[iV])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(cV.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new nV(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 aV="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 cV(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(lV.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var lV=class extends eV.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=lV.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[tV];r?this.name=r.name+"-"+r.count++:i[tV]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=oV.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);oV.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=lV.instances.get(e),t||lV.instances.set(e,t=new lV(e,void 0,Object.create(lV.prototype)))):(t=lV.instances2.get(e),t||lV.instances2.set(e,t=new lV(e.constructor.name,void 0,Object.create(lV.prototype)))),t}static getState(e){var t;return null===(t=lV.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};aV(lV.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){cV.call(this,e)}};lV.STATECHANGED="stateChanged",lV.UPDATEAFSM="updateAFSM",lV.INIT="[*]",lV.ON="on",lV.OFF="off",lV.instances=new Map,lV.instances2=new WeakMap;var dV=ob(db()),uV="1",hV="5",pV="2",mV="3",_V="5",fV="4",gV={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},TV=[gV.UPDATE_REMOTE_MUTE_STAT,gV.UPLINK_NETWORK_STATS,gV.USER_LIST_RES,gV.MUTE_RESULT,gV.SERVER_FIRST_PACKAGE_RECEIVED,gV.RECEIVE_CUSTOM_MSG],EV={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},SV="publish_change",IV="join",vV="leave",yV="quality_report",AV="mute_uplink",RV="publish",CV="publish_state_change",bV="unpublish",kV="subscribe",NV="unsubscribe",DV="subscribe_change",wV="start_publishing",OV="stop_publishing",PV="start_push_user_cdn",MV="stop_push_user_cdn",LV="start_mcu_mix",xV="stop_mcu_mix",VV="get_user_list",UV="change_role",FV="update_constraint_config",BV="rebuild_pc",HV="join/v2",jV="publish/v2",GV="subscribe/v3",WV="ability_status_report",JV="reconnect",zV="channel_msg",KV=new Set;var qV=class extends dV.default{constructor(e){var t,i;super(),ab(this,"room"),ab(this,"url"),ab(this,"backupUrl"),ab(this,"race"),ab(this,"destroyed",!1),ab(this,"_socketInUse"),ab(this,"_socket"),ab(this,"_backupSocket"),ab(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),ab(this,"_currentState","DISCONNECTED"),ab(this,"_isReconnecting",!1),ab(this,"_seq",0),ab(this,"_log"),ab(this,"_lastMessageTime",-1),ab(this,"_connnectStartTime",-1),ab(this,"_stopConnectRetry"),ab(this,"bytesSent",0),ab(this,"bytesReceived",0),ab(this,"keepAlive",!1),this.room=e.room,this.race=!!xw(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-KV.size>0&&this.room.enableSPC&&(this.keepAlive=!0,KV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=IO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return lb(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=Yw();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 qw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?sk.BACKUP:sk.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?sk.MAIN:sk.BACKUP),t(new yb({code:Ib.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===sk.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(Ok){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(Ok){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||1e3!==e.code)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?sk.MAIN:sk.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(sk.MAIN),this.unbindAndCloseSocket(sk.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=uO(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(gV),o=Object.keys(gV)[n.indexOf(i)],s=EV[o];switch(TV.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case gV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){Ab=e-(new Date).getTime();let t=new Date;t.setTime(e),IO.info("baseTime from server: ".concat(t," offset: ").concat(Ab))}(r.svrTime),this._log.info("ChannelSetup Success"),fM.addSuccessEvent({key:521701,cost:Yw()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(uV,{signalInfo:this._signalInfo});else{let e=new yb({code:Ib.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:ZD({key:hN.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),fM.addFailedEvent({key:521701,error:e}),this.emit(hV,e)}break;case gV.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._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return lb(this,null,(function*(){try{aw(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(Ob){}}))}reconnect(){return lb(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:JV,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:EV.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),fM.addSuccessEvent({key:521702,cost:Yw()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(fM.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(Ob){this._log.error(Ob),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+=uO(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(n,l);let e=new yb({code:Ib.API_CALL_TIMEOUT,message:ZD({key:hN.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),r),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(n,l),e(t))};this.on(n,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return tw({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(mV,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"),KV.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(sk.MAIN),this.unbindAndCloseSocket(sk.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"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof rV&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(lV.STATECHANGED,i))};this.room.on(lV.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(pV,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(mV):"DISCONNECTED"===e&&this.emit(_V))}};sb([vx({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())}})],qV.prototype,"connect",1);var YV=ob(db()),QV=0,XV=!1,$V=new Set,ZV=!1,eU=class{constructor(e){ab(this,"userId"),ab(this,"tinyId"),ab(this,"_sdpSemantics"),ab(this,"_isUplink"),ab(this,"_room"),ab(this,"_log"),ab(this,"_signalChannel"),ab(this,"_isErrorObserved",!1),ab(this,"_waitForPeerConnectionConnectedPromise"),ab(this,"_waitForPeerConnectionConnectedPromiseReject",null),ab(this,"_peerConnection",null),ab(this,"_emitter",new YV.default),ab(this,"_currentState","DISCONNECTED"),ab(this,"_isReconnecting",!1),ab(this,"_reconnectionCount",0),ab(this,"_reconnectionTimer",-1),ab(this,"_isFirstConnection",!0),ab(this,"_prevTime",-1),ab(this,"_enableSEI"),ab(this,"_sei"),ab(this,"_localAddress"),ab(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=IO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=Yw())}afterConnect(e){return lb(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,fM.addSuccessEvent({key:521705,cost:Math.min(Yw()-this._prevTime,3e4)})):this._isReconnecting&&fM.addSuccessEvent({key:521706,cost:Yw()-this._prevTime}),this._prevTime=-1}catch(Ob){throw this._isFirstConnection?(this._isFirstConnection=!1,fM.addFailedEvent({key:521705,error:Ob})):this._isReconnecting&&this._reconnectionCount>=3&&fM.addFailedEvent({key:521706,error:Ob}),Ob}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&nP,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),$V.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 yb({code:Ib.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return bk;let e=null;if(this._isUplink){if(!YO()||0===this._peerConnection.getSenders().length)return bk;e=this._peerConnection.getSenders()[0].transport}else{if(!qO()||0===this._peerConnection.getReceivers().length)return bk;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:bk}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===kk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===kk.FAILED||e.target.connectionState===kk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new yb({message:r,code:Ib.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===kk.CONNECTED||e.target.connectionState===kk.COMPLETED)&&(this.logSelectedCandidate(),nw.logSuccessEvent({userId:this._room.userId,eventType:Mk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(QV=0,XV=!1,ZV=!0,$V.add(this)):$V.delete(this),iw.emit(EO.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 lb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(HO(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 yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{iw.off(EO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new yb({code:Ib.API_CALL_TIMEOUT,message:"connection timeout"});var i;QV+=1,i=this._signalChannel.isConnected,QV>2&&!XV&&0===$V.size&&i&&(this._log.warn("firewall restriction"),XV=!0,this._emitter.emit("firewall-restriction")),t(e)}),zk);iw.on(EO.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(mV,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=wk()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new yb({code:this._isUplink?Ib.UPLINK_RECONNECTION_FAILED:Ib.DOWNLINK_RECONNECTION_FAILED,message:ZD({key:this._isUplink?hN.UPLINK_RECONNECTION_FAILED:hN.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(mV,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"))}},tU=ob(Tb()),iU=function(e){return tU.default.parse(e)},rU=function(e){return tU.default.write(e)};function nU(e){return Object.keys(e).filter((t=>e[t]))}var oU=class extends eU{constructor(e){super(ib(tb({},e),{isUplink:!1})),ab(this,"_flag",0),ab(this,"role","anchor"),ab(this,"remoteAudioTrack"),ab(this,"remoteVideoTrack"),ab(this,"remoteAuxiliaryTrack"),ab(this,"ssrc",{audio:0,video:0,auxiliary:0}),ab(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new vL(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new yL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new AL(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return eO(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===sk.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===fk?sk.MAIN:sk.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=sk.AUDIO;i.kind===sk.VIDEO&&(n=r===sk.MAIN?sk.VIDEO:sk.AUXILIARY);let o=this.remoteAudioTrack;n===sk.VIDEO?o=this.remoteVideoTrack:n===sk.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=iU(e);return t.media.forEach((e=>{e.type===sk.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),rU(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=iU(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),rU(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return lb(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===kk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===kk.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(Mb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Mb.message," ").concat(JSON.stringify(this.muteState))),new yb({code:Ib.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Mb}}))}unsubscribe(e){return lb(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=tb({},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(nU(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=NV,n=EV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=DV,n=EV.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 yb({code:i.code,message:ZD({key:hN.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return lb(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(Ok){throw e.closePeerConnection(!0),Ok}}()}))}exchangeSDP(e){return lb(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:kV,commandDesc:"exchange sdp",data:r,responseCommand:EV.SUBSCRIBE_RESULT,timeout:Vk});if(!this._peerConnection){let e=new yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(Ok){throw this._isSDPExchanging=!1,Ok}}))}createOffer(){return lb(this,null,(function*(){let e={voiceActivityDetection:!1};XO()&&this._sdpSemantics===Uk?(this._peerConnection.addTransceiver(sk.AUDIO,{direction:ak.RECVONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:ak.RECVONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:ak.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=iU(e);return t.media.forEach((e=>{var t,i;if(e.type===sk.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(" ")}})),rU(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=iU(e);return t.media.forEach((e=>{e.type===sk.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),rU(t)}(t.sdp),this._sdpSemantics===Uk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return lb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Bk)throw new yb({code:Ib.NOT_SUPPORTED_H264,message:ZD({key:hN.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new yb({code:t,message:ZD({key:hN.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",ib(tb({},e),{userId:this.userId}))}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{iU(e).media.forEach((e=>{if(e.ssrcs)if(e.type===sk.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(fk)}));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(fk)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(gk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(Ok){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return lb(this,null,(function*(){if(!(cb(oU.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(Ok){let t=Pw(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}},sU=oU;sb([$M((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 yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],sU.prototype,"subscribe",1),sb([XM(eU.prototype.afterConnect),QM(eU.prototype.beforeConnect)],sU.prototype,"connect",1);var aU=sU,cU={voiceActivityDetection:!1},lU=class extends eU{constructor(e){super(ib(tb({},e),{isUplink:!0})),ab(this,"localMainAudioTrack",null),ab(this,"localMainVideoTrack",null),ab(this,"localAuxAudioTrack",null),ab(this,"localAuxVideoTrack",null),ab(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),ab(this,"_isPublishingAux",!1),ab(this,"_publishingLocalAudioTrack"),ab(this,"_publishingLocalVideoTrack"),ab(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}),ab(this,"flag",0)}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&&(QO()?(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===sk.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 lb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),XO()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:o}),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)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return lb(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||sk.AUDIO,{direction:ak.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?sk.VIDEO:s||sk.VIDEO,{direction:ak.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||sk.VIDEO,{direction:ak.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||sk.VIDEO,{direction:ak.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:sk.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:sk.VIDEO,videoType:o?sk.AUXILIARY:sk.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:sk.VIDEO,videoType:sk.SMALL}),e.push(2))}yield t.setTransceiverDirection(ak.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 lb(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 lb(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(ak.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ak.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 lb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!QO())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&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ib(tb({},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=ib(tb({},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(ak.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 lb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:CV,data:t,responseCommand:EV.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:bV,commandDesc:"unpublish",responseCommand:EV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Ib.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),iP){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:FV,data:this._mediaSettings,responseCommand:EV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return lb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?sk.AUXILIARY:sk.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),XO()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return lb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===sk.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===ak.INACTIVE&&(yield this.setTransceiverDirection(ak.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return lb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;QO()&&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===sk.VIDEO&&e instanceof hL&&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===Fk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=iU(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===sk.VIDEO)return!0;return!1}removeSender(e){let t=null;QO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&Lw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return lb(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?sk.AUXILIARY:sk.MAIN," stream")),XO()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return lb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===sk.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(ak.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return lb(this,null,(function*(){if(!DN)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._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ak.INACTIVE,"|").concat(ak.RECVONLY,"|").concat(ak.SENDONLY,")")))&&o++,t.includes(o)){if(e===ak.INACTIVE&&i.includes("a=".concat(ak.RECVONLY)))return r=!0,"a=".concat(e);if(e===ak.SENDONLY&&i.includes("a=".concat(ak.INACTIVE)))return r=!0,"a=".concat(ak.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return lb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===sk.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===sk.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===sk.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return lb(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return;if(i=XO()?e.kind===sk.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(n?sk.AUXILIARY:sk.MAIN," stream")),e.kind===sk.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===sk.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return lb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(cU);DN&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===sk.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:SV,data:n,responseCommand:EV.UPDATE_OFFER_RESULT,timeout:xk,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(Pb){throw this._log.error(Pb),Pb}}))}setBandwidth(e){return lb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!tP())return o?r===sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(XO()){let t=0;r===sk.VIDEO&&(t=n===sk.SMALL?2:n===sk.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===sk.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";DN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===sk.SMALL?n=1:i===sk.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 DN&&(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 lb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(Ob){throw this.closePeerConnection(!0),this.uninstallEvents(),Ob}}))}exchangeSDP(){return lb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(Ob){throw Ob}}))}createOffer(){return lb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(cU);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(Ob){throw Ob}}))}doExchangeSDP(){let e={command:RV,responseCommand:EV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof fL||this.localAuxVideoTrack instanceof fL,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=iU(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),rU(r)}acceptAnswer(e){return lb(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?sk.AUXILIARY:sk.BIG;s=yield this.setBandwidth({bandwidth:e,type:sk.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:sk.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:sk.VIDEO,videoType:sk.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch($U){throw this._log.error("failed to accept remote answer ".concat($U)),$U}}))}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(AV,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return lb(this,null,(function*(){if(!(cb(lU.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:bV,responseCommand:EV.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(Ok){let t=Pw(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)&&iw.emit(EO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{iU(e).media.forEach(((e,t)=>{if(e.type===sk.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Fk&&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(Ok){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Bk?(this._log.error(pN.NOT_SUPPORTED_H264ENCODE),new yb({code:Ib.NOT_SUPPORTED_H264,message:ZD({key:hN.NOT_SUPPORTED_H264ENCODE})})):new yb({code:Ib.UNKNOWN,message:ZD({key:hN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EV.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},dU=lU;sb([$M((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 yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],dU.prototype,"publish",1),sb([XM(eU.prototype.afterConnect),QM(eU.prototype.beforeConnect)],dU.prototype,"connect",1);var uU=dU,hU=class{constructor(e,t){this.room=e,ab(this,"_log"),ab(this,"_prevReportTime"),ab(this,"_prevReport",{}),ab(this,"_prevEncoderImplementation"),ab(this,"_prevQualityLimitationReason"),ab(this,"_prevAuxQualityLimitationReason"),ab(this,"_prevDecoderImplementationMap",new Map),ab(this,"totalBytesSent",0),ab(this,"totalBytesReceived",0),ab(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return lb(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),r=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var n;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===sk.VIDEO){let n,o;if(i.ssrc===r.video?(n=sk.VIDEO,o=e.localMainVideoTrack):i.ssrc===r.small?n=sk.SMALL:i.ssrc===r.auxiliary&&(o=e.localAuxVideoTrack,n=sk.AUXILIARY),!n)return;t[n].bytesSent=i.bytesSent,t[n].packetsSent=i.packetsSent,t[n].framesEncoded=i.framesEncoded,xw(i.keyFramesEncoded)||(t[n].keyFramesEncoded=i.keyFramesEncoded),xw(i.nackCount)||(t[n].nackCount=i.nackCount),xw(i.pliCount)||(t[n].pliCount=i.pliCount),xw(i.retransmittedPacketsSent)||(t[n].retransmittedPacketsSent=i.retransmittedPacketsSent),xw(i.totalEncodeTime)||(t[n].totalEncodeTime=i.totalEncodeTime),xw(i.totalPacketSendDelay)||(t[n].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===r.video?(!xw(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!xw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===r.auxiliary&&!xw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?HO(i)&&Uw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===sk.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===sk.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(sk.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(sk.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!xw(i.audioLevel)&&(null==(n=e.localMainAudioTrack)?void 0:n.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!xw(i.frameWidth)){let n=sk.SMALL;i.trackIdentifier===e.getVideoTrackId(sk.VIDEO)||i.ssrc===r.video?n=sk.VIDEO:(i.trackIdentifier===e.getVideoTrackId(sk.AUXILIARY)||i.ssrc===r.auxiliary)&&(n=sk.AUXILIARY),t[n].frameWidth=i.frameWidth,t[n].frameHeight=i.frameHeight,t[n].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(rM){this._log.warn("failed to getStats on sender connection ".concat(rM))}return t}))}getReceiverStats(e){return lb(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===sk.AUDIO){if(i.ssrc!==r.audio||!n.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,i.jitterBufferDelay&&(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount),t.hasAudio=!0}else{if(DN&&0===i.bytesReceived)return;let s;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&HO(i)&&Uw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);xw(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!xw(i.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&i.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(Pb){this._log.warn("failed to getStats on receiver connection ".concat(Pb))}return t}))}getStats(e,t){return lb(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=Yw(),n=yield e.getStats(),o=Yw();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(WM(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;if(!WM(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*uN,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*uN);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:n}=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(Tk)),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};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};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/n),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/n),sD&&115===AD()&&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),xw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),xw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),xw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),xw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),xw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/n)),xw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/n))}));let a=o.msg_down_stream_info;return i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid)))),i.msg_down_stream_info.forEach((e=>{let t=a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(WM(e.msg_audio_status)||WM(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,o=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)/o)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(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/n),i.uint32_audio_total_bitrate=Math.round(8*a/n)}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,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(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/n);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/n),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/n)}))}})),i}getStatsReport(e){return lb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,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}},pU=ob(db()),mU=class extends pU.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ab(this,"_room"),ab(this,"_signalChannel"),ab(this,"_log"),ab(this,"_uplinkRTT",0),ab(this,"_uplinkLoss",0),ab(this,"_downlinkRTT",0),ab(this,"_downlinkLoss",0),ab(this,"_downlinkPrevStatMap",new Map),ab(this,"_downlinkLossAndRTTMap",new Map),ab(this,"_interval",-1),ab(this,"_uplinkNetworkQuality",0),ab(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=IO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(EV.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(pV,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.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 lb(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)===kk.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;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 lb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!qO())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&&Uw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===sk.AUDIO||e.mediaType===sk.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(rM){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!==kk.DISCONNECTED&&e.connectionState!==kk.FAILED&&e.connectionState!==kk.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=RP.run(nN,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];iw.emit(EO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(mU.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(RP.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay: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})}}))}},_U=mU;ab(_U,"EVENT_NETWORK_QUALITY","0");var fU=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=IO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&Lw(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 Ww(o)?o.catch((e=>IO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(Ok){IO.error("".concat(t.name,"() error observed ").concat(Ok))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=RP.run(nN,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Db,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,WD().then((e=>{this._basicInfo.string_os_version=qD(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),iw.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(EO.JOIN_START,this.handleJoinStart).addEvent(EO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(EO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(EO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(EO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(EO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(EO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(EO.JOIN_FAILED,this.handleJoinFailed).addEvent(EO.LEAVE_START,this.handleLeaveStart).addEvent(EO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(EO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(EO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(EO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(EO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(EO.PUBLISH_START,this.handlePublishStart).addEvent(EO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(EO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(EO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(EO.PLAY_TRACK_START,this.handlePlayStart).addEvent(EO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(EO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!Gw(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===sk.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(EO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(EO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(EO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(EO.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(EO.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)=>iw.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),RP.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(xw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),xw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),xw(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 yb?Number(i.getExtraCode()||i.getCode()):Ib.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:ib(tb({},TU),{msg_user_info:new EU({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 EU({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(!Gw(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(!Gw(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_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:r,uint32_video_height:n}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/uN*100)>0&&(this._localStreamStat.totalAudioLevel+=e/uN,this._localStreamStat.audioLevelCount++)}i.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*ZC(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/uN*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/uN,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof yb?i.getExtraCode()||i.getCode():Ib.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&dk))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&pk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&hk))>=0}hitTest(e){return e===this._room}checkStorage(){return lb(this,null,(function*(){try{let e=yO.getItem(this._storageKey);e&&(yield this.upload(e),yO.deleteItem(this._storageKey))}catch(oM){this._log.warn(oM)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&yO.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,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,sk.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,sk.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,gU);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>gU&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+gU):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>gU&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+gU):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>gU&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+gU)}getReportData(){this._basicInfo.uint32_networkType=yw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new EU({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:iO(this._signalInfo.relayIp),uint32_client_ip:iO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ZC(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:iO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return _O(e),e}report(){return lb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),yO.deleteItem(this._storageKey),this.initData()}catch(oM){this._log.warn(oM)}}))}upload(e){return lb(this,null,(function*(){if(FD&&!hD||0===e.msg_path_enter_room.uint64_start_time||[Bb,Hb,jb].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=yield dN(e),r=i instanceof ArrayBuffer,n="".concat(Tw(t,Yb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||lN({url:n,body:i}),this.uploadKVStat(fM),this.uploadKVStat(_M)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return lb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=ib(tb({},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 dN(t),r="".concat(Tw(+this._room.sdkAppId,Yb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||lN({url:r,body:i})}))}};sb([vx({settings:{timeout:500,retries:3}})],fU.prototype,"upload",1);var gU=5e3,TU={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},EU=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},SU=fU,IU=class{constructor(){ab(this,"_startTime"),ab(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=Yw())}stop(){0===this._endTime&&(this._endTime=Yw())}getDuration(){return 0===this._endTime?Yw()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},vU=class{constructor(e){ab(this,"_room",null),ab(this,"_durationMap"),ab(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(EO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(EO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(EO.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"),sk.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),sk.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),sk.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,sk.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,sk.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,sk.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>iw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>iw.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 IU,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,sk.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new IU,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,sk.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,sk.AUDIO),this.stopDurationItem(o,sk.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new IU,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===sk.AUDIO?[n]:[],video:t===sk.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()}},yU=class{constructor(e){ab(this,"_room"),ab(this,"_renderFreezeMap",new Map),ab(this,"_isVideoPlayingEventFiredMap",new Map),ab(this,"_dataFreezeMap",new Map),ab(this,"_monitorFreezeData",new Map),ab(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(EO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(EO.PLAY_TRACK_START,this.onPlayTrackStart).set(EO.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(EO.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(EO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(Gw(t)&&this.hitTest(t.room)&&n===sk.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===sk.MUTE?this.onVideoTrackMuted(t):r===sk.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(EO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>iw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>iw.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 IU;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>jk?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 lb(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=Yw();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=Yw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!Gw(t)||!this.hitTest(t.room)||t.kind!==sk.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()<jk&&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=Yw()-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()}},AU=ob(db(),1),RU=[-1,-1,1,-1,-1,1,1,1],CU=[0,0,1,0,0,1,1,1],bU=class extends SP{constructor(e,t){if(super(),this.context=e,ab(this,"name"),ab(this,"input"),ab(this,"output"),ab(this,"texture"),ab(this,"image"),ab(this,"ctx2d",null),ab(this,"fbo"),ab(this,"width",0),ab(this,"height",0),ab(this,"x",0),ab(this,"y",0),ab(this,"program"),ab(this,"vertexShader"),ab(this,"fragmentShader"),ab(this,"totalFrames",0),ab(this,"dropFrames",0),ab(this,"matchInputSize",!0),ab(this,"texCoordBuffer"),ab(this,"positionBuffer"),ab(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ab(this,"cost",0),ab(this,"_canvas",null),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof UU){if(e.ctx&&t.create2d){let e=document.createElement("canvas"),t="function"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext("2d"),this.image=t,this._canvas=t}}else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(CU),this.positionBuffer=this.createBuffer(RU),!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(Pb){this.context.destroy(Pb)}}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 VU&&this.render(e)||this.context instanceof UU&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),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 VU){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},tb({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}};sb([gP(SP.INIT,"connected",{sync:!0})],bU.prototype,"connect",1),sb([gP("connected",SP.INIT,{ignoreError:!0,sync:!0})],bU.prototype,"disconnect",1),sb([gP([],"closed",{sync:!0})],bU.prototype,"close",1);var kU=[0,1,1,1,0,0,1,0],NU=class extends bU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),ab(this,"_intervalId",0),ab(this,"_sequence",0),ab(this,"checkGLError",!1),e instanceof UU?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(kU)}start(e){this._intervalId=RP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(RP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof VU){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),RP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},DU=class extends NU{constructor(e,t){super(e,t),ab(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,r)},r=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,r)};e instanceof VU&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}},wU=class extends DU{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},OU=class extends DU{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;IO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(IO.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))}},PU=class extends bU{constructor(e,t,i){super(e,tb({name:"imageSource"},i)),this.image=t,ab(this,"_image"),ab(this,"_totalFrames",0),ab(this,"_autoResize",!1),this._autoResize=!1!==(null==i?void 0:i.autoResize)}_render(e,t){let{width:i,height:r}=this;if(this.image instanceof HTMLVideoElement){if(Lw(this.image.getVideoPlaybackQuality)&&!wD){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}if(({videoWidth:i,videoHeight:r}=this.image),!i||!r)return!1;this.image.width=i,this.image.height=r}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:r}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&r===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:r}=this.image),this._image=this.image);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,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,r)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},MU=class extends PU{constructor(e,t,i){let r=document.createElement("video");r.setAttribute("playsinline","playsinline"),r.setAttribute("muted",""),super(e,r,i),this._videoTrack=t,ab(this,"_mediaStream"),this.name="videoTrackSource",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play())}close(){var e;super.close(),null==(e=this._mediaStream)||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}},LU=class extends SP{constructor(e){super(),ab(this,"frameRate"),ab(this,"_canvas"),ab(this,"log"),ab(this,"hasAlpha",!1),ab(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e){return new MU(this,e)}createVideoTrackDestination(e){return new DU(this,e)}createVideoImageSource(e,t){return new PU(this,e,t)}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},xU={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},VU=class extends LU{constructor(){super(...arguments),ab(this,"defaultProgam"),ab(this,"defaultVShader"),ab(this,"defaultFShader"),ab(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",xU),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,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}};sb([gP(SP.INIT,"created",{sync:!0})],VU.prototype,"create",1),sb([gP("created",SP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],VU.prototype,"destroy",1);var UU=class extends LU{constructor(){super(...arguments),ab(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};sb([gP(SP.INIT,"created",{sync:!0})],UU.prototype,"create",1),sb([gP("created",SP.INIT,{ignoreError:!0,sync:!0})],UU.prototype,"destroy",1);var FU=[1,0,0,0,1,1,0,1],BU=class extends bU{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof VU)try{this.setTexBuffer(FU)}catch(Ob){e.destroy(Ob)}}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)}},HU=class{constructor(e,t){this.node=e,this.layout=t,ab(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}},jU=class extends bU{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),ab(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new HU(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 VU&&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},tb({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 VU))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(rM){}}))}},GU=class extends MU{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0}),ab(this,"ready",!1),ab(this,"_bgTexture"),ab(this,"_waterMarkTexture"),ab(this,"_lastMaskTexture"),ab(this,"_lastMaskFbo"),ab(this,"_textureValid",!1),ab(this,"_selfieTextureValid",!1),ab(this,"_selfieSegmentation"),ab(this,"wasm"),ab(this,"_prePrograme"),ab(this,"_segmentationMask"),ab(this,"_weixin",!1),this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return lb(this,null,(function*(){let t=e.Wasm,i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(i.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(i.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),i.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0}))}onPredict(e){let t=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():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality&&!wD){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:r}=this.image;this.image.width=i,this.image.height=r;let n=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),n=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===r&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,r),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,i,r):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,i,r,0)),this._selfieSegmentation.send(i,r)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},WU=class extends AU.EventEmitter{constructor(e){super(),this.room=e,ab(this,"videoContext"),ab(this,"_glVideoContext"),ab(this,"_2dVideoContext"),ab(this,"destination"),ab(this,"smallVideoContext"),ab(this,"smallDestination"),ab(this,"smallTrackSource"),ab(this,"smallImageSource"),ab(this,"_isMirror",!1),ab(this,"cameraTrack"),ab(this,"cameraNode"),ab(this,"mirrorNode"),ab(this,"mixNode"),ab(this,"screenTrack"),ab(this,"screenNode"),ab(this,"selfModel",!1),ab(this,"blurRadius",3),ab(this,"arTrack"),ab(this,"Wasm"),ab(this,"waterMarkNode"),ab(this,"_waterMarkOption"),ab(this,"watermarkImageList",[]),ab(this,"_isMixScreen",!1),ab(this,"_virtualBackground"),ab(this,"virtualBackgroundInstance"),ab(this,"isUsingArTrack",!1),ab(this,"_bgAssetPath"),ab(this,"log",IO.createLogger({id:"vm"})),ab(this,"_checkId",0),ab(this,"_use2d",!1),ab(this,"_autoSwitchRenderMode",!0),ab(this,"_selfieSegmentation"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new UU({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _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 UU({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new VU({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(Ob){this.emit("error",{reason:"create",error:Ob}),this.sendCreateResult("videoCtxGl",Ob)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=RP.run(sN,(()=>{this.destination&&this.log.debug(this.destination.getInfo())}),{delay:e})}destroy(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),RP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(wD||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&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?fM.addFailedEvent({key:t,error:e}):fM.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 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 OU(this.smallVideoContext,r)),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),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),wD&&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(Pb){this.log.error("set main output failed",Pb)}}update(){return lb(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.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(i.width,i.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new wU(this.videoContext,{name:"mainDestination"})),this.cameraNode=new GU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new BU(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new jU(this.videoContext),i.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),null==(e=this.waterMarkNode)||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)}))}changeInput(e){var t,i,r,n;if(e instanceof fL)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof hL)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof yL){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;if(17===LD&&!e.source&&e.player.element){let t=new UU({frameRate:15,logger:this.log,name:e.userId});t.create({alpha:!1});let i=t.createVideoImageSource(e.player.element);e.source=i;let r=new NU(t);i.connect(r),e.player.setCanvas(t._canvas)}return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof fL?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hL?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof yL&&e.source&&e.source.context.destroy()}setCameraTrack(e){return lb(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 lb(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 yb({code:Ib.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)})),pO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setWatermark(e){return lb(this,null,(function*(){let t;try{t=yield pO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new yb({code:Ib.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return lb(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return lb(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 lb(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield pO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else this._virtualBackground=void 0;this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return lb(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}},JU=0,zU=class extends SP{constructor(e){super("room"),this.seq=++JU,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=IO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,Fw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Fw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Fw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new SU({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new vU({room:this}),this.badCaseDetector=new yU({room:this}),this.audioManager=new TL(this),this.videoManager=new WU(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return lb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return lb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return lb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Vw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(ww(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?(dw([o,o]),Fb("https://".concat(o))):(r&&Fb(r),n&&dw(n))}iw.once(EO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:lw.main,sched_back_domain:lw.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return lb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return lb(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 lb(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 yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(pN.INVALID_DESTROY),new yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.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,iw.emit(EO.ROOM_DESTROY,{room:this})}schedule(e,t){return lb(this,null,(function*(){var i,r;let n=Yw();try{let{isCached:o,result:s,detailCost:a}=yield cw({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Db,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(lO(s,{keysToExclude:["username","credential"]}))),o&&iw.once(EO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=tb(tb({},this.scheduleResult),s),Uw(null==(i=s.config)?void 0:i.retryCount)&&Dk(s.config.retryCount),Vw(null==(r=s.config)?void 0:r.loggerDomain)&&Fb(s.config.loggerDomain),iw.emit(EO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),fM.addSuccessEvent({key:521700,cost:Yw()-n,split:50})}catch(o){throw fM.addFailedEvent({key:521700,error:o}),o}}))}},KU=ob(db()),qU=ob(Tb()),YU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=iU(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:sk.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:sk.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(QU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),rU(s)},QU=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:sk.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:sk.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;a<i.video.codecs.length;a++)XU(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));XU(s,i.video.codecs[e])}else if(o)for(let a=0;a<r.video.codecs.length;a++)XU(s,r.video.codecs[a]);else XU(s,r.video.codecs[0]);return s.payloads=s.payloads.trim(),s},XU=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var $U,ZU=e=>{let t=qU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===sk.AUDIO||e.type===sk.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===sk.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===sk.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),qU.default.write(t)},eF=(($U=eF||{}).TRACK="track",$U.DATA_CHANNEL_MESSAGE="data_channel_msg",$U[$U.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",$U[$U.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",$U.RECONNECTED="spc-reconnected",$U.RECONNECT_FAILED="spc-reconnect-failed",$U.ERROR="error",$U.SEI_MESSAGE="sei-message",$U),tF=0,iF=!1,rF=new Set,nF=1,oF=class extends KU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),ab(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ab(this,"currentState","DISCONNECTED"),ab(this,"_room"),ab(this,"_signalChannel"),ab(this,"_peerConnection",null),ab(this,"_datachannel",null),ab(this,"_enableCustomMessage"),ab(this,"_log"),ab(this,"_downlinkMIDMap",new Map),ab(this,"_downlinkMIDUserIDMap",new Map),ab(this,"_reconnectionTimer",-1),ab(this,"reconnectionCount",0),ab(this,"clientAbility"),ab(this,"_serverAbility",null),ab(this,"addDownlinkQueue",new Set),ab(this,"removeDownlinkQueue",new Set),ab(this,"_parsedAnswer",null),ab(this,"_updateSDPPromise",null),ab(this,"_waitForPCConnectedPromise"),ab(this,"_waitForPCConnectedPromiseReject",null),ab(this,"_isSDPLogged",!1),ab(this,"abortMap",new Map),ab(this,"enableInsertableStreams",!1),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=IO.createLogger({id:"spc".concat(nF++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&nP&&(this.enableInsertableStreams=!0)}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.abortMap.get(e))||i.abort("destory"),this.abortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return null!=(e=this._serverAbility)&&e.useVp8?"vp8":"h264"}get isUsingH264(){return"h264"===this.videoCodec}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=iU(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&&!xw(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}}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 lb(this,null,(function*(){let e;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())},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 aF(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(sk.AUDIO,{direction:sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:sk.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:sk.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this.clientAbility=((e,t)=>{var i,r;let n=iU(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let s=n.media[0],a=n.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(r=a.rtp[l+1])?void 0:r.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),fM.addSuccessEvent({key:521707}),this.clientAbility}catch(Ok){throw fM.addFailedEvent({key:521707,error:Ok}),this._log.error("initialize failed ".concat(Ok," \noffer: ").concat(null==e?void 0:e.sdp)),Ok}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return lb(this,null,(function*(){try{if("CONNECTED"===this.currentState)return;let i=Yw(),r={type:"answer",sdp:YU({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||fM.addSuccessEvent({key:521703,cost:Yw()-i})}catch(Pb){let i=Pb instanceof yb&&Pb.code===Ib.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(Pb),e),this.reset(),!i&&!this.isReconnecting&&(fM.addFailedEvent({key:521703,error:Pb}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),Pb}}))}reconnect(){return lb(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(mV,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:BV,responseCommand:EV.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new yb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),fM.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),iw.emit(EO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(Ob){if(!this.isReconnecting)return;if(null!=Ob&&Ob.message.includes("timeout")){let e=Pw(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(null==Ob?void 0:Ob.code," ").concat(Ob)),fM.addFailedEvent({key:521704,error:Ob}),this.reconnectionCount>=wk()&&this._log.warn("SDK has tried reconnect for ".concat(wk()," 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 lb(this,null,(function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(mV,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===kk.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===kk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===kk.FAILED||e.target.connectionState===kk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===kk.CONNECTED||e.target.connectionState===kk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),iw.emit(EO.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 bk;let e=null;return YO()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,qO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:bk):bk}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(eF.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return lb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(HO(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&&vw(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();this._waitForPCConnectedPromiseReject=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 yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{iw.off(EO.LEAVE_SUCCESS,r,this),this.off(eF.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new yb({code:Ib.API_CALL_TIMEOUT,message:"connection timeout"});var i;tF+=1,i=this._signalChannel.isConnected,tF>2&&!iF&&0===rF.size&&i&&(this._log.warn("firewall restriction"),iF=!0,this.emit(eF.FIREWALL_RESTRICTION)),t(e)}),zk);iw.on(EO.LEAVE_SUCCESS,r,this),this.on(eF.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return lb(this,null,(function*(){var t,i;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(rM){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(rM)),yield this.startReconnection()}null!=(t=this._room.scheduleResult.config)&&t.jitterDelay&&this.setJitterBufferDelay(e.userId,null==(i=this._room.scheduleResult.config)?void 0:i.jitterDelay)}))}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().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=sk.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=iU(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(sk.AUDIO,{direction:sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:sk.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(sk.VIDEO,{direction:sk.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=QU({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:iU(this._peerConnection.localDescription.sdp),useAllCodec:!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=sk.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(sk.MAIN," ").concat(l,"-audio")}],s.direction=sk.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(sk.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(sk.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=sk.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(sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(sk.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(sk.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 lb(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=iU(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 lb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(tP()){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=iU(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=iU(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=iU(this._peerConnection.remoteDescription.sdp));let s=DN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:DN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:DN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:DN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:DN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:DN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:DN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:DN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:DN?1e3*n:n}]);let a={type:"offer",sdp:rU(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=rU(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>lb(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($U){this._log.error($U),!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($U)}})))),this._updateSDPPromise}filterSDPDirection(){return iU(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((e=>e.direction))}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:ZU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.abortMap.forEach((e=>e.abort("destroy"))),this.abortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}setJitterBufferDelay(e,t){var i;if(this._peerConnection){this._log.info("set ".concat(e," jitterBuffer delay ").concat(t));try{let r=this._peerConnection.getReceivers();null==(i=this._downlinkMIDMap.get(e))||i.forEach((e=>{r[e]&&(r[e].jitterBufferTarget=t)}))}catch(rM){this._log.warn("set ".concat(e," jitterBuffer delay error: ").concat(rM))}}}};sb([oL("reconnect")],oF.prototype,"startReconnection",1),sb([sL((e=>e.userId))],oF.prototype,"addDownlink",1),sb([sL((e=>e))],oF.prototype,"removeDownlink",1),sb([nL(!0)],oF.prototype,"updateSDP",1);var sF=class{constructor(e){ab(this,"tag"),ab(this,"len"),ab(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}},aF=class{constructor(e){ab(this,"tinyId"),ab(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new sF(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)}))}},cF=new Set;function lF(){let e=Math.floor(4294967296*Math.random());return cF.has(e)?lF():(cF.add(e),e)}var dF=ob(db()),uF=class extends dF.default{constructor(e){super(),ab(this,"userId"),ab(this,"tinyId"),ab(this,"_sdpSemantics"),ab(this,"_isUplink"),ab(this,"_room"),ab(this,"_log"),ab(this,"_signalChannel"),ab(this,"_currentState","DISCONNECTED"),ab(this,"_prevTime",-1),ab(this,"_enableSEI"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=IO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(iw.emit(EO.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"))}},hF=class extends uF{constructor(e){super(ib(tb({},e),{isUplink:!0})),ab(this,"localMainAudioTrack",null),ab(this,"localMainVideoTrack",null),ab(this,"localAuxAudioTrack",null),ab(this,"localAuxVideoTrack",null),ab(this,"_isPublishingAux",!1),ab(this,"_publishingLocalAudioTrack"),ab(this,"_publishingLocalVideoTrack"),ab(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}),ab(this,"_flag",0),ab(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc: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=RP.run(aN,(()=>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(qD()," ").concat(JD())),fM.addCount({key:521e3})}RP.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&&(QO()?(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===sk.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&pk),bigVideo:!!(this.flag&dk),smallVideo:!!(this.flag&uk),auxVideo:!!(this.flag&hk)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,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 lb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e,o,s,a,c,l;if(!t.singlePC)return;yield t.singlePC.waitForPeerConnectionConnected();let d,{publishState:u,muteState:h}=t;if(i&&(t._publishingLocalAudioTrack=i,u.audio=!0,h.audio=i.muted),r){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new yb({code:Ib.NOT_SUPPORTED_H264,message:ZD({key:hN.NOT_SUPPORTED_H264ENCODE})});CN&&115===AD()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(nk["480p_2"]),yield r.applyProfile()),t._publishingLocalVideoTrack=r,n?(u.auxVideo=!0,h.auxVideo=r.muted):(u.bigVideo=!0,h.bigVideo=r.muted)}if(t._isPublishingAux=n,r&&!n&&r.small&&(d=t._room.videoManager.smallTrack,u.smallVideo=!0),yield t._signalChannel.sendWaitForResponseWithRetry({command:jV,responseCommand:EV.SPC_PUBLISH_RESULT,data:ib(tb({},t.singlePC.uplinkSSRC),{state:u,muteState:h}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:d,isAuxiliary:n}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n)r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i);else{if(r){t.localMainVideoTrack=r;let{scaleResolutionDownBy:e}=r;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(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)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!XO())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[],d=(e,t,i)=>{var r;let n=a[t].sender.replaceTrack(i);l.push(t),null!=(r=this.singlePC)&&r.enableInsertableStreams&&n.then((()=>this.createEncodedStreams(a[t].sender,e))),c.push(n)};s&&d(t.mediaType,0,s),o&&d(i.mediaType,n?3:1,o),r&&d(8,2,r);let u=this.setTransceiverDirection(ak.SENDONLY,l);return c.push(u),Promise.all(c)}getTrackByMeidaType(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:throw new Error("mediaType error")}}createEncodedStreams(e,t){var i,r;if(this.singlePC.abortMap.has(e))return;let n=e.createEncodedStreams(),o=new AbortController;null==(i=this.singlePC)||i.addAbortController(e,o),(null!=(r=this.getTrackByMeidaType(t))&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(e,i)=>{var r;return i.enqueue(null!=(r=this.singlePC)&&r.isUsingH264?this.getTrackByMeidaType(t).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)}))}enableSmall(e){return lb(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ak.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ak.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 lb(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&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ib(tb({},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=ib(tb({},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(ak.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 lb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:CV,data:t,responseCommand:EV.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:bV,commandDesc:"unpublish",responseCommand:EV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Ib.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),iP){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:FV,data:this._mediaSettings,responseCommand:EV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return lb(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?sk.AUXILIARY:sk.MAIN," stream")),QO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return lb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===sk.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===ak.INACTIVE&&(yield this.setTransceiverDirection(ak.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return lb(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?sk.AUXILIARY:sk.MAIN," stream")),QO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return lb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===sk.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ak.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return lb(this,null,(function*(){if(!DN)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._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(ak.INACTIVE,"|").concat(ak.RECVONLY,"|").concat(ak.SENDONLY,")")))&&o++,t.includes(o)){if(e===ak.INACTIVE&&i.includes("a=".concat(ak.RECVONLY)))return r=!0,"a=".concat(e);if(e===ak.SENDONLY&&i.includes("a=".concat(ak.INACTIVE)))return r=!0,"a=".concat(ak.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return lb(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;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(r.kind," track on ").concat(n?sk.AUXILIARY:sk.MAIN," stream")),r.kind===sk.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===sk.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r)))}))}setBandwidth(e){return lb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===sk.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:AV,responseCommand:EV.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&iw.emit(EO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sk.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===sk.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===sk.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===sk.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===sk.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Bk?(this._log.error(pN.NOT_SUPPORTED_H264ENCODE),new yb({code:Ib.NOT_SUPPORTED_H264,message:ZD({key:hN.NOT_SUPPORTED_H264ENCODE})})):new yb({code:Ib.UNKNOWN,message:ZD({key:hN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EV.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return lb(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};function pF(e){return Object.keys(e).filter((t=>e[t]))}var mF=class extends uF{constructor(e){super(ib(tb({},e),{isUplink:!1})),ab(this,"_flag",0),ab(this,"role","anchor"),ab(this,"remoteAudioTrack"),ab(this,"remoteVideoTrack"),ab(this,"remoteAuxiliaryTrack"),ab(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new vL(this._room,this),this.remoteVideoTrack=new yL(this._room,this),this.remoteAuxiliaryTrack=new AL(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return eO(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===sk.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let 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,receiver:r}=e;if(!t.id.includes(this.tinyId))return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let o=sk.AUDIO;i.kind===sk.VIDEO&&(o=n===sk.MAIN?sk.VIDEO:sk.AUXILIARY);let s=this.remoteAudioTrack;o===sk.VIDEO?s=this.remoteVideoTrack:o===sk.AUXILIARY&&(s=this.remoteAuxiliaryTrack),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s,r),s.setInputMediaStreamTrack(i)}createEncodedStreams(e,t){if(!this.singlePC.abortMap.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}};(e.enableDecodeFrame?i.readable.pipeThrough(new TransformStream({transform:(e,t)=>t.enqueue(n.enqueue(e))})):i.readable).pipeTo(i.writable,r).catch((e=>{"destory"!==e&&this._log.warn(e)})),this.singlePC.addAbortController(t,n)}}subscribe(e,t){return lb(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(pF(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(Pb){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Pb.message," ").concat(JSON.stringify(this.muteState))),new yb({code:Ib.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Pb}}))}checkTrackEnded(e){var t,i,r;(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&&(this._log.warn("remote track ended start spc reconnect"),this.singlePC.startReconnection())}unsubscribe(e){return lb(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=tb({},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(pF(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=NV,n=EV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=DV,n=EV.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 yb({code:i.code,message:ZD({key:hN.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 lb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:lF(),bigVideoSsrc:lF(),bigVideoRtxSsrc:lF(),auxVideoSsrc:lF(),auxVideoRtxSsrc:lF()},{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:GV,responseCommand:EV.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 yb({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})}}()}))}removeDownlink(){return lb(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.userId))}))}};sb([nL(),$M((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 yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],mF.prototype,"subscribe",1),sb([nL()],mF.prototype,"unsubscribe",1);var _F=mF;var fF=ob(db());var gF=class extends fF.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,ab(this,"log"),ab(this,"cmdIdSeqMap",new Map),ab(this,"messageMap",new Map),this.log=IO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(EV.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}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(zV,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||Math.abs(r.lastSeq-e.seq)>gF.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 this.emit("message",e)}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}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.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},TF=gF;ab(TF,"SEQ_INTERVAL",300);var EF,{isString:SF,isUndefined:IF,getNetworkType:vF,isEmpty:yF}=bb,AF=class extends zU{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=$O,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new hU(this,this._log),this.userManager=new HL(this.userId,this._log),this._version=Db,this.sdpSemantics=Fk,IF(e.sdpSemantics)?AO.isUnifiedPlanDefault()&&(this.sdpSemantics=Uk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(vF())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!IF(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!IF(e.enableSPC)&&$O&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return lb(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)QC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&qC)for(var r of qC(e))t.indexOf(r)<0&&XC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);iw.emit(EO.REMOTE_PUBLISH_STATE_CHANGED,tb({room:this},t)),this.emit("remote-publish-state-changed",tb({},t))})),this._joinOptions=e,new Promise(((t,i)=>lb(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 yb&&o.code===Ib.SPC_INITIALIZED_FAILED))return i(o);null==(r=this._signalChannel)||r.destroy(),yield this.initialize()}yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(o){i(o)}this._joinReject=null}))))}))}initSinglePC(){return lb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new oF({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(Ob){throw this.fallbackToMPC(),new yb({code:Ib.SPC_INITIALIZED_FAILED,message:null==Ob?void 0:Ob.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>lb(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this._signalChannel.once(hV,(e=>{this.clearJoinTimeout(),iw.emit(EO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),Fw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&$O&&(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:YD(),netType:yw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new yb({code:Ib.JOIN_ROOM_FAILED,message:ZD({key:hN.JOIN_ROOM_TIMEOUT})}))}),c),iw.emit(EO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?HV:IV,a),this._signalChannel.once(EV.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:n,data:o,tinyId:s}=e.data;iw.emit(EO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(n)),r(new yb({code:Ib.JOIN_ROOM_FAILED,extraCode:t,message:ZD({key:hN.JOIN_ROOM_FAILED,data:{error:n,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return lb(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),i.push(this._signalChannel.connect())),yield Promise.all(i),yield this.doJoin(ib(tb({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),nw.logSuccessEvent({userId:this.userId,eventType:Mk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(eF.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof hF&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(eF.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof uU&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(Ok){this._log.warn("reJoin fail ".concat(Ok)),this.reset(),nw.logFailedEvent({userId:this.userId,eventType:Mk.REJOIN,error:Ok}),this.emit("error",new yb({code:Ib.JOIN_ROOM_FAILED,message:ZD({key:hN.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return lb(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...KV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),r=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(r?"reuse":"setup"," signal channel")),r?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):(this._signalChannel=new qV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._customMessageManager=new TF(this,this._signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this._networkQuality||(this._networkQuality=new _U({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(_U.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),NP(this,this._signalChannel).add(pV,(e=>{iw.emit(EO.SIGNAL_CONNECTION_STATE_CHANGED,tb({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(fV,(e=>{this.reset(),this.emit("error",e)})).add(EV.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(EV.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(EV.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(EV.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(nw.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(uV,(e=>{this.tinyId=e.signalInfo.tinyId,iw.emit(EO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),iw.emit(EO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),r&&iw.emit(EO.JOIN_SIGNAL_CONNECTION_END,{room:this}),r}))}setSignalChannel(e){this._signalChannel=e,e||DP(this)}leave(){return lb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(Ok){}this._log.info("leave() => leaving room"),iw.emit(EO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(vV)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=RP.run(nN,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),RP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return lb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let r=this._signalChannel.isConnected?function(e){if(UL.has(e)){let t=UL.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return UL.delete(e),t}return[]}(this.userId):[],n=tb({str_sdk_version:Nb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:yw()},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);iw.emit(EO.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(yV,n),this.emit("heartbeat-report",ib(tb({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag: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}}));iw.emit(EO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?_F:aU)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}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!==Ib.ICE_TRANSPORT_ERROR&&(i===Ib.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",ib(tb({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=RP.run(nN,this.syncUserList.bind(this)))}stopSyncUserListInterval(){RP.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then((e=>{this.userManager.setUserList(e)})).catch((e=>{this._log.debug("sync user list failed: ".concat(e))}))}getUserList(){var e;return null!=(e=this._signalChannel)&&e.isConnected?this._signalChannel.sendWaitForResponse({command:VV,responseCommand:EV.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 ZD({key:hN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:EV.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||!ZV)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)===kk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof eU&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===kk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return lb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),nw.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 uU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}this.remotePublishedUserMap.forEach((e=>{let t=new aU({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return lb(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:UV,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:EV.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 yb({code:Ib.SWITCH_ROLE_FAILED,message:ZD({key:hN.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof yb&&e.getCode()===Ib.API_CALL_TIMEOUT&&(e=new yb({code:Ib.SWITCH_ROLE_FAILED,message:ZD({key:hN.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 lb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof lL&&(t instanceof gL?i.audio=t:e.audio=t),t instanceof hL&&(t instanceof fL&&2===t.mediaType?i.video=t:e.video=t)}));let r=yF(e),n=yF(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new hF({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new uU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",ib(tb({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Ib.ICE_TRANSPORT_ERROR&&(t===Ib.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 lb(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 lL&&(t instanceof gL?i.audio=t:e.audio=t),t instanceof hL&&(t instanceof fL&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");yF(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),yF(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(rM){}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&&eP()?this.uplinkConnection.replaceTrack(e).then((t=>{iw.emit(EO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return lb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return lb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:sk.VIDEO,videoType:sk.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 lb(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=tb({},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),iw.emit(EO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(nU(n),"] prev: [").concat(nU(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());iw.emit(EO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Mb){let i=Mb instanceof yb?Mb.getCode():Ib.UNKNOWN,n=Mb;throw Mb instanceof yb?i===Ib.REMOTE_STREAM_NOT_EXIST&&(n=new yb({code:Ib.API_CALL_ABORTED,message:ZD({key:hN.API_CALL_ABORTED,data:{message:Mb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new yb({code:i,message:ZD({key:hN.SUBSCRIBE_FAILED,data:{message:Mb.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 lb(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(Mb){this._log.warn("unsubscribe() => failed ".concat(Mb))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),iw.emit(EO.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 RP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),iw.emit(EO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&RP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=RP.run(oN,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit("audio-volume",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return lb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return lb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return lb(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 lb(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 lb(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(bb.getTurnServer(e)))):bb.isPlainObject(e)&&i.push(bb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:LV,data:e,timeout:5e3,responseCommand:EV.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:xV,data:e,timeout:5e3,responseCommand:EV.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?wV:PV,data:e,timeout:5e3,responseCommand:t?EV.START_PUBLISH_TENCENT_CDN_RES:EV.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?OV:MV,data:e,timeout:5e3,responseCommand:t?EV.STOP_PUBLISH_TENCENT_CDN_RES:EV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:WV,data:e,timeout:5e3,responseCommand:EV.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=bb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this._signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return lb(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(iN-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=iN}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(iN-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:iN};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(SF(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!IF(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new yb({code:Ib.INVALID_PARAMETER,message:ZD({key:hN.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(!IF(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new yb({code:Ib.INVALID_PARAMETER,message:ZD({key:hN.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!IF(e.userDefinePushArgs)){if(!(SF(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new yb({code:Ib.INVALID_PARAMETER,message:ZD({key:hN.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}yF(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){var i,r;this.uplinkConnection instanceof hF&&(null!=t&&t.toSubStream?null==(i=this.uplinkConnection.localAuxVideoTrack)||i.sendSEI(e,t):null==(r=this.uplinkConnection.localMainVideoTrack)||r.sendSEI(e,t))}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}};return sb([sV(["left",lV.INIT],"joined"),vx({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),aw(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),$M((e=>{let t=new $x;return function(i,r,n){return lb(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 yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new yb({code:Ib.INVALID_OPERATION,message:ZD({key:hN.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)),iw.emit(EO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield AO.checkSystemRequirementsInternal(),this.checkDestroy();let s=bb.getEnv();s||(s=Qb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ck.OLD_CLOUD_LADDER)?s=Qb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ck.WEBRTC)&&(s=Qb.WEBRTC))),nw.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Zx.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!AO.isWebRTCSupported()||!a&&!c)throw new yb({code:Ib.NOT_SUPPORTED,message:ZD({key:hN.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!bb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=bb.performanceNow(),iw.emit(EO.JOIN_SUCCESS,{room:this}),nw.uploadEvent({log:"stat-conv-".concat(Number(FD),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),iw.emit(EO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],AF.prototype,"join",1),sb([sV("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),$M((e=>function(){return lb(this,null,(function*(){iw.emit(EO.LEAVE_START,{room:this}),yield e.call(this),iw.emit(EO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),oL("leave room"),yx({fnName:"publish",validateArgs:!1}),yx({fnName:"unsubscribe",validateArgs:!1})],AF.prototype,"leave",1),sb([nL(),$M((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return lb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;iw.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),vx({settings:{retries:wk,timeout:e=>Pw(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),iw.emit(EO.PUBLISH_FAILED,{room:this}))}})],AF.prototype,"publish",1),sb([yx({fnName:"publish"}),(EF="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=iL.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new yb({code:Ib.API_CALL_ABORTED,message:EF})),!1)}));n.queue=e}return r.apply(this,t)},i}),nL(),$M((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}))],AF.prototype,"unpublish",1),sb([sL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),EL(),$M((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})),vx({settings:{retries:wk,timeout:e=>Pw(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),iw.emit(EO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],AF.prototype,"subscribe",1),sb([yx({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")}))}}),sL((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],AF.prototype,"unsubscribe",1),Xx.create=Xx._create.bind(Xx,AF),Xx}));
|
|
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,S=TypeError,y=function(e){if(E(e))throw S("Can't call method on "+e);return e},I=g,v=y,A=function(e){return I(v(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},N=C,D=Object.defineProperty,w=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0})}catch(i){N[e]=t}return t},O=w,P="__core-js_shared__",L=C[P]||O(P,{}),M=L;(k.exports=function(e,t){return M[e]||(M[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.30.0",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.30.0/LICENSE",source:"https://github.com/zloirock/core-js"});var x,V,U=y,F=Object,B=function(e){return F(U(e))},H=B,j=c({}.hasOwnProperty),G=Object.hasOwn||function(e,t){return j(H(e),t)},W=c,J=0,K=Math.random(),z=W(1..toString),q=function(e){return"Symbol("+(void 0===e?"":e)+")_"+z(++J+K,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=G,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},Se=Ee,ye=ge.all,Ie=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===ye}:function(e){return"object"==typeof e?null!==e:Se(e)},ve=Ie,Ae=String,Re=TypeError,Ce=function(e){if(ve(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},we=Ie,Oe=C.document,Pe=we(Oe)&&we(Oe.createElement),Le=function(e){return Pe?Oe.createElement(e):{}},Me=Le,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Me("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},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,ze=Object,qe=se?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&Ke(t.prototype,ze(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=Ie,at=TypeError,ct=Fe,lt=Ie,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,St=xe,yt=Ne,It=Ce,vt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Nt="writable";De.f=Et?yt?function(e,t,i){if(It(e),t=vt(t),It(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Nt in i&&!i[Nt]){var r=Ct(e,t);r&&r[Nt]&&(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(It(e),t=vt(t),It(i),St)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 Dt=Math.ceil,wt=Math.floor,Ot=Math.trunc||function(e){var t=+e;return(t>0?wt:Dt)(t)},Pt=Ot,Lt=function(e){var t=+e;return t!=t||0===t?0:Pt(t)},Mt=Lt,xt=Math.max,Vt=Math.min,Ut=function(e,t){var i=Mt(e);return i<0?xt(i+t,0):Vt(i,t)},Ft=Lt,Bt=Math.min,Ht=function(e){return e>0?Bt(Ft(e),9007199254740991):0},jt=Ht,Gt=function(e){return jt(e.length)},Wt=A,Jt=Ut,Kt=Gt,zt=function(e){return function(t,i,r){var n,o=Wt(t),s=Kt(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:zt(!0),indexOf:zt(!1)},Yt={},Qt=G,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=Ne,ci=De,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,Si=Yt,yi=pi,Ii=Le,vi="prototype",Ai="script",Ri=fi("IE_PROTO"),Ci=function(){},bi=function(e){return"<"+Ai+">"+e+"</"+Ai+">"},ki=function(e){e.write(bi("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ni=function(){try{hi=new ActiveXObject("htmlfile")}catch(n){}var e,t,i;Ni="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=Ii("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 Ni[vi][Ei[r]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[vi]=gi(e),i=new Ci,Ci[vi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},wi=_e,Oi=Di,Pi=De.f,Li=wi("unscopables"),Mi=Array.prototype;null==Mi[Li]&&Pi(Mi,Li,{configurable:!0,value:Oi(null)});var xi,Vi,Ui,Fi=function(e){Mi[Li][e]=!0},Bi={},Hi=Ee,ji=C.WeakMap,Gi=Hi(ji)&&/native code/.test(String(ji)),Wi=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},Ji=De,Ki=Wi,zi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},qi=Gi,Yi=C,Qi=Ie,Xi=zi,$i=G,Zi=L,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=Wi,gr=A,Tr=Tt,Er=G,Sr=xe,yr=Object.getOwnPropertyDescriptor;cr.f=pr?yr:function(e,t){if(e=gr(e),t=Tr(t),Sr)try{return yr(e,t)}catch(i){}if(Er(e,t))return fr(!mr(_r.f,e,t),e[t])};var Ir={},vr={get exports(){return Ir},set exports(e){Ir=e}},Ar=ke,Rr=G,Cr=Function.prototype,br=Ar&&Object.getOwnPropertyDescriptor,kr=Rr(Cr,"name"),Nr={EXISTS:kr,PROPER:kr&&"something"===function(){}.name,CONFIGURABLE:kr&&(!Ar||Ar&&br(Cr,"name").configurable)},Dr=Ee,wr=L,Or=c(Function.toString);Dr(wr.inspectSource)||(wr.inspectSource=function(e){return Or(e)});var Pr=wr.inspectSource,Lr=c,Mr=i,xr=Ee,Vr=G,Ur=ke,Fr=Nr.CONFIGURABLE,Br=Pr,Hr=ar.enforce,jr=ar.get,Gr=String,Wr=Object.defineProperty,Jr=Lr("".slice),Kr=Lr("".replace),zr=Lr([].join),qr=Ur&&!Mr((function(){return 8!==Wr((function(){}),"length",{value:8}).length})),Yr=String(String).split("String"),Qr=vr.exports=function(e,t,i){"Symbol("===Jr(Gr(t),0,7)&&(t="["+Kr(Gr(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Vr(e,"name")||Fr&&e.name!==t)&&(Ur?Wr(e,"name",{value:t,configurable:!0}):e.name=t),qr&&i&&Vr(i,"arity")&&e.length!==i.arity&&Wr(e,"length",{value:i.arity});try{i&&Vr(i,"constructor")&&i.constructor?Ur&&Wr(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(n){}var r=Hr(e);return Vr(r,"source")||(r.source=zr(Yr,"string"==typeof t?t:"")),e};Function.prototype.toString=Qr((function(){return xr(this)&&jr(this).source||Br(this)}),"toString");var Xr=Ee,$r=De,Zr=Ir,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=G,gn=_n,Tn=cr,En=De,Sn=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,In=Ee,vn=/#|\.prototype\./,An=function(e,t){var i=Cn[Rn(e)];return i==kn||i!=bn&&(In(t)?yn(t):!!t)},Rn=An.normalize=function(e){return String(e).replace(vn,".").toLowerCase()},Cn=An.data={},bn=An.NATIVE="N",kn=An.POLYFILL="P",Nn=An,Dn=C,wn=cr.f,On=zi,Pn=tn,Ln=w,Mn=Sn,xn=Nn,Vn=function(e,t){var i,r,n,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Dn:l?Dn[a]||Ln(a,{}):(Dn[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;Mn(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=G,Bn=Ee,Hn=B,jn=Un,Gn=fi("IE_PROTO"),Wn=Object,Jn=Wn.prototype,Kn=jn?Wn.getPrototypeOf:function(e){var t=Hn(e);if(Fn(t,Gn))return t[Gn];var i=t.constructor;return Bn(i)&&t instanceof i?i.prototype:t instanceof Wn?Jn:null},zn=i,qn=Ee,Yn=Ie,Qn=Kn,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)||zn((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=De.f,ro=G,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=Di,co=Wi,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){}},So=Ce,yo=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},Io=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 So(i),yo(r),t?e(i,r):i.__proto__=r,i}}():void 0),vo=Vn,Ao=Fe,Ro=Ee,Co=po,bo=Kn,ko=Io,No=oo,Do=zi,wo=tn,Oo=Bi,Po=Nr.PROPER,Lo=Nr.CONFIGURABLE,Mo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=_e("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,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)!==Mo&&(ko?ko(a,Mo):Ro(a[Vo])||wo(a,Vo,Ho)),No(a,u,!0)),Po&&n==Fo&&m&&m.name!==Fo&&(Lo?Do(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 vo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&wo(p,Vo,_,{name:n}),Oo[t]=_,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,Ko=Bi,zo=ar,qo=De.f,Yo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=zo.set,es=zo.getterFor($o),ts=Yo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,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=Ko.Arguments=Ko.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{qo(is,"name",{value:"values"})}catch(kF){}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=Le("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=zi,hs=_e,ps=hs("iterator"),ms=hs("toStringTag"),_s=ds.values,fs=function(e,t){if(e){if(e[ps]!==_s)try{us(e,ps,_s)}catch(kF){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(kF){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=Ir,Ss=De,ys=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},Is=je,vs=ys,As=ke,Rs=_e("species"),Cs=function(e){var t=Is(e);As&&t&&!t[Rs]&&vs(t,Rs,{configurable:!0,get:function(){return this}})},bs=Ge,ks=TypeError,Ns=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ds={};Ds[_e("toStringTag")]="z";var ws="[object z]"===String(Ds),Os=Ee,Ps=h,Ls=_e("toStringTag"),Ms=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(kF){}}(t=Ms(e),Ls))?i:xs?Ps(t):"Object"==(r=Ps(t))&&Os(t.callee)?"Arguments":r},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Pr,Gs=function(){},Ws=[],Js=je("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,zs=Us(Ks.exec),qs=!Ks.exec(Gs),Ys=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(kF){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return qs||!!zs(Ks,js(e))}catch(kF){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,Sa=r,ya=Ta(Ta.bind),Ia=function(e,t){return Ea(e),void 0===t?e:Sa?ya(e,t):function(){return e.apply(t,arguments)}},va=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,Na=Ia,Da=Ee,wa=G,Oa=i,Pa=pi,La=va,Ma=Le,xa=Ra,Va=Ca,Ua=Ts,Fa=ba.setImmediate,Ba=ba.clearImmediate,Ha=ba.process,ja=ba.Dispatch,Ga=ba.Function,Wa=ba.MessageChannel,Ja=ba.String,Ka=0,za={},qa="onreadystatechange";Oa((function(){Xs=ba.location}));var Ya=function(e){if(wa(za,e)){var t=za[e];delete za[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=Da(e)?e:Ga(e),i=La(arguments,1);return za[++Ka]=function(){ka(t,void 0,i)},$s(Ka),Ka},Ba=function(e){delete za[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Wa&&!Va?(ea=(Zs=new Wa).port2,Zs.port1.onmessage=Xa,$s=Na(ea.postMessage,ea)):ba.addEventListener&&Da(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!Oa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=qa in Ma("script")?function(e){Pa.appendChild(Ma("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=Ia,uc=cr.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,yc=lc.Promise,Ic=uc(lc,"queueMicrotask"),vc=Ic&&Ic.value;if(!vc){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch(kF){throw Ac.head&&tc(),kF}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(){Sc.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}),vc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=vc,bc=function(e){try{return{error:!1,value:e()}}catch(kF){return{error:!0,value:kF}}},kc=C.Promise,Nc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!Nc&&!Ts&&"object"==typeof window&&"object"==typeof document,wc=C,Oc=kc,Pc=Ee,Lc=Nn,Mc=Pr,xc=_e,Vc=Dc,Uc=Nc,Fc=ie;Oc&&Oc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(wc.PromiseRejectionEvent),Gc=Lc("Promise",(function(){var e=Mc(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})),Wc={CONSTRUCTOR:Gc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},Kc=et,zc=TypeError,qc=function(e){var t,i;this.promise=new e((function(e,r){if(void 0!==t||void 0!==i)throw zc("Bad Promise constructor");t=e,i=r})),this.resolve=Kc(t),this.reject=Kc(i)};Jc.f=function(e){return new qc(e)};var Yc,Qc,Xc,$c=Vn,Zc=Ts,el=C,tl=Fe,il=tn,rl=Io,nl=oo,ol=Cs,sl=et,al=Ee,cl=Ie,ll=Ns,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(kF){}},ml=bc,_l=sc,fl=ar,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,yl=Wc.REJECTION_EVENT,Il=Wc.SUBCLASSING,vl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Nl=el.document,Dl=el.process,wl=Tl.f,Ol=wl,Pl=!!(Nl&&Nl.createEvent&&el.dispatchEvent),Ll="unhandledrejection",Ml=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,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=Ml(i))?tl(r,i,c,l):c(i)):l(o)}catch(kF){d&&!n&&d.exit(),l(kF)}},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=Nl.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===Ll&&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?Dl.emit("unhandledRejection",r,i):Ul(Ll,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?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(r){e(t,r,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var r=Ml(t);r?hl((function(){var i={done:!1};try{tl(r,t,jl(Wl,i,e),jl(Gl,i,e))}catch(kF){Gl(i,kF,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(kF){Gl({done:!1},kF,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(Yc,this);var t=vl(this);try{e(jl(Wl,t),jl(Gl,t))}catch(kF){Gl(t,kF)}}).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=vl(this),r=wl(dl(this,Cl));return i.parent=!0,r.ok=!al(e)||e,r.fail=al(t)&&t,r.domain=Zc?Dl.domain:void 0,0==i.state?i.reactions.add(r):hl((function(){xl(r,i)})),r.promise})),Qc=function(){var e=new Yc,t=vl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=wl=function(e){return e===Cl||undefined===e?new Qc(e):Ol(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,Il||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(kF){}rl&&rl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),nl(Cl,El,!1),ol(El);var Jl=Bi,Kl=_e("iterator"),zl=Array.prototype,ql=function(e){return void 0!==e&&(Jl.Array===e||zl[Kl]===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(kF){n=!0,r=kF}if("throw"===t)throw i;if(n)throw r;return ld(r),i},hd=Ia,pd=Fe,md=Ce,_d=Qe,fd=ql,gd=Gt,Td=Ge,Ed=ad,Sd=ed,yd=ud,Id=TypeError,vd=function(e,t){this.stopped=e,this.result=t},Ad=vd.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 vd(!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=Sd(e)))throw Id(_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 vd(!1)}r=Ed(e,n)}for(c=h?e.next:r.next;!(l=pd(c,r)).done;){try{a=g(l.value)}catch(kF){yd(r,"throw",kF)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new vd(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Nd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Nd[Cd]=function(){return this},Array.from(Nd,(function(){throw 2}))}catch(kF){}var Dd=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(kF){}return i},wd=kc,Od=Wc.CONSTRUCTOR||!Dd((function(e){wd.all(e).then(void 0,(function(){}))})),Pd=Fe,Ld=et,Md=Jc,xd=bc,Vd=Rd;Vn({target:"Promise",stat:!0,forced:Od},{all:function(e){var t=this,i=Md.f(t),r=i.resolve,n=i.reject,o=xd((function(){var i=Ld(t.resolve),o=[],s=0,a=1;Vd(e,(function(e){var c=s++,l=!1;a++,Pd(i,t,e).then((function(e){l||(l=!0,o[c]=e,--a||r(o))}),n)})),--a||r(o)}));return o.error&&n(o.value),i.promise}});var Ud=Vn,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=tn,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var Kd=Fe,zd=et,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=zd(t.resolve);Qd(e,(function(e){Kd(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:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=Ie,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=Wc.CONSTRUCTOR,ou=iu;je("Promise"),ru({target:"Promise",stat:!0,forced:nu},{resolve:function(e){return ou(this,e)}});var su=Ee,au=Ie,cu=Io,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=Ie,uu=h,hu=_e("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},mu=Vs,_u=String,fu=function(e){if("Symbol"===mu(e))throw TypeError("Cannot convert a Symbol value to a string");return _u(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,yu=Ge,Iu=Tu,vu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in vu||Su(e,"flags")||!yu(vu,e)?t:Eu(Iu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Nu=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},wu=De.f,Ou=i,Pu=C.RegExp,Lu=Ou((function(){var e=Pu(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),Mu=i,xu=C.RegExp,Vu=Mu((function(){var e=xu("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),Uu=ke,Fu=C,Bu=c,Hu=Nn,ju=lu,Gu=zi,Wu=rn.f,Ju=Ge,Ku=pu,zu=fu,qu=Au,Yu=Du,Qu=function(e,t,i){i in e||wu(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=tn,$u=i,Zu=G,eh=ar.enforce,th=Cs,ih=Lu,rh=Vu,nh=_e("match"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu("".charAt),dh=Bu("".replace),uh=Bu("".indexOf),hh=Bu("".slice),ph=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,mh=/a/g,_h=/a/g,fh=new oh(mh)!==mh,gh=Yu.MISSED_STICKY,Th=Yu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||rh||$u((function(){return _h[nh]=!1,oh(mh)!=mh||oh(_h)==_h||"/a/i"!=oh(mh,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,r,n,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=qu(h))),e=void 0===e?"":zu(e),t=void 0===t?"":zu(t),h=e,ih&&"dotAll"in mh&&(r=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in mh&&(n=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),rh&&(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=lh(e,r)))t+=lh(e,++r);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,r+1))&&(r+=2,c=!0),n+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:n+=t}return[n,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(r||n||u.length)&&(a=eh(s),r&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,r=0,n="",o=!1;r<=i;r++)"\\"!==(t=lh(e,r))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),n+=t):n+="[\\s\\S]":n+=t+lh(e,++r);return n}(e),i)),n&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch(kF){}return s},yh=Wu(oh),Ih=0;yh.length>Ih;)Qu(Sh,oh,yh[Ih++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,"RegExp",Sh,{constructor:!0})}th("RegExp");var vh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=ar.get,Dh=Lu,wh=Vu,Oh=b("native-string-replace",String.prototype.replace),Ph=RegExp.prototype.exec,Lh=Ph,Mh=Ah("".charAt),xh=Ah("".indexOf),Vh=Ah("".replace),Uh=Ah("".slice),Fh=function(){var e=/a/,t=/b*/g;return vh(Ph,e,"a"),vh(Ph,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),Bh=bh.BROKEN_CARET,Hh=void 0!==/()??/.exec("")[1];(Fh||Hh||Bh||Dh||wh)&&(Lh=function(e){var t,i,r,n,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=vh(Lh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,m=vh(Ch,c),_=c.source,f=0,g=d;if(p&&(m=Vh(m,"y",""),-1===xh(m,"g")&&(m+="g"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Mh(d,c.lastIndex-1))&&(_="(?: "+_+")",g=" "+g,f++),i=new RegExp("^(?:"+_+")",m)),Hh&&(i=new RegExp("^"+_+"$(?!\\s)",m)),Fh&&(r=c.lastIndex),n=vh(Ph,p?i:c,g),p?n?(n.input=Uh(n.input,f),n[0]=Uh(n[0],f),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:Fh&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),Hh&&n&&n.length>1&&vh(Oh,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=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=n[a[1]];return n});var jh=Lh;Vn({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,Kh=ta,zh=Ie,qh=_e("species"),Yh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(Kh(t)&&(t===Yh||Jh(t.prototype))||zh(t)&&null===(t=t[qh]))&&(t=void 0)),void 0===t?Yh:t},Xh=Ia,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),rp=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=Zh(c),_=$h(m),f=Xh(l,d),g=ep(_),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:r||n?n:S}},np={forEach:rp(0),map:rp(1),filter:rp(2),some:rp(3),every:rp(4),find:rp(5),findIndex:rp(6),filterReject:rp(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=np.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=rs,up=ss,hp=cp,pp=zi,mp=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch(kF){e.forEach=hp}};for(var _p in dp)dp[_p]&&mp(lp[_p]&&lp[_p].prototype);mp(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,yp=function(e){return function(t,i,r,n){fp(i);var o=gp(t),s=Tp(o),a=Ep(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 Sp("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}},Ip={left:yp(!1),right:yp(!0)}.left;Vn({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return Ip(this,e,t,t>1?arguments[1]:void 0)}});var vp=Ta,Ap=tn,Rp=jh,Cp=i,bp=_e,kp=zi,Np=bp("species"),Dp=RegExp.prototype,wp=c,Op=Lt,Pp=fu,Lp=y,Mp=wp("".charAt),xp=wp("".charCodeAt),Vp=wp("".slice),Up=function(e){return function(t,i){var r,n,o=Pp(Lp(t)),s=Op(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=xp(o,s))<55296||r>56319||s+1===a||(n=xp(o,s+1))<56320||n>57343?e?Mp(o,s):r:e?Vp(o,s,s+2):n-56320+(r-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),Kp=Hp("".slice),zp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,Yp=function(e,t,i,r,n,o){var s=i+e.length,a=r.length,c=qp;return void 0!==n&&(n=jp(n),c=zp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return Kp(t,0,i);case"'":return Kp(t,s);case"<":l=n[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===r[u-1]?Wp(c,1):r[u-1]+Wp(c,1):o}l=r[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,em=jh,tm=TypeError,im=_a,rm=Fe,nm=c,om=function(e,t,i,r){var n=bp(e),o=!Cp((function(){var t={};return t[n]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags="",i[n]=/./[n]),i.exec=function(){return t=!0,null},i[n](""),!t}));if(!o||!s||i){var a=vp(/./[n]),c=t(n,""[e],(function(e,t,i,r,n){var s=vp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!n?{done:!0,value:a(t,i,r)}:{done:!0,value:s(i,t,r)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,n,c[1])}r&&kp(Dp[n],"sham",!0)},sm=i,am=Ce,cm=Ee,lm=T,dm=Lt,um=Ht,hm=fu,pm=y,mm=function(e,t,i){return t+(i?Bp(e,t).length:1)},_m=rt,fm=Yp,gm=function(e,t){var i=e.exec;if($p(i)){var r=Qp(i,e,t);return null!==r&&Xp(r),r}if("RegExp"===Zp(e))return Qp(em,e,t);throw tm("RegExp#exec called on incompatible receiver")},Tm=_e("replace"),Em=Math.max,Sm=Math.min,ym=nm([].concat),Im=nm([].push),vm=nm("".indexOf),Am=nm("".slice),Rm=function(e){return void 0===e?e:String(e)},Cm="$0"==="a".replace(/./,"$0"),bm=!!/./[Tm]&&""===/./[Tm]("a","$0"),km=!sm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));om("replace",(function(e,t,i){var r=bm?"$":"$0";return[function(e,i){var r=pm(this),n=lm(e)?void 0:_m(e,Tm);return n?rm(n,e,r,i):rm(t,hm(r),e,i)},function(e,n){var o=am(this),s=hm(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=cm(n);c||(n=hm(n));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=gm(o,s);if(null===h)break;if(Im(u,h),!l)break;""===hm(h[0])&&(o.lastIndex=mm(s,um(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=hm((h=u[_])[0]),g=Em(Sm(dm(h.index),s.length),0),T=[],E=1;E<h.length;E++)Im(T,Rm(h[E]));var S=h.groups;if(c){var y=ym([f],T,g,s);void 0!==S&&Im(y,S);var I=hm(im(n,void 0,y))}else I=fm(f,s,g,T,S,n);g>=m&&(p+=Am(s,m,g)+I,m=g+f.length)}return p+Am(s,m)}]}),!km||!Cm||bm);var Nm=qt.includes,Dm=Fi;Vn({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Nm(this,e,arguments.length>1?arguments[1]:void 0)}}),Dm("includes");var wm=Lt,Om=fu,Pm=y,Lm=RangeError,Mm=c,xm=Ht,Vm=fu,Um=function(e){var t=Om(Pm(this)),i="",r=wm(e);if(r<0||Infinity==r)throw Lm("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},Fm=y,Bm=Mm(Um),Hm=Mm("".slice),jm=Math.ceil,Gm=function(e){return function(t,i,r){var n,o,s=Vm(Fm(t)),a=xm(i),c=s.length,l=void 0===r?" ":Vm(r);return a<=c||""==l?s:((o=Bm(l,jm((n=a-c)/l.length))).length>n&&(o=Hm(o,0,n)),e?s+o:o+s)}},Wm={start:Gm(!1),end:Gm(!0)},Jm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Y),Km=Wm.start;Vn({target:"String",proto:!0,forced:Jm},{padStart:function(e){return Km(this,e,arguments.length>1?arguments[1]:void 0)}});var zm=i,qm=ke,Ym=_e("iterator"),Qm=!zm((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),i+=r+e})),!t.size&&!qm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Ym]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==i||"x"!==new URL("http://x",void 0).host})),Xm=tn,$m=function(e,t,i){for(var r in t)Xm(e,r,t[r],i);return e},Zm=Tt,e_=De,t_=Wi,i_=function(e,t,i){var r=Zm(t);r in e?e_.f(e,r,t_(0,i)):e[r]=i},r_=Ut,n_=Gt,o_=i_,s_=Array,a_=Math.max,c_=function(e,t,i){for(var r=n_(e),n=r_(t,r),o=r_(void 0===i?r:i,r),s=s_(a_(o-n,0)),a=0;n<o;n++,a++)o_(s,a,e[n]);return s.length=a,s},l_=c_,d_=Math.floor,u_=function(e,t){var i=e.length,r=d_(i/2);return i<8?h_(e,t):p_(e,u_(l_(e,0,r),t),u_(l_(e,r),t),t)},h_=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},p_=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},m_=u_,__=Vn,f_=C,g_=Fe,T_=c,E_=ke,S_=Qm,y_=tn,I_=ys,v_=$m,A_=oo,R_=po,C_=ar,b_=Ns,k_=Ee,N_=G,D_=Ia,w_=Vs,O_=Ce,P_=Ie,L_=fu,M_=Di,x_=Wi,V_=ad,U_=ed,F_=Ra,B_=m_,H_=_e("iterator"),j_="URLSearchParams",G_=j_+"Iterator",W_=C_.set,J_=C_.getterFor(j_),K_=C_.getterFor(G_),z_=Object.getOwnPropertyDescriptor,q_=function(e){if(!E_)return f_[e];var t=z_(f_,e);return t&&t.value},Y_=q_("fetch"),Q_=q_("Request"),X_=q_("Headers"),$_=Q_&&Q_.prototype,Z_=X_&&X_.prototype,ef=f_.RegExp,tf=f_.TypeError,rf=f_.decodeURIComponent,nf=f_.encodeURIComponent,of=T_("".charAt),sf=T_([].join),af=T_([].push),cf=T_("".replace),lf=T_([].shift),df=T_([].splice),uf=T_("".split),hf=T_("".slice),pf=/\+/g,mf=Array(4),_f=function(e){return mf[e-1]||(mf[e-1]=ef("((?:%[\\da-f]{2}){"+e+"})","gi"))},ff=function(e){try{return rf(e)}catch(kF){return e}},gf=function(e){var t=cf(e,pf," "),i=4;try{return rf(t)}catch(kF){for(;i;)t=cf(t,_f(i--),ff);return t}},Tf=/[!'()~]|%20/g,Ef={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Sf=function(e){return Ef[e]},yf=function(e){return cf(nf(e),Tf,Sf)},If=R_((function(e,t){W_(this,{type:G_,iterator:V_(J_(e).entries),kind:t})}),"Iterator",(function(){var e=K_(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&&(P_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===of(e,0)?hf(e,1):e:L_(e)))};vf.prototype={type:j_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,s,a,c=U_(e);if(c)for(i=(t=V_(e,c)).next;!(r=g_(i,t)).done;){if(o=(n=V_(O_(r.value))).next,(s=g_(o,n)).done||(a=g_(o,n)).done||!g_(o,n).done)throw tf("Expected sequence with length 2");af(this.entries,{key:L_(s.value),value:L_(a.value)})}else for(var l in e)N_(e,l)&&af(this.entries,{key:l,value:L_(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=uf(e,"&"),n=0;n<r.length;)(t=r[n++]).length&&(i=uf(t,"="),af(this.entries,{key:gf(lf(i)),value:gf(sf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],af(i,yf(e.key)+"="+yf(e.value));return sf(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Af=function(){b_(this,Rf);var e=W_(this,new vf(arguments.length>0?arguments[0]:void 0));E_||(this.length=e.entries.length)},Rf=Af.prototype;if(v_(Rf,{append:function(e,t){F_(arguments.length,2);var i=J_(this);af(i.entries,{key:L_(e),value:L_(t)}),E_||this.length++,i.updateURL()},delete:function(e){F_(arguments.length,1);for(var t=J_(this),i=t.entries,r=L_(e),n=0;n<i.length;)i[n].key===r?df(i,n,1):n++;E_||(this.length=i.length),t.updateURL()},get:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=L_(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=L_(e),r=[],n=0;n<t.length;n++)t[n].key===i&&af(r,t[n].value);return r},has:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=L_(e),r=0;r<t.length;)if(t[r++].key===i)return!0;return!1},set:function(e,t){F_(arguments.length,1);for(var i,r=J_(this),n=r.entries,o=!1,s=L_(e),a=L_(t),c=0;c<n.length;c++)(i=n[c]).key===s&&(o?df(n,c--,1):(o=!0,i.value=a));o||af(n,{key:s,value:a}),E_||(this.length=n.length),r.updateURL()},sort:function(){var e=J_(this);B_(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=D_(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 If(this,"keys")},values:function(){return new If(this,"values")},entries:function(){return new If(this,"entries")}},{enumerable:!0}),y_(Rf,H_,Rf.entries,{name:"entries"}),y_(Rf,"toString",(function(){return J_(this).serialize()}),{enumerable:!0}),E_&&I_(Rf,"size",{get:function(){return J_(this).entries.length},configurable:!0,enumerable:!0}),A_(Af,j_),__({global:!0,constructor:!0,forced:!S_},{URLSearchParams:Af}),!S_&&k_(X_)){var Cf=T_(Z_.has),bf=T_(Z_.set),kf=function(e){if(P_(e)){var t,i=e.body;if(w_(i)===j_)return t=e.headers?new X_(e.headers):new X_,Cf(t,"content-type")||bf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),M_(e,{body:x_(0,L_(i)),headers:x_(0,t)})}return e};if(k_(Y_)&&__({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return Y_(e,arguments.length>1?kf(arguments[1]):{})}}),k_(Q_)){var Nf=function(e){return b_(this,$_),new Q_(e,arguments.length>1?kf(arguments[1]):{})};$_.constructor=Nf,Nf.prototype=$_,__({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Nf})}}var Df={URLSearchParams:Af,getState:J_},wf="\t\n\v\f\r \u2028\u2029\ufeff",Of=y,Pf=fu,Lf=wf,Mf=c("".replace),xf=RegExp("^["+Lf+"]+"),Vf=RegExp("(^|[^"+Lf+"])["+Lf+"]+$"),Uf=function(e){return function(t){var i=Pf(Of(t));return 1&e&&(i=Mf(i,xf,"")),2&e&&(i=Mf(i,Vf,"$1")),i}},Ff={start:Uf(1),end:Uf(2),trim:Uf(3)},Bf=Nr.PROPER,Hf=i,jf=wf,Gf=Ff.trim;Vn({target:"String",proto:!0,forced:function(e){return Hf((function(){return!!jf[e]()||"
"!=="
"[e]()||Bf&&jf[e].name!==e}))}("trim")},{trim:function(){return Gf(this)}});var Wf=Vn,Jf=ke,Kf=c,zf=G,qf=Ee,Yf=Ge,Qf=fu,Xf=ys,$f=Sn,Zf=C.Symbol,eg=Zf&&Zf.prototype;if(Jf&&qf(Zf)&&(!("description"in eg)||void 0!==Zf().description)){var tg={},ig=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Qf(arguments[0]),t=Yf(eg,this)?new Zf(e):void 0===e?Zf():Zf(e);return""===e&&(tg[t]=!0),t};$f(ig,Zf),ig.prototype=eg,eg.constructor=ig;var rg="Symbol(test)"==String(Zf("test")),ng=Kf(eg.valueOf),og=Kf(eg.toString),sg=/^Symbol\((.*)\)[^)]+$/,ag=Kf("".replace),cg=Kf("".slice);Xf(eg,"description",{configurable:!0,get:function(){var e=ng(this);if(zf(tg,e))return"";var t=og(e),i=rg?cg(t,7,-1):ag(t,sg,"$1");return""===i?void 0:i}}),Wf({global:!0,constructor:!0,forced:!0},{Symbol:ig})}var lg=Fp.charAt,dg=fu,ug=ar,hg=jo,pg=Go,mg="String Iterator",_g=ug.set,fg=ug.getterFor(mg);hg(String,"String",(function(e){_g(this,{type:mg,string:dg(e),index:0})}),(function(){var e,t=fg(this),i=t.string,r=t.index;return r>=i.length?pg(void 0,!0):(e=lg(i,r),t.index+=e.length,pg(e,!1))}));var gg,Tg=ke,Eg=c,Sg=Fe,yg=i,Ig=oi,vg=sn,Ag=lr,Rg=B,Cg=g,bg=Object.assign,kg=Object.defineProperty,Ng=Eg([].concat),Dg=!bg||yg((function(){if(Tg&&1!==bg({b:1},bg(kg({},"a",{enumerable:!0,get:function(){kg(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!=bg({},e)[i]||Ig(bg({},t)).join("")!=r}))?function(e,t){for(var i=Rg(e),r=arguments.length,n=1,o=vg.f,s=Ag.f;r>n;)for(var a,c=Cg(arguments[n++]),l=o?Ng(Ig(c),o(c)):Ig(c),d=l.length,u=0;d>u;)a=l[u++],Tg&&!Sg(s,c,a)||(i[a]=c[a]);return i}:bg,wg=Ce,Og=ud,Pg=Ia,Lg=Fe,Mg=B,xg=function(e,t,i,r){try{return r?t(wg(i)[0],i[1]):t(i)}catch(kF){Og(e,"throw",kF)}},Vg=ql,Ug=ta,Fg=Gt,Bg=i_,Hg=ad,jg=ed,Gg=Array,Wg=c,Jg=2147483647,Kg=/[^\0-\u007E]/,zg=/[.\u3002\uFF0E\uFF61]/g,qg="Overflow: input needs wider integers to process",Yg=RangeError,Qg=Wg(zg.exec),Xg=Math.floor,$g=String.fromCharCode,Zg=Wg("".charCodeAt),eT=Wg([].join),tT=Wg([].push),iT=Wg("".replace),rT=Wg("".split),nT=Wg("".toLowerCase),oT=function(e){return e+22+75*(e<26)},sT=function(e,t,i){var r=0;for(e=i?Xg(e/700):e>>1,e+=Xg(e/t);e>455;)e=Xg(e/35),r+=36;return Xg(r+36*e/(e+38))},aT=function(e){var t=[];e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=Zg(e,i++);if(n>=55296&&n<=56319&&i<r){var o=Zg(e,i++);56320==(64512&o)?tT(t,((1023&n)<<10)+(1023&o)+65536):(tT(t,n),i--)}else tT(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&&tT(t,$g(r));var c=t.length,l=c;for(c&&tT(t,"-");l<n;){var d=Jg;for(i=0;i<e.length;i++)(r=e[i])>=o&&r<d&&(d=r);var u=l+1;if(d-o>Xg((Jg-s)/u))throw Yg(qg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((r=e[i])<o&&++s>Jg)throw Yg(qg);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;tT(t,$g(oT(m+_%f))),h=Xg(_/f),p+=36}tT(t,$g(oT(h))),a=sT(s,u,l==c),s=0,l++}}s++,o++}return eT(t,"")},cT=Vn,lT=ke,dT=Qm,uT=C,hT=Ia,pT=c,mT=tn,_T=ys,fT=Ns,gT=G,TT=Dg,ET=function(e){var t=Mg(e),i=Ug(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=Pg(n,r>2?arguments[2]:void 0));var s,a,c,l,d,u,h=jg(t),p=0;if(!h||this===Gg&&Vg(h))for(s=Fg(t),a=i?new this(s):Gg(s);s>p;p++)u=o?n(t[p],p):t[p],Bg(a,p,u);else for(d=(l=Hg(t,h)).next,a=i?new this:[];!(c=Lg(d,l)).done;p++)u=o?xg(l,n,[c.value,p],!0):c.value,Bg(a,p,u);return a.length=p,a},ST=c_,yT=Fp.codeAt,IT=function(e){var t,i,r=[],n=rT(iT(nT(e),zg,"."),".");for(t=0;t<n.length;t++)i=n[t],tT(r,Qg(Kg,i)?"xn--"+aT(i):i);return eT(r,".")},vT=fu,AT=oo,RT=Ra,CT=Df,bT=ar,kT=bT.set,NT=bT.getterFor("URL"),DT=CT.URLSearchParams,wT=CT.getState,OT=uT.URL,PT=uT.TypeError,LT=uT.parseInt,MT=Math.floor,xT=Math.pow,VT=pT("".charAt),UT=pT(/./.exec),FT=pT([].join),BT=pT(1..toString),HT=pT([].pop),jT=pT([].push),GT=pT("".replace),WT=pT([].shift),JT=pT("".split),KT=pT("".slice),zT=pT("".toLowerCase),qT=pT([].unshift),YT="Invalid scheme",QT="Invalid host",XT="Invalid port",$T=/[a-z]/i,ZT=/[\d+-.a-z]/i,eE=/\d/,tE=/^0x/i,iE=/^[0-7]+$/,rE=/^\d+$/,nE=/^[\da-f]+$/i,oE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,sE=/[\0\t\n\r #/:<>?@[\\\]^|]/,aE=/^[\u0000-\u0020]+/,cE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,lE=/[\t\n\r]/g,dE=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)qT(t,e%256),e=MT(e/256);return FT(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+=BT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},uE={},hE=TT({},uE,{" ":1,'"':1,"<":1,">":1,"`":1}),pE=TT({},hE,{"#":1,"?":1,"{":1,"}":1}),mE=TT({},pE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),_E=function(e,t){var i=yT(e,0);return i>32&&i<127&&!gT(t,e)?e:encodeURIComponent(e)},fE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},gE=function(e,t){var i;return 2==e.length&&UT($T,VT(e,0))&&(":"==(i=VT(e,1))||!t&&"|"==i)},TE=function(e){var t;return e.length>1&&gE(KT(e,0,2))&&(2==e.length||"/"===(t=VT(e,2))||"\\"===t||"?"===t||"#"===t)},EE=function(e){return"."===e||"%2e"===zT(e)},SE={},yE={},IE={},vE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},wE={},OE={},PE={},LE={},ME={},xE={},VE={},UE={},FE={},BE={},HE=function(e,t,i){var r,n,o,s=vT(e);if(t){if(n=this.parse(s))throw PT(n);this.searchParams=null}else{if(void 0!==i&&(r=new HE(i,!0)),n=this.parse(s,null,r))throw PT(n);(o=wT(new DT)).bindURL(this),this.searchParams=o}};HE.prototype={type:"URL",parse:function(e,t,i){var r,n,o,s,a,c=this,l=t||SE,d=0,u="",h=!1,p=!1,m=!1;for(e=vT(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=GT(e,aE,""),e=GT(e,cE,"$1")),e=GT(e,lE,""),r=ET(e);d<=r.length;){switch(n=r[d],l){case SE:if(!n||!UT($T,n)){if(t)return YT;l=IE;continue}u+=zT(n),l=yE;break;case yE:if(n&&(UT(ZT,n)||"+"==n||"-"==n||"."==n))u+=zT(n);else{if(":"!=n){if(t)return YT;u="",l=IE,d=0;continue}if(t&&(c.isSpecial()!=gT(fE,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&fE[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=PE:c.isSpecial()&&i&&i.scheme==c.scheme?l=vE:c.isSpecial()?l=bE:"/"==r[d+1]?(l=AE,d++):(c.cannotBeABaseURL=!0,jT(c.path,""),l=UE)}break;case IE:if(!i||i.cannotBeABaseURL&&"#"!=n)return YT;if(i.cannotBeABaseURL&&"#"==n){c.scheme=i.scheme,c.path=ST(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=BE;break}l="file"==i.scheme?PE:RE;continue;case vE:if("/"!=n||"/"!=r[d+1]){l=RE;continue}l=kE,d++;break;case AE:if("/"==n){l=NE;break}l=VE;continue;case RE:if(c.scheme=i.scheme,n==gg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query;else if("/"==n||"\\"==n&&c.isSpecial())l=CE;else if("?"==n)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query="",l=FE;else{if("#"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.path.length--,l=VE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ST(i.path),c.query=i.query,c.fragment="",l=BE}break;case CE:if(!c.isSpecial()||"/"!=n&&"\\"!=n){if("/"!=n){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=VE;continue}l=NE}else l=kE;break;case bE:if(l=kE,"/"!=n||"/"!=VT(u,d+1))continue;d++;break;case kE:if("/"!=n&&"\\"!=n){l=NE;continue}break;case NE:if("@"==n){h&&(u="%40"+u),h=!0,o=ET(u);for(var _=0;_<o.length;_++){var f=o[_];if(":"!=f||m){var g=_E(f,mE);m?c.password+=g:c.username+=g}else m=!0}u=""}else if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=ET(u).length+1,u="",l=DE}else u+=n;break;case DE:case wE:if(t&&"file"==c.scheme){l=ME;continue}if(":"!=n||p){if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()){if(c.isSpecial()&&""==u)return QT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=xE,t)return;continue}"["==n?p=!0:"]"==n&&(p=!1),u+=n}else{if(""==u)return QT;if(s=c.parseHost(u))return s;if(u="",l=OE,t==wE)return}break;case OE:if(!UT(eE,n)){if(n==gg||"/"==n||"?"==n||"#"==n||"\\"==n&&c.isSpecial()||t){if(""!=u){var T=LT(u,10);if(T>65535)return XT;c.port=c.isSpecial()&&T===fE[c.scheme]?null:T,u=""}if(t)return;l=xE;continue}return XT}u+=n;break;case PE:if(c.scheme="file","/"==n||"\\"==n)l=LE;else{if(!i||"file"!=i.scheme){l=VE;continue}if(n==gg)c.host=i.host,c.path=ST(i.path),c.query=i.query;else if("?"==n)c.host=i.host,c.path=ST(i.path),c.query="",l=FE;else{if("#"!=n){TE(FT(ST(r,d),""))||(c.host=i.host,c.path=ST(i.path),c.shortenPath()),l=VE;continue}c.host=i.host,c.path=ST(i.path),c.query=i.query,c.fragment="",l=BE}}break;case LE:if("/"==n||"\\"==n){l=ME;break}i&&"file"==i.scheme&&!TE(FT(ST(r,d),""))&&(gE(i.path[0],!0)?jT(c.path,i.path[0]):c.host=i.host),l=VE;continue;case ME:if(n==gg||"/"==n||"\\"==n||"?"==n||"#"==n){if(!t&&gE(u))l=VE;else if(""==u){if(c.host="",t)return;l=xE}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=xE}continue}u+=n;break;case xE:if(c.isSpecial()){if(l=VE,"/"!=n&&"\\"!=n)continue}else if(t||"?"!=n)if(t||"#"!=n){if(n!=gg&&(l=VE,"/"!=n))continue}else c.fragment="",l=BE;else c.query="",l=FE;break;case VE:if(n==gg||"/"==n||"\\"==n&&c.isSpecial()||!t&&("?"==n||"#"==n)){if(".."===(a=zT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==n||"\\"==n&&c.isSpecial()||jT(c.path,"")):EE(u)?"/"==n||"\\"==n&&c.isSpecial()||jT(c.path,""):("file"==c.scheme&&!c.path.length&&gE(u)&&(c.host&&(c.host=""),u=VT(u,0)+":"),jT(c.path,u)),u="","file"==c.scheme&&(n==gg||"?"==n||"#"==n))for(;c.path.length>1&&""===c.path[0];)WT(c.path);"?"==n?(c.query="",l=FE):"#"==n&&(c.fragment="",l=BE)}else u+=_E(n,pE);break;case UE:"?"==n?(c.query="",l=FE):"#"==n?(c.fragment="",l=BE):n!=gg&&(c.path[0]+=_E(n,uE));break;case FE:t||"#"!=n?n!=gg&&("'"==n&&c.isSpecial()?c.query+="%27":c.query+="#"==n?"%23":_E(n,uE)):(c.fragment="",l=BE);break;case BE:n!=gg&&(c.fragment+=_E(n,hE))}d++}},parseHost:function(e){var t,i,r;if("["==VT(e,0)){if("]"!=VT(e,e.length-1))return QT;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 VT(e,u)};if(":"==h()){if(":"!=VT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&UT(nE,h());)t=16*t+LT(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(!UT(eE,h()))return;for(;UT(eE,h());){if(o=LT(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}(KT(e,1,-1)),!t)return QT;this.host=t}else if(this.isSpecial()){if(e=IT(e),UT(oE,e))return QT;if(t=function(e){var t,i,r,n,o,s,a,c=JT(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"==VT(n,0)&&(o=UT(tE,n)?16:8,n=KT(n,8==o?1:2)),""===n)s=0;else{if(!UT(10==o?rE:8==o?iE:nE,n))return e;s=LT(n,o)}jT(i,s)}for(r=0;r<t;r++)if(s=i[r],r==t-1){if(s>=xT(256,5-t))return null}else if(s>255)return null;for(a=HT(i),r=0;r<i.length;r++)a+=i[r]*xT(256,3-r);return a}(e),null===t)return QT;this.host=t}else{if(UT(sE,e))return QT;for(t="",i=ET(e),r=0;r<i.length;r++)t+=_E(i[r],uE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return gT(fE,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&gE(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+=dE(n),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+FT(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw PT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new jE(e.path[0]).origin}catch(kF){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+dE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(vT(e)+":",SE)},getUsername:function(){return this.username},setUsername:function(e){var t=ET(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=_E(t[i],mE)}},getPassword:function(){return this.password},setPassword:function(e){var t=ET(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=_E(t[i],mE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?dE(e):dE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,DE)},getHostname:function(){var e=this.host;return null===e?"":dE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,wE)},getPort:function(){var e=this.port;return null===e?"":vT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=vT(e))?this.port=null:this.parse(e,OE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+FT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,xE))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=vT(e))?this.query=null:("?"==VT(e,0)&&(e=KT(e,1)),this.query="",this.parse(e,FE)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=vT(e))?("#"==VT(e,0)&&(e=KT(e,1)),this.fragment="",this.parse(e,BE)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var jE=function(e){var t=fT(this,GE),i=RT(arguments.length,1)>1?arguments[1]:void 0,r=kT(t,new HE(e,!1,i));lT||(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())},GE=jE.prototype,WE=function(e,t){return{get:function(){return NT(this)[e]()},set:t&&function(e){return NT(this)[t](e)},configurable:!0,enumerable:!0}};if(lT&&(_T(GE,"href",WE("serialize","setHref")),_T(GE,"origin",WE("getOrigin")),_T(GE,"protocol",WE("getProtocol","setProtocol")),_T(GE,"username",WE("getUsername","setUsername")),_T(GE,"password",WE("getPassword","setPassword")),_T(GE,"host",WE("getHost","setHost")),_T(GE,"hostname",WE("getHostname","setHostname")),_T(GE,"port",WE("getPort","setPort")),_T(GE,"pathname",WE("getPathname","setPathname")),_T(GE,"search",WE("getSearch","setSearch")),_T(GE,"searchParams",WE("getSearchParams")),_T(GE,"hash",WE("getHash","setHash"))),mT(GE,"toJSON",(function(){return NT(this).serialize()}),{enumerable:!0}),mT(GE,"toString",(function(){return NT(this).serialize()}),{enumerable:!0}),OT){var JE=OT.createObjectURL,KE=OT.revokeObjectURL;JE&&mT(jE,"createObjectURL",hT(JE,OT)),KE&&mT(jE,"revokeObjectURL",hT(KE,OT))}AT(jE,"URL"),cT({global:!0,constructor:!0,forced:!dT,sham:!lT},{URL:jE});var zE="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,qE=Lt,YE=Ht,QE=RangeError,XE=function(e){if(void 0===e)return 0;var t=qE(e),i=YE(t);if(t!==i)throw QE("Wrong length or index");return i},$E=Array,ZE=Math.abs,eS=Math.pow,tS=Math.floor,iS=Math.log,rS=Math.LN2,nS={pack:function(e,t,i){var r,n,o,s=$E(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?eS(2,-24)-eS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=ZE(e))!=e||Infinity===e?(n=e!=e?1:0,r=c):(r=tS(iS(e)/rS),e*(o=eS(2,-r))<1&&(r--,o*=2),(e+=r+l>=1?d/o:d*eS(2,1-l))*o>=2&&(r++,o/=2),r+l>=c?(n=0,r=c):r+l>=1?(n=(e*o-1)*eS(2,t),r+=l):(n=e*eS(2,l-1)*eS(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+=eS(2,t),d-=s}return(l?-1:1)*i*eS(2,d-t)}},oS=B,sS=Ut,aS=Gt,cS=function(e){for(var t=oS(this),i=aS(t),r=arguments.length,n=sS(r>1?arguments[1]:void 0,i),o=r>2?arguments[2]:void 0,s=void 0===o?i:sS(o,i);s>n;)t[n++]=e;return t},lS=C,dS=c,uS=ke,hS=zE,pS=Nr,mS=zi,_S=ys,fS=$m,gS=i,TS=Ns,ES=Lt,SS=Ht,yS=XE,IS=nS,vS=Kn,AS=Io,RS=rn.f,CS=cS,bS=c_,kS=oo,NS=ar,DS=pS.PROPER,wS=pS.CONFIGURABLE,OS="ArrayBuffer",PS="DataView",LS="prototype",MS="Wrong index",xS=NS.getterFor(OS),VS=NS.getterFor(PS),US=NS.set,FS=lS[OS],BS=FS,HS=BS&&BS[LS],jS=lS[PS],GS=jS&&jS[LS],WS=Object.prototype,JS=lS.Array,KS=lS.RangeError,zS=dS(CS),qS=dS([].reverse),YS=IS.pack,QS=IS.unpack,XS=function(e){return[255&e]},$S=function(e){return[255&e,e>>8&255]},ZS=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},ey=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},ty=function(e){return YS(e,23,4)},iy=function(e){return YS(e,52,8)},ry=function(e,t,i){_S(e[LS],t,{configurable:!0,get:function(){return i(this)[t]}})},ny=function(e,t,i,r){var n=yS(i),o=VS(e);if(n+t>o.byteLength)throw KS(MS);var s=o.bytes,a=n+o.byteOffset,c=bS(s,a,a+t);return r?c:qS(c)},oy=function(e,t,i,r,n,o){var s=yS(i),a=VS(e);if(s+t>a.byteLength)throw KS(MS);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(hS){var sy=DS&&FS.name!==OS;if(gS((function(){FS(1)}))&&gS((function(){new FS(-1)}))&&!gS((function(){return new FS,new FS(1.5),new FS(NaN),1!=FS.length||sy&&!wS})))sy&&wS&&mS(FS,"name",OS);else{(BS=function(e){return TS(this,HS),new FS(yS(e))})[LS]=HS;for(var ay,cy=RS(FS),ly=0;cy.length>ly;)(ay=cy[ly++])in BS||mS(BS,ay,FS[ay]);HS.constructor=BS}AS&&vS(GS)!==WS&&AS(GS,WS);var dy=new jS(new BS(2)),uy=dS(GS.setInt8);dy.setInt8(0,2147483648),dy.setInt8(1,2147483649),!dy.getInt8(0)&&dy.getInt8(1)||fS(GS,{setInt8:function(e,t){uy(this,e,t<<24>>24)},setUint8:function(e,t){uy(this,e,t<<24>>24)}},{unsafe:!0})}else HS=(BS=function(e){TS(this,HS);var t=yS(e);US(this,{type:OS,bytes:zS(JS(t),0),byteLength:t}),uS||(this.byteLength=t,this.detached=!1)})[LS],GS=(jS=function(e,t,i){TS(this,GS),TS(e,HS);var r=xS(e),n=r.byteLength,o=ES(t);if(o<0||o>n)throw KS("Wrong offset");if(o+(i=void 0===i?n-o:SS(i))>n)throw KS("Wrong length");US(this,{type:PS,buffer:e,byteLength:i,byteOffset:o,bytes:r.bytes}),uS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[LS],uS&&(ry(BS,"byteLength",xS),ry(jS,"buffer",VS),ry(jS,"byteLength",VS),ry(jS,"byteOffset",VS)),fS(GS,{getInt8:function(e){return ny(this,1,e)[0]<<24>>24},getUint8:function(e){return ny(this,1,e)[0]},getInt16:function(e){var t=ny(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ny(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return ey(ny(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return ey(ny(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return QS(ny(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return QS(ny(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){oy(this,1,e,XS,t)},setUint8:function(e,t){oy(this,1,e,XS,t)},setInt16:function(e,t){oy(this,2,e,$S,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){oy(this,2,e,$S,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){oy(this,4,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){oy(this,4,e,ZS,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){oy(this,4,e,ty,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){oy(this,8,e,iy,t,arguments.length>2?arguments[2]:void 0)}});kS(BS,OS),kS(jS,PS);var hy={ArrayBuffer:BS,DataView:jS},py=Vn,my=Ta,_y=i,fy=Ce,gy=Ut,Ty=Ht,Ey=da,Sy=hy.ArrayBuffer,yy=hy.DataView,Iy=yy.prototype,vy=my(Sy.prototype.slice),Ay=my(Iy.getUint8),Ry=my(Iy.setUint8);py({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:_y((function(){return!new Sy(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(vy&&void 0===t)return vy(fy(this),e);for(var i=fy(this).byteLength,r=gy(e,i),n=gy(void 0===t?i:t,i),o=new(Ey(this,Sy))(Ty(n-r)),s=new yy(this),a=new yy(o),c=0;r<n;)Ry(a,c++,Ay(s,r++));return o}});var Cy,by,ky,Ny={},Dy={get exports(){return Ny},set exports(e){Ny=e}},wy=zE,Oy=ke,Py=C,Ly=Ee,My=Ie,xy=G,Vy=Vs,Uy=Qe,Fy=zi,By=tn,Hy=ys,jy=Ge,Gy=Kn,Wy=Io,Jy=_e,Ky=q,zy=ar.enforce,qy=ar.get,Yy=Py.Int8Array,Qy=Yy&&Yy.prototype,Xy=Py.Uint8ClampedArray,$y=Xy&&Xy.prototype,Zy=Yy&&Gy(Yy),eI=Qy&&Gy(Qy),tI=Object.prototype,iI=Py.TypeError,rI=Jy("toStringTag"),nI=Ky("TYPED_ARRAY_TAG"),oI="TypedArrayConstructor",sI=wy&&!!Wy&&"Opera"!==Vy(Py.opera),aI=!1,cI={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},lI={BigInt64Array:8,BigUint64Array:8},dI=function(e){var t=Gy(e);if(My(t)){var i=qy(t);return i&&xy(i,oI)?i[oI]:dI(t)}},uI=function(e){if(!My(e))return!1;var t=Vy(e);return xy(cI,t)||xy(lI,t)};for(Cy in cI)(ky=(by=Py[Cy])&&by.prototype)?zy(ky)[oI]=by:sI=!1;for(Cy in lI)(ky=(by=Py[Cy])&&by.prototype)&&(zy(ky)[oI]=by);if((!sI||!Ly(Zy)||Zy===Function.prototype)&&(Zy=function(){throw iI("Incorrect invocation")},sI))for(Cy in cI)Py[Cy]&&Wy(Py[Cy],Zy);if((!sI||!eI||eI===tI)&&(eI=Zy.prototype,sI))for(Cy in cI)Py[Cy]&&Wy(Py[Cy].prototype,eI);if(sI&&Gy($y)!==eI&&Wy($y,eI),Oy&&!xy(eI,rI))for(Cy in aI=!0,Hy(eI,rI,{configurable:!0,get:function(){return My(this)?this[nI]:void 0}}),cI)Py[Cy]&&Fy(Py[Cy],nI,Cy);var hI={NATIVE_ARRAY_BUFFER_VIEWS:sI,TYPED_ARRAY_TAG:aI&&nI,aTypedArray:function(e){if(uI(e))return e;throw iI("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Ly(e)&&(!Wy||jy(Zy,e)))return e;throw iI(Uy(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(Oy){if(i)for(var n in cI){var o=Py[n];if(o&&xy(o.prototype,e))try{delete o.prototype[e]}catch(kF){try{o.prototype[e]=t}catch(s){}}}eI[e]&&!i||By(eI,e,i?t:sI&&Qy[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(Oy){if(Wy){if(i)for(r in cI)if((n=Py[r])&&xy(n,e))try{delete n[e]}catch(kF){}if(Zy[e]&&!i)return;try{return By(Zy,e,i?t:sI&&Zy[e]||t)}catch(kF){}}for(r in cI)!(n=Py[r])||n[e]&&!i||By(n,e,t)}},getTypedArrayConstructor:dI,isView:function(e){if(!My(e))return!1;var t=Vy(e);return"DataView"===t||xy(cI,t)||xy(lI,t)},isTypedArray:uI,TypedArray:Zy,TypedArrayPrototype:eI},pI=C,mI=i,_I=Dd,fI=hI.NATIVE_ARRAY_BUFFER_VIEWS,gI=pI.ArrayBuffer,TI=pI.Int8Array,EI=!fI||!mI((function(){TI(1)}))||!mI((function(){new TI(-1)}))||!_I((function(e){new TI,new TI(null),new TI(1.5),new TI(e)}),!0)||mI((function(){return 1!==new TI(new gI(2),1,void 0).length})),SI=Ie,yI=Math.floor,II=Number.isInteger||function(e){return!SI(e)&&isFinite(e)&&yI(e)===e},vI=Lt,AI=RangeError,RI=function(e){var t=vI(e);if(t<0)throw AI("The argument can't be less than 0");return t},CI=RangeError,bI=function(e,t){var i=RI(e);if(i%t)throw CI("Wrong offset");return i},kI=Vs,NI=_t,DI=TypeError,wI=function(e){var t=NI(e,"number");if("number"==typeof t)throw DI("Can't convert number to bigint");return BigInt(t)},OI=Ia,PI=Fe,LI=oa,MI=B,xI=Gt,VI=ad,UI=ed,FI=ql,BI=function(e){var t=kI(e);return"BigInt64Array"==t||"BigUint64Array"==t},HI=hI.aTypedArrayConstructor,jI=wI,GI=function(e){var t,i,r,n,o,s,a,c,l=LI(this),d=MI(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=UI(d);if(m&&!FI(m))for(c=(a=VI(d,m)).next,d=[];!(s=PI(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=OI(h,arguments[2])),i=xI(d),r=new(HI(l))(i),n=BI(r),t=0;i>t;t++)o=p?h(d[t],t):d[t],r[t]=n?jI(o):+o;return r},WI=Vn,JI=C,KI=Fe,zI=ke,qI=EI,YI=hI,QI=hy,XI=Ns,$I=Wi,ZI=zi,ev=II,tv=Ht,iv=XE,rv=bI,nv=Tt,ov=G,sv=Vs,av=Ie,cv=qe,lv=Di,dv=Ge,uv=Io,hv=rn.f,pv=GI,mv=np.forEach,_v=Cs,fv=ys,gv=De,Tv=cr,Ev=lu,Sv=ar.get,yv=ar.set,Iv=ar.enforce,vv=gv.f,Av=Tv.f,Rv=Math.round,Cv=JI.RangeError,bv=QI.ArrayBuffer,kv=bv.prototype,Nv=QI.DataView,Dv=YI.NATIVE_ARRAY_BUFFER_VIEWS,wv=YI.TYPED_ARRAY_TAG,Ov=YI.TypedArray,Pv=YI.TypedArrayPrototype,Lv=YI.aTypedArrayConstructor,Mv=YI.isTypedArray,xv="BYTES_PER_ELEMENT",Vv="Wrong length",Uv=function(e,t){Lv(e);for(var i=0,r=t.length,n=new e(r);r>i;)n[i]=t[i++];return n},Fv=function(e,t){fv(e,t,{configurable:!0,get:function(){return Sv(this)[t]}})},Bv=function(e){var t;return dv(kv,e)||"ArrayBuffer"==(t=sv(e))||"SharedArrayBuffer"==t},Hv=function(e,t){return Mv(e)&&!cv(t)&&t in e&&ev(+t)&&t>=0},jv=function(e,t){return t=nv(t),Hv(e,t)?$I(2,e[t]):Av(e,t)},Gv=function(e,t,i){return t=nv(t),!(Hv(e,t)&&av(i)&&ov(i,"value"))||ov(i,"get")||ov(i,"set")||i.configurable||ov(i,"writable")&&!i.writable||ov(i,"enumerable")&&!i.enumerable?vv(e,t,i):(e[t]=i.value,e)};zI?(Dv||(Tv.f=jv,gv.f=Gv,Fv(Pv,"buffer"),Fv(Pv,"byteOffset"),Fv(Pv,"byteLength"),Fv(Pv,"length")),WI({target:"Object",stat:!0,forced:!Dv},{getOwnPropertyDescriptor:jv,defineProperty:Gv}),Dy.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=JI[n],c=a,l=c&&c.prototype,d={},u=function(e,t){vv(e,t,{get:function(){return function(e,t){var i=Sv(e);return i.view[o](t*r+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,n){var o=Sv(e);i&&(n=(n=Rv(n))<0?0:n>255?255:255&n),o.view[s](t*r+o.byteOffset,n,!0)}(this,t,e)},enumerable:!0})};Dv?qI&&(c=t((function(e,t,i,n){return XI(e,l),Ev(av(t)?Bv(t)?void 0!==n?new a(t,rv(i,r),n):void 0!==i?new a(t,rv(i,r)):new a(t):Mv(t)?Uv(c,t):KI(pv,c,t):new a(iv(t)),e,c)})),uv&&uv(c,Ov),mv(hv(a),(function(e){e in c||ZI(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,n){XI(e,l);var o,s,a,d=0,h=0;if(av(t)){if(!Bv(t))return Mv(t)?Uv(c,t):KI(pv,c,t);o=t,h=rv(i,r);var p=t.byteLength;if(void 0===n){if(p%r)throw Cv(Vv);if((s=p-h)<0)throw Cv(Vv)}else if((s=tv(n)*r)+h>p)throw Cv(Vv);a=s/r}else a=iv(t),o=new bv(s=a*r);for(yv(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Nv(o)});d<a;)u(e,d++)})),uv&&uv(c,Ov),l=c.prototype=lv(Pv)),l.constructor!==c&&ZI(l,"constructor",c),Iv(l).TypedArrayConstructor=c,wv&&ZI(l,wv,n);var h=c!=a;d[n]=c,WI({global:!0,constructor:!0,forced:h,sham:!Dv},d),xv in c||ZI(c,xv,r),xv in l||ZI(l,xv,r),_v(n)}):Dy.exports=function(){},Ny("Uint8",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var Wv=cS,Jv=wI,Kv=Vs,zv=Fe,qv=i,Yv=hI.aTypedArray,Qv=hI.exportTypedArrayMethod,Xv=c("".slice);Qv("fill",(function(e){var t=arguments.length;Yv(this);var i="Big"===Xv(Kv(this),0,3)?Jv(e):+e;return zv(Wv,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),qv((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var $v=C,Zv=Fe,eA=hI,tA=Gt,iA=bI,rA=B,nA=i,oA=$v.RangeError,sA=$v.Int8Array,aA=sA&&sA.prototype,cA=aA&&aA.set,lA=eA.aTypedArray,dA=eA.exportTypedArrayMethod,uA=!nA((function(){var e=new Uint8ClampedArray(2);return Zv(cA,e,{length:1,0:3},1),3!==e[1]})),hA=uA&&eA.NATIVE_ARRAY_BUFFER_VIEWS&&nA((function(){var e=new sA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));dA("set",(function(e){lA(this);var t=iA(arguments.length>1?arguments[1]:void 0,1),i=rA(e);if(uA)return Zv(cA,this,i,t);var r=this.length,n=tA(i),o=0;if(n+t>r)throw oA("Wrong length");for(;o<n;)this[t+o]=i[o++]}),!uA||hA);var pA=Y.match(/firefox\/(\d+)/i),mA=!!pA&&+pA[1],_A=/MSIE|Trident/.test(Y),fA=Y.match(/AppleWebKit\/(\d+)\./),gA=!!fA&&+fA[1],TA=Ta,EA=i,SA=et,yA=m_,IA=mA,vA=_A,AA=ie,RA=gA,CA=hI.aTypedArray,bA=hI.exportTypedArrayMethod,kA=C.Uint16Array,NA=kA&&TA(kA.prototype.sort),DA=!(!NA||EA((function(){NA(new kA(2),null)}))&&EA((function(){NA(new kA(2),{})}))),wA=!!NA&&!EA((function(){if(AA)return AA<74;if(IA)return IA<67;if(vA)return!0;if(RA)return RA<602;var e,t,i=new kA(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(NA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==r[e])return!0}));bA("sort",(function(e){return void 0!==e&&SA(e),wA?NA(this,e):yA(CA(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))}),!wA||DA);var OA=Vn,PA=kc,LA=i,MA=je,xA=Ee,VA=da,UA=iu,FA=tn,BA=PA&&PA.prototype;if(OA({target:"Promise",proto:!0,real:!0,forced:!!PA&&LA((function(){BA.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=VA(this,MA("Promise")),i=xA(e);return this.then(i?function(i){return UA(t,e()).then((function(){return i}))}:e,i?function(i){return UA(t,e()).then((function(){throw i}))}:e)}}),xA(PA)){var HA=MA("Promise").prototype.finally;BA.finally!==HA&&FA(BA,"finally",HA,{unsafe:!0})}var jA=Cs,GA="ArrayBuffer",WA=hy[GA];Vn({global:!0,constructor:!0,forced:C[GA]!==WA},{ArrayBuffer:WA}),jA(GA);var JA=Qe,KA=TypeError,zA=Vn,qA=c,YA=et,QA=B,XA=Gt,$A=function(e,t){if(!delete e[t])throw KA("Cannot delete property "+JA(t)+" of "+JA(e))},ZA=fu,eR=i,tR=m_,iR=sp,rR=mA,nR=_A,oR=ie,sR=gA,aR=[],cR=qA(aR.sort),lR=qA(aR.push),dR=eR((function(){aR.sort(void 0)})),uR=eR((function(){aR.sort(null)})),hR=iR("sort"),pR=!eR((function(){if(oR)return oR<70;if(!(rR&&rR>3)){if(nR)return!0;if(sR)return sR<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++)aR.push({k:t+r,v:i})}for(aR.sort((function(e,t){return t.v-e.v})),r=0;r<aR.length;r++)t=aR[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}}));zA({target:"Array",proto:!0,forced:dR||!uR||!hR||!pR},{sort:function(e){void 0!==e&&YA(e);var t=QA(this);if(pR)return void 0===e?cR(t):cR(t,e);var i,r,n=[],o=XA(t);for(r=0;r<o;r++)r in t&&lR(n,t[r]);for(tR(n,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:ZA(t)>ZA(i)?1:-1}}(e)),i=XA(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)$A(t,r++);return t}}),Ny("Float32",(function(e){return function(t,i,r){return e(this,t,i,r)}}));var mR=Vn,_R=Wh,fR=c([].reverse),gR=[1,2];mR({target:"Array",proto:!0,forced:String(gR)===String(gR.reverse())},{reverse:function(){return _R(this)&&(this.length=this.length),fR(this)}});var TR=Vn,ER=Fe,SR=c,yR=y,IR=Ee,vR=T,AR=pu,RR=fu,CR=rt,bR=Au,kR=Yp,NR=_e("replace"),DR=TypeError,wR=SR("".indexOf);SR("".replace);var OR=SR("".slice),PR=Math.max,LR=function(e,t,i){return i>e.length?-1:""===t?i:wR(e,t,i)};TR({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,s,a,c,l,d=yR(this),u=0,h=0,p="";if(!vR(e)){if(AR(e)&&(i=RR(yR(bR(e))),!~wR(i,"g")))throw DR("`.replaceAll` does not allow non-global regexes");if(r=CR(e,NR))return ER(r,e,d,t)}for(n=RR(d),o=RR(e),(s=IR(t))||(t=RR(t)),a=o.length,c=PR(1,a),u=LR(n,o,0);-1!==u;)l=s?RR(t(o,u,n)):kR(o,n,u,[],void 0,t),p+=OR(n,h,u)+l,h=u+a,u=LR(n,o,u+c);return h<n.length&&(p+=OR(n,h)),p}}),(0,hI.exportTypedArrayStaticMethod)("from",GI,EI);let MR=!0,xR=!0;function VR(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function UR(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 FR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(MR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function BR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(xR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function HR(){if("object"==typeof window){if(MR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function jR(e,t){xR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function GR(e){return"[object Object]"===Object.prototype.toString.call(e)}function WR(e){return GR(e)?Object.keys(e).reduce((function(t,i){const r=GR(e[i]),n=r?WR(e[i]):e[i],o=r&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[i]:n})}),{}):e}function JR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((r=>{r.endsWith("Id")?JR(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach((t=>{JR(e,e.get(t),i)}))})))}function KR(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&&JR(e,i,n)}))})),n}const zR=HR;function qR(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),zR("chrome: "+JSON.stringify(e)),n(e)}))}e.video=r(e.video)}return zR("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 YR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function QR(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 UR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function XR(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 $R(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 ZR(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=>KR(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}),UR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>KR(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 eC(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 tC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return eC(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 iC(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 rC(e,t){UR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var nC=Object.freeze({__proto__:null,shimMediaStream:YR,shimOnTrack:QR,shimGetSendersWithDtmf:XR,shimGetStats:$R,shimSenderReceiverGetStats:ZR,shimAddTrackRemoveTrackWithNative:eC,shimAddTrackRemoveTrack:tC,shimPeerConnection:iC,fixNegotiationNeeded:rC,shimGetUserMedia:qR,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 oC(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){jR("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 sC(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 aC(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(wb){if("TypeError"!==wb.name)throw wb;e.forEach(((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(n,o)}}function cC(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 lC(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}),UR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function dC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){jR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function uC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function hC(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 pC(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 mC(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 _C(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 fC=Object.freeze({__proto__:null,shimOnTrack:sC,shimPeerConnection:aC,shimSenderGetStats:cC,shimReceiverGetStats:lC,shimRemoveStream:dC,shimRTCDataChannel:uC,shimAddTransceiver:hC,shimGetParameters:pC,shimCreateOffer:mC,shimCreateAnswer:_C,shimGetUserMedia:oC,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 gC(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 TC(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 EC(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 SC(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(yC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}.bind(t))}function yC(e){return e&&void 0!==e.video?Object.assign({},e,{video:WR(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?(jR("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 vC(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 AC(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 RC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var CC=Object.freeze({__proto__:null,shimLocalStreamsAPI:gC,shimRemoteStreamsAPI:TC,shimCallbacksAPI:EC,shimGetUserMedia:SC,shimConstraints:yC,shimRTCIceServerUrls:IC,shimTrackEventTransceiver:vC,shimCreateOfferLegacy:AC,shimAudioContext:RC}),bC={},kC={get exports(){return bC},set exports(e){bC=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}(kC);var NC=bC,DC=e({__proto__:null,default:NC},[bC]);function wC(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=NC.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,UR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function OC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||UR(e,"icecandidate",(e=>{if(e.candidate){const t=NC.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=NC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=NC.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=NC.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 LC(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},UR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function MC(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 xC(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 VC(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 UC(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 FC=Object.freeze({__proto__:null,shimRTCIceCandidate:wC,shimRTCIceCandidateRelayProtocol:OC,shimMaxMessageSize:PC,shimSendThrowTypeError:LC,shimConnectionState:MC,removeExtmapAllowMixed:xC,shimAddIceCandidateNullOrEmpty:VC,shimParameterlessSetLocalDescription:UC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=HR,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=VR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=VR(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=VR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:r,commonShim:FC,extractVersion:VR,disableLog:FR,disableWarnings:BR,sdp:DC};switch(r.browser){case"chrome":if(!nC||!iC||!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=nC,VC(e,r),UC(e),qR(e,r),YR(e),iC(e,r),QR(e),tC(e,r),XR(e),$R(e),ZR(e),rC(e,r),wC(e),OC(e),MC(e),PC(e,r),LC(e),xC(e,r);break;case"firefox":if(!fC||!aC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=fC,VC(e,r),UC(e),oC(e,r),aC(e,r),sC(e),dC(e),cC(e),lC(e),uC(e),hC(e),pC(e),mC(e),_C(e),wC(e),MC(e),PC(e,r),LC(e);break;case"safari":if(!CC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=CC,VC(e,r),UC(e),IC(e),AC(e),EC(e),gC(e),TC(e),vC(e),SC(e),RC(e),wC(e),OC(e),PC(e,r),LC(e),xC(e,r);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var BC,HC=Object.create,jC=Object.defineProperty,GC=Object.defineProperties,WC=Object.getOwnPropertyDescriptor,JC=Object.getOwnPropertyDescriptors,KC=Object.getOwnPropertyNames,zC=Object.getOwnPropertySymbols,qC=Object.getPrototypeOf,YC=Object.prototype.hasOwnProperty,QC=Object.prototype.propertyIsEnumerable,XC=Reflect.get,$C=Math.pow,ZC=(e,t,i)=>t in e?jC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,eb=(e,t)=>{for(var i in t||(t={}))YC.call(t,i)&&ZC(e,i,t[i]);if(zC)for(var i of zC(t))QC.call(t,i)&&ZC(e,i,t[i]);return e},tb=(e,t)=>GC(e,JC(t)),ib=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),rb=(e,t)=>{for(var i in t)jC(e,i,{get:t[i],enumerable:!0})},nb=(e,t,i)=>(i=null!=e?HC(qC(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of KC(t))!YC.call(e,n)&&n!==i&&jC(e,n,{get:()=>t[n],enumerable:!(r=WC(t,n))||r.enumerable});return e})(!t&&e&&e.__esModule?i:jC(i,"default",{value:e,enumerable:!0}),e)),ob=(e,t,i,r)=>{for(var n,o=r>1?void 0:r?WC(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&&jC(t,i,o),o},sb=(e,t,i)=>(ZC(e,"symbol"!=typeof t?t+"":t,i),i),ab=(e,t,i)=>XC(qC(e),i,t),cb=(e,t,i)=>new Promise(((r,n)=>{var o=e=>{try{a(i.next(e))}catch(t){n(t)}},s=e=>{try{a(i.throw(e))}catch(t){n(t)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),lb=ib(((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)})),db=ib(((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")}))}))})),ub=ib((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=db(),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}}))}))}})),hb=ib(((e,t)=>{var i=db(),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"}})),pb=ib((e=>{var t=ub(),i=hb();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})),mb=ib(((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")}))}))})),_b=ib((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=mb(),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}}))}))}})),fb=ib(((e,t)=>{var i=mb(),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"}})),gb=ib((e=>{var t=_b(),i=fb();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})),Tb=nb(lb()),Eb=((BC=Eb||{})[BC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",BC[BC.INVALID_OPERATION=4097]="INVALID_OPERATION",BC[BC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",BC[BC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",BC[BC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",BC[BC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",BC[BC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",BC[BC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",BC[BC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",BC[BC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",BC[BC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",BC[BC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",BC[BC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",BC[BC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",BC[BC.CLIENT_BANNED=16448]="CLIENT_BANNED",BC[BC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",BC[BC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",BC[BC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",BC[BC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",BC[BC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",BC[BC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",BC[BC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",BC[BC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",BC[BC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",BC[BC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",BC[BC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",BC[BC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",BC[BC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",BC[BC.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",BC[BC.UNKNOWN=65535]="UNKNOWN",BC),Sb=Eb,yb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=Sb.UNKNOWN,extraCode:n=0,constraint:o}=e,s="<".concat(function(e){for(let t in Sb)if(Sb[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),sb(this,"code"),sb(this,"extraCode"),sb(this,"message"),sb(this,"originMessage"),sb(this,"name"),sb(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=yb,vb=((new Date).getTime(),0),Ab=function(){return(new Date).getTime()+vb},Rb=function(){let e=new Date;return e.setTime(Ab()),e.toLocaleString()},Cb={};rb(Cb,{bytes2ms:()=>Aw,convertObjectNumberToInt:()=>mO,copyProperties:()=>vw,deepClone:()=>rO,deepMerge:()=>iO,fibonacci:()=>ww,formatedTime:()=>aO,getAbilityConfigUrl:()=>uw,getConstructorName:()=>Jw,getContainerFromElement:()=>oO,getEnv:()=>_w,getInternalVersion:()=>Qw,getLoggerUrl:()=>gw,getMuteStateFromFlag:()=>Zw,getNetworkType:()=>Ew,getNumNetworkType:()=>Iw,getReconnectionTimeout:()=>Ow,getStringByteLength:()=>dO,getTurnServer:()=>eO,getUint32Version:()=>pO,getValueType:()=>Pw,getViewListFromView:()=>nO,glog:()=>kw,ipv4ToUint32:()=>tO,isArray:()=>Bw,isAudioWorkletSupported:()=>Kw,isBoolean:()=>Uw,isConstructor:()=>Ww,isEmpty:()=>$w,isFunction:()=>Lw,isLangChinese:()=>Nw,isMediaStreamTrack:()=>Hw,isNumber:()=>Vw,isObject:()=>Fw,isOverseaSdkAppId:()=>fw,isPlainObject:()=>Dw,isPortrait:()=>uO,isPromise:()=>Gw,isRemoteTrack:()=>jw,isString:()=>xw,isUndefined:()=>Mw,loadImage:()=>hO,ms2bytes:()=>Cw,ms2samples:()=>bw,performanceNow:()=>qw,promiseAny:()=>zw,samples2ms:()=>Rw,setNetworkType:()=>yw,stringify:()=>cO,stringifyIncludeValue:()=>lO});var bb={};rb(bb,{AUDIO_MUTE_BIT:()=>pk,AUDIO_STAT_BIT:()=>hk,AUX_STAT_BIT:()=>uk,AUX_STREAM_MSID:()=>fk,BACKEND_ENV:()=>ak,BASE_DOC_URL:()=>Gb,BASE_HOST:()=>Fb,CAPABILITIES_KEYS:()=>aN,CLASS_NAME:()=>qk,CLOUD_CONSOLE_URL:()=>jb,DATA_FREEZE_TIMING:()=>Hk,DOC_URL:()=>Wb,DTLS_STATE_UNKNOWN:()=>Ck,ENV_NAME:()=>Yb,EXCHANGE_SDP_TIMEOUT:()=>xk,INTERVAL:()=>oN,IS_WORKER:()=>Lb,IS_WORKLET:()=>Mb,KIBANA_EVENT:()=>Pk,LOCAL_STREAM_PUBLISH_STATE:()=>Bk,LOGGER_CMD_TYPE:()=>qb,LOGGER_DOMAIN:()=>Jb,LOGGER_DOMAIN_OVERSEA:()=>Kb,LOG_LEVEL:()=>Qb,LOG_LEVEL_NAME:()=>Zk,MAIN_STREAM_MSID:()=>_k,MICROPHONE_COMMUNICATIONS:()=>$k,MICROPHONE_DEFAULT:()=>Qk,NAME:()=>ok,NETWORK_TYPE:()=>Zb,NOT_SUPPORTED_H264:()=>Fk,PAUSED_RETRY_COUNT:()=>Yk,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Jk,PEER_CONNECTION_STATE:()=>bk,PEER_LEAVE_REASON:()=>eN,RAF:()=>nN,RECOVER_CAPTURE_INTERVAL:()=>iN,REMOTE_STREAM_TYPE_AUX:()=>Tk,REMOTE_STREAM_TYPE_MAIN:()=>gk,RENDER_FREEZE_TIMING:()=>jk,RIC:()=>rN,SCHEDULE_DOMAIN:()=>Kk,SCHEDULE_TIMEOUT:()=>zk,SDP_SEMANTICS_PLAN_B:()=>Uk,SDP_SEMANTICS_UNIFIED_PLAN:()=>Vk,SECOND_HOST:()=>Bb,SIGNAL_PING_PONG_INTERVAL:()=>$b,SIGNAL_PING_TIMEOUT:()=>Xb,SIGNAL_RECONNECTION_COUNT:()=>Ok,SMALL_STAT_BIT:()=>dk,SPEAKER_DEFAULT:()=>Xk,STORAGE_EXPIRES_TIME:()=>ek,STREAM_TYPE_BIG:()=>Gk,STREAM_TYPE_SMALL:()=>Wk,SUBSCRIBE_SMALL_RETRY_COUNT:()=>tN,SYNC_USER_LIST_INTERVAL:()=>Lk,Scene:()=>ck,Switch:()=>tk,THIRD_HOST:()=>Hb,TIMEOUT:()=>sN,TRANSPORT_DIRECTION:()=>sk,TRTC_ERROR_ASSISTANCE:()=>zb,TRTC_QUALITY_BAD:()=>vk,TRTC_QUALITY_DISCONNECTED:()=>Rk,TRTC_QUALITY_EXCELLENT:()=>Sk,TRTC_QUALITY_GOOD:()=>yk,TRTC_QUALITY_POOR:()=>Ik,TRTC_QUALITY_UNKNOWN:()=>Ek,TRTC_QUALITY_VERY_BAD:()=>Ak,UPDATE_OFFER_TIMEOUT:()=>Mk,VIDEO_MUTE_BIT:()=>mk,VIDEO_STAT_BIT:()=>lk,audioProfileMap:()=>ik,getRetryCount:()=>Dk,getScriptDir:()=>xb,innerVersion:()=>kb,loggerProxy:()=>Vb,screenProfileMap:()=>nk,setLoggerProxy:()=>Ub,setRetryCount:()=>Nk,setVersion:()=>Db,version:()=>Nb,videoProfileMap:()=>rk});var kb="4.15.00.1600",Nb="5.0.0";function Db(e){Nb=e;let[t,i,r]=e.split(".").map((e=>parseInt(e,10)));kb="".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 wb,Ob,Pb,Lb="undefined"!=typeof importScripts,Mb="undefined"!=typeof registerProcessor,xb=()=>{let e=Lb?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Vb="",Ub=e=>Vb=e,Fb="web.sdk.qcloud.com",Bb="web.sdk.tencent.cn",Hb="web.sdk.cloud.tencent.cn",jb="https://console.cloud.tencent.com/trtc",Gb="https://".concat(Fb,"/trtc/webrtc/v5/doc"),Wb="".concat(Gb,"/zh-cn/"),Jb="https://yun.tim.qq.com",Kb="https://apisgp.my-imcloud.com",zb="trtc_error_assistance",qb={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Yb={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Qb=((Pb=Qb||{})[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),Xb=18e3,$b=2e3,Zb={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ek=6048e5,tk=((Ob=tk||{}).USEAINS="useAINS",Ob.ENABLEDEBUG="enableDebug",Ob.USEV2="useV2",Ob.USEWT="useWt",Ob),ik={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}},rk={"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}},nk={"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}},ok={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"},sk={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ak={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ck=((wb=ck||{}).LIVE="live",wb.RTC="rtc",wb),lk=1,dk=2,uk=4,hk=8,pk=64,mk=16,_k="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",fk="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",gk=ok.MAIN,Tk=ok.AUXILIARY,Ek=0,Sk=1,yk=2,Ik=3,vk=4,Ak=5,Rk=6,Ck="unknown",bk={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},kk=1/0;function Nk(e){kk=e}function Dk(){return kk}var wk,Ok=30,Pk={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"},Lk=1e4,Mk=1e4,xk=1e4,Vk="unified-plan",Uk="plan-b",Fk=1028,Bk=((wk=Bk||{})[wk.UNPUBLISH=-1]="UNPUBLISH",wk[wk.PUBLISHING=0]="PUBLISHING",wk[wk.PUBLISHED=1]="PUBLISHED",wk),Hk=500,jk=1e3,Gk=ok.BIG,Wk=ok.SMALL,Jk=1e4,Kk={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},zk=2e3,qk={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Yk=5,Qk="default",Xk=Qk,$k="communications",Zk=Object.keys(Qb),eN=["normal leave","timeout leave","kick","role change"],tN=10,iN=2e3,rN="ric",nN="raf",oN="interval",sN="timeout",aN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function cN(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 lN(e){return cb(this,null,(function*(){let t=qw(),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 SO.debug("compressJSON ".concat(i.length," -> ").concat(r.byteLength," ").concat(qw()-t,"ms")),r}catch(wk){return i}}))}var dN=1e8,uN={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"},hN={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(Pw(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(Pw(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=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_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,"()")},pN={};rb(pN,{ANDROID_VERSION:()=>CN,CHROME_MAJOR_VERSION:()=>bD,CHROME_VERSION:()=>kD,EDGE_VERSION:()=>PN,EDG_MAJOR_VERSION:()=>xN,EDG_VERSION:()=>MN,FIREFOX_MAJOR_VERSION:()=>wN,FIREFOX_VERSION:()=>DN,HUAWEI_VERSION:()=>fD,IE_VERSION:()=>zN,IOS_MAIN_VERSION:()=>LD,IOS_VERSION:()=>PD,IPADQQB_VERSION:()=>nD,IS_ANDROID:()=>RN,IS_ANDROID_WEBVIEW:()=>OD,IS_ANY_SAFARI:()=>DD,IS_CHROME:()=>RD,IS_CHROME_OS:()=>cD,IS_CHROMIUM_BASE:()=>AD,IS_EDG:()=>LN,IS_EDGE:()=>ON,IS_ELECTRON:()=>uD,IS_FIREFOX:()=>NN,IS_HEADLESS_CHROME:()=>CD,IS_HUAWEI:()=>_D,IS_HUAWEIBROWSER:()=>mD,IS_IE:()=>KN,IS_IE8:()=>JN,IS_IOS:()=>AN,IS_IOS_13_OR_14:()=>VD,IS_IOS_15_1:()=>xD,IS_IPAD:()=>SN,IS_IPADQQB:()=>rD,IS_IPAD_PRO:()=>yN,IS_IPHONE:()=>IN,IS_IPOD:()=>vN,IS_LINUX:()=>aD,IS_LOCAL:()=>UD,IS_MAC:()=>sD,IS_MACQQB:()=>tD,IS_MIBROWSER:()=>hD,IS_MQQB:()=>XN,IS_NATIVE_ANDROID:()=>kN,IS_OLD_ANDROID:()=>bN,IS_OPPOBROWSER:()=>ED,IS_SAFARI:()=>ND,IS_SAFARI_15_1:()=>MD,IS_SAMSUNGBROWSER:()=>gD,IS_SOGOU:()=>FN,IS_SOGOUM:()=>VN,IS_TBS:()=>HN,IS_UCBROWSER:()=>dD,IS_VIVOBROWSER:()=>yD,IS_WECHAT:()=>qN,IS_WIN:()=>oD,IS_WQQB:()=>ZN,IS_WX:()=>lD,IS_X5MQQB:()=>QN,IS_XWEB:()=>GN,MACQQB_VERSION:()=>iD,MI_VERSION:()=>pD,MQQB_VERSION:()=>$N,OPPO_VERSION:()=>SD,SAFARI_VERSION:()=>wD,SAMSUNG_VERSION:()=>TD,SOGOUM_VERSION:()=>UN,SOGOU_VERSION:()=>BN,TBS_VERSION:()=>jN,USER_AGENT:()=>mN,VIVO_VERSION:()=>ID,WECHAT_VERSION:()=>YN,WQQB_VERSION:()=>eD,XWEB_VERSION:()=>WN,browserInfo:()=>BD,getBrowserInfo:()=>HD,getChromeMajorVersion:()=>vD,getDeviceModel:()=>WD,getOSName:()=>KD,getOSString:()=>zD,getOSType:()=>YD,getTerminalType:()=>qD,getUserAgentData:()=>GD,isLocalStorageEnabled:()=>FD});var mN="undefined"==typeof navigator?"":navigator.userAgent,_N=e=>new RegExp(e,"i").test(mN),fN=e=>{if(_N(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=mN.match(t);if(i&&i[1])return i[1]}return""},gN=e=>{if(_N(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=mN.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},TN=/AppleWebKit\/([\d.]+)/i.exec(mN),EN=TN?parseFloat(TN[1]):NaN,SN=_N("iPad"),yN="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&_N("Macintosh"),IN=_N("iPhone")&&!SN,vN=_N("iPod"),AN=IN||SN||vN||yN,RN=_N("Android"),CN=function(){if(RN){let e=mN.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}(),bN=RN&&_N("webkit")&&CN<2.3,kN=RN&&CN<5&&EN<537,NN=_N("Firefox"),DN=fN("Firefox"),wN=gN("Firefox"),ON=_N("Edge"),PN=fN("Edge"),LN=_N("Edg"),MN=fN("Edg"),xN=gN("Edg"),VN=_N("SogouMobileBrowser"),UN=fN("SogouMobileBrowser"),FN=_N("MetaSr\\s"),BN=fN("MetaSr\\s"),HN=_N("TBS"),jN=fN("TBS"),GN=_N("XWEB"),WN=fN("XWEB"),JN=_N("MSIE\\s8\\.0"),KN=_N("MSIE\\/\\d+"),zN=function(){if(KN){let e=/MSIE\s(\d+)\.\d/.exec(mN),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(mN)&&/rv:11.0/.test(mN)&&(t=11),t}return NaN}(),qN=_N("(micromessenger|webbrowser)"),YN=fN("MicroMessenger"),QN=!HN&&_N("MQQBrowser")&&_N("COVC"),XN=!HN&&_N("MQQBrowser")&&!_N("COVC"),$N=XN||QN?fN("MQQBrowser"):"",ZN=!HN&&_N(" QQBrowser"),eD=fN(" QQBrowser"),tD=!HN&&_N("QQBrowserLite"),iD=fN("QQBrowserLite"),rD=!HN&&_N("MQBHD"),nD=fN("MQBHD"),oD=_N("Windows"),sD=!AN&&_N("MAC OS X"),aD=!RN&&_N("Linux"),cD=_N("CrOS"),lD=_N("MicroMessenger"),dD=_N("UCBrowser"),uD=_N("Electron"),hD=_N("MiuiBrowser"),pD=fN("MiuiBrowser"),mD=_N("HuaweiBrowser"),_D=_N("Huawei"),fD=fN("HuaweiBrowser"),gD=_N("SamsungBrowser"),TD=fN("SamsungBrowser"),ED=_N("HeyTapBrowser"),SD=fN("HeyTapBrowser"),yD=_N("VivoBrowser"),ID=fN("VivoBrowser"),vD=()=>gN("Chrome"),AD=_N("Chrome"),RD=!ON&&!FN&&!VN&&!HN&&!GN&&!LN&&!ZN&&!hD&&!mD&&!gD&&!ED&&!yD&&AD,CD=_N("HeadlessChrome"),bD=vD(),kD=fN("Chrome"),ND=!AD&&!XN&&!QN&&!tD&&!rD&&_N("Safari"),DD=ND||AN,wD=fN("Version"),OD=/Android.*(wv|.0.0.0)/.test(mN),PD=(()=>{if(yN)return wD;if(AN){let e=mN.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),LD=Number(PD.split(".")[0]),MD="15.1"===wD,xD="15.1"===PD,VD=(()=>{let e=Number(PD.split(".")[0]);return 14===e||13===e})(),UD="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),FD=(()=>{let e;return()=>{if(Mw(e))try{e=!!window.localStorage}catch(nL){e=!1}return e}})(),BD=HD();function HD(){let e=new Map([[NN,["Firefox",DN]],[LN,["Edg",MN]],[RD,["Chrome",kD]],[ND,["Safari",wD]],[HN,["TBS",jN]],[GN,["XWEB",WN]],[qN&&IN,["WeChat",YN]],[ZN,["QQ(Win)",eD]],[XN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[tD,["QQ(Mac)",iD]],[rD,["QQ(iPad)",nD]],[hD,["MI",pD]],[mD,["HW",fD]],[gD,["Samsung",TD]],[ED,["OPPO",SD]],[yD,["VIVO",ID]],[ON,["EDGE",PN]],[VN,["SogouMobile",UN]],[FN,["Sogou",BN]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var jD=null;function GD(){return cb(this,null,(function*(){if(jD)return jD;if(!navigator.userAgentData||!Lw(navigator.userAgentData.getHighEntropyValues))return null;try{return jD=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(IF){return null}}))}function WD(){return(null==jD?void 0:jD.model)||""}var JD=new Map([[RN,"Android"],[AN,"iOS"],[oD,"Windows"],[sD,"MacOS"],[aD,"Linux"],[cD,"ChromeOS"]]),KD=function(){return JD.get(!0)?JD.get(!0):jD?jD.platform:"unknown"},zD=()=>{let e=KD();return e+="/".concat(BD.name,"/").concat(ND?BD.version:BD.version.split(".")[0]),null!=jD&&jD.platformVersion&&(e+="/".concat(jD.platformVersion)),null!=jD&&jD.architecture&&(e+="/".concat(jD.architecture)),e};function qD(){return RN?4:IN?2:SN?3:sD?12:oD?5:aD?13:1}function YD(){return RN?"Android":IN?"iPhone":SN?"iPad":sD?"Mac":oD?"Windows":aD?"Linux":"unknown"}var QD=(e,t)=>t?"".concat(Gb,"/").concat(e,"/").concat(t):"".concat(Gb,"/").concat(e,"/index.html"),XD=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(zb);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 $D(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,o="",s="",a="";Lw(hN[t])?o=hN[t](i):xw(hN[t])&&(o=hN[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=XD();r?a="".concat(r.className,".html#").concat(r.fnName):l&&l[t]&&(Lw(l[t])?a=l[t](i):xw(l[t])&&(a=l[t]));let d=o;return Nw()&&(c&&c[t]&&(Lw(c[t])?s=c[t](i):xw(c[t])&&(s=c[t])),s&&(d=n?"".concat(s,"\n请查看文档: ").concat(QD("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),n&&(d+=" \nRefer to: ".concat(QD("en",a),"\n")),d}var ZD,ew=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)=>cb(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<(Lw(d)?d():d)?(h++,m=1,Lw(n)&&n.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),Lw(u)?u(h):u)):(t(),Lw(o)&&o.call(this,f))};Lw(r)?r.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},tw=new(nb(lb(),1).default),iw=((ZD=iw||{}).ROOM_DESTROY="1",ZD.JOIN_START="21",ZD.JOIN_SCHEDULE_SUCCESS="22",ZD.JOIN_SIGNAL_CONNECTION_START="23",ZD.JOIN_SIGNAL_CONNECTION_END="24",ZD.JOIN_SEND_CMD="25",ZD.JOIN_RECEIVED_CMD_RES="26",ZD.JOIN_SUCCESS="27",ZD.JOIN_FAILED="28",ZD.LEAVE_START="51",ZD.LEAVE_SEND_CMD="52",ZD.LEAVE_SUCCESS="53",ZD.PUBLISH_START="61",ZD.SEND_FIRST_VIDEO_FRAME="62",ZD.PUBLISH_FAILED="63",ZD.SUBSCRIBE_START="81",ZD.SUBSCRIBE_SUCCESS="82",ZD.SUBSCRIBE_FAILED="84",ZD.UNSUBSCRIBE_SUCCESS="83",ZD.LOCAL_TRACK_CAPTURE_START="101",ZD.LOCAL_TRACK_CAPTURE_SUCCESS="102",ZD.LOCAL_TRACK_CAPTURE_FAILED="103",ZD.LOCAL_TRACK_PUBLISHED="104",ZD.LOCAL_TRACK_UNPUBLISHED="105",ZD.LOCAL_TRACK_REPLACED="106",ZD.SWITCH_DEVICE_SUCCESS="107",ZD.TRACK_MUTED="108",ZD.TRACK_UNMUTED="109",ZD.REMOTE_TRACK_SUBSCRIBED="110",ZD.REMOTE_TRACK_UNSUBSCRIBED="111",ZD.PLAY_TRACK_START="151",ZD.PLAYER_STATE_CHANGED="152",ZD.VIDEO_LOADED_DATA="153",ZD.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",ZD.SIGNAL_CONNECTION_STATE_CHANGED="201",ZD.PEER_CONNECTION_STATE_CHANGED="202",ZD.SINGLE_CONNECTION_STAT="203",ZD.SPC_RECONNECTED="204",ZD.HEARTBEAT_REPORT="251",ZD.RECEIVED_PUBLISHED_USER_LIST="252",ZD.REMOTE_PUBLISH_STATE_CHANGED="253",ZD.AUDIO_LEVEL_INTERVAL="260",ZD.NETWORK_QUALITY="261",ZD),rw=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:Nb,env:Yb.QCLOUD,browserVersion:BD.name+BD.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){UD||!SO.isAbleToUpload||this._configs.env===Yb.QCLOUD&&this.uploadEventToKibana(tb(eb({},e),{result:"success"}))}logFailedEvent(e){if(UD||!SO.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)||Sb.UNKNOWN};this._configs.env===Yb.QCLOUD&&this.uploadEventToKibana(tb(eb({},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:Rb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:Nb,log:t};r&&(n.errorInfo=r.message),this.sendRequest(gw(this._configs.sdkAppId,qb.LOG),n)}sendRequest(e,t){SO.isAbleToUpload?cN({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},nw=null,ow=!0;function sw(e){Uw(e)&&e!==ow&&(ow=e,SO.info("setIsNeedToSchedule ".concat(e)))}function aw(e){return cb(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(!ow&&nw)return{isCached:!0,result:nw};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=qw(),h=yield function(e,t,i){return new Promise(((r,n)=>{let o=null;zw([mw((e=>t.count[0]=e+1),(e=>{let{error:r,retry:n,retriedCount:s,retryFuncArgs:a}=e;t.msg[0]=r.message,o||(s>=2&&(a[0]=dw(i,ok.MAIN,!0)),n())}))(dw(i,ok.MAIN),e,{get timeout(){return 1e3*ww(2+t.count[0])}}),mw((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]=dw(i,ok.BACKUP,!0)),n())}))(dw(i,ok.BACKUP),e,{get timeout(){return 1e3*ww(2+t.count[1])}})]).then((e=>{o=e,r(o)})).catch(n)}))}(d,e,i);h.config&&(h.config.loggerDomain&&Ub(h.config.loggerDomain),Uw(h.config.scheduleCache)&&sw(!h.config.scheduleCache)),e.delta=qw()-u;let p=function(e,t,i){let r=performance.getEntriesByType("resource"),n=dw(e,ok.MAIN),o=dw(e,ok.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of r)if(a.startTime>=i&&(a.name===n||a.name===o)&&a.transferSize>0){let e=a.name===n?ok.MAIN:ok.BACKUP,i=Math.round(a.duration),r=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[r,o,c,l,d,u];rw.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=tb(eb({},s),{totalCost:i,local:r,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,u);return nw=h,{isCached:!1,result:h,detailCost:p}}catch(d){let e=Bw(d)?d[0]:d,t=Vw(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),r=new Ib({code:Sb.SCHEDULE_FAILED,extraCode:t,message:$D({key:uN.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw SO.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")),tw.on("28",(()=>sw(!0))),tw.on("63",(()=>sw(!0))),tw.on("84",(()=>sw(!0))),tw.on("201",(e=>{"RECONNECTING"===e.state&&sw(!0)})),tw.on("202",(e=>{"RECONNECTING"===e.state&&sw(!0)}));var cw={main:"",backup:""};function lw(e){Bw(e)?(cw.main=e[0],cw.backup=e[1]):cw.main=e}function dw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ok.MAIN,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return"https://".concat(cw[t]||hw(e,t,i),"/api/v1/config")}function uw(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ok.MAIN;return"https://".concat(cw[t]||hw(e,t),"/api/v1/trtcAutoConf")}function hw(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ok.MAIN,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return fw(e)?i===ok.MAIN?Kk.MAIN_OVERSEA:Kk.BACKUP_OVERSEA:(t=fw(e)?r?i===ok.MAIN?Kk.MAIN_OVERSEA_OLD:Kk.BACKUP_OVERSEA_OLD:i===ok.MAIN?Kk.MAIN_OVERSEA:Kk.BACKUP_OVERSEA:i===ok.MAIN?Kk.MAIN:Kk.BACKUP,t)}function pw(e,t,i){return new Promise(((r,n)=>{cN({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 mw=(e,t)=>ew({retryFunction:pw,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var _w=function(){return new URLSearchParams(location.search).get("trtc_env")||""},fw=e=>Number(e)<14e8,gw=function(e,t){let i;i=Vb||(fw(e)?Kb:Jb);let r=Math.floor(Math.random()*$C(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},Tw="unknown";function Ew(){if("unknown"!==Tw)return Tw;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&&(Tw=Sw(r,n)),Tw}function Sw(e,t){if(Zb[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function yw(e){Tw=Sw(e)}function Iw(){return Zb[Ew()]}function vw(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 Aw(e){return Rw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Rw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Cw(e){return 4*bw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function bw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var kw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},Nw=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},Dw=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 ww(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:ww(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function Ow(e){return e>8?3e4:1e3*ww(e)}function Pw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Lw=e=>"function"==typeof e,Mw=e=>void 0===e,xw=e=>"string"==typeof e,Vw=e=>"number"==typeof e,Uw=e=>"boolean"==typeof e,Fw=e=>"object"===Pw(e),Bw=e=>"array"===Pw(e),Hw=e=>Pw(e)==="MediaStreamTrack".toLowerCase(),jw=e=>e.isRemote,Gw=e=>"promise"===Pw(e),Ww=e=>Lw(e)&&e.prototype.constructor===e,Jw=e=>Ww(e)?e.prototype.constructor.name:"",Kw="undefined"!=typeof AudioWorkletNode;function zw(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 qw(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Yw=e=>+e<10?"0".concat(e):e,Qw=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=Yw(i[1])+Yw(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},Xw=Object.prototype.hasOwnProperty;function $w(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(Dw(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(Xw.call(e,t))return!1;return!0}return!1}function Zw(e,t){return{userId:t,hasAudio:!!(e&hk),hasVideo:!!(e&lk),hasAuxiliary:!!(e&uk),hasSmall:!!(e&dk),audioMuted:!!(e&pk),videoMuted:!!(e&mk),audioAvailable:!(!(e&hk)||e&pk),videoAvailable:!(!(e&lk)||e&mk)}}function eO(e){let t={urls:"turn:".concat(e.url)};return!Mw(e.username)&&!Mw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",Mw(e.credentialType)||(t.credentialType=e.credentialType)),t}function tO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!xw(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 iO=function(e,t,i,r){if(!Fw(e)||!Fw(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],!(Mw(t[n])||i&&i.includes(n)))if(Fw(e[n])&&Fw(t[n]))o+=iO(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=rO(t[n]),o+=1)}return o};function rO(e){if(Bw(e)){let t=[];return e.forEach(((e,i)=>{t[i]=rO(e)})),t}if(Fw(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=rO(e[i])})),t}return e}var nO=e=>{let t=[];if(Bw(e))t=[...e];else if(xw(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},oO=e=>xw(e)?document.getElementById(e):e,sO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),aO=()=>sO.format(new Date);function cO(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Bw(e))return"[".concat(e.map((e=>cO(e,{keysToInclude:i,keysToExclude:r}))).join(","),"]");if(!Dw(e)||!Bw(i)&&!Bw(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]=Dw(e[s])||Bw(e[s])?JSON.parse(cO(e[s],{keysToExclude:r,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(wk){return"{}"}}function lO(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)})),cO(e,{keysToInclude:i})}function dO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var uO=()=>{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},hO=e=>cb(void 0,null,(function*(){return new Promise(((t,i)=>{let r;if(xw(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}))})),pO=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},mO=e=>(Object.keys(e).forEach((t=>{Vw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Dw(e[t])||Bw(e[t]))&&mO(e[t])})),e),_O=Object.prototype.hasOwnProperty;function fO(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(_O.call(e,t))return!1;return!0}return!1}var gO=class{constructor(e){sb(this,"userId"),sb(this,"remoteUserId"),sb(this,"id"),sb(this,"sdkAppId"),sb(this,"type"),sb(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):"","]")),SO.log(e,t,void 0===this.userId||fO(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)}},TO=iw,EO=!(AN||RN||CD),SO=new class{constructor(){sb(this,"_isEnableUploadLog",!0),sb(this,"_localJoinedUser",new Map),sb(this,"_queue",[]),sb(this,"_timeoutId",-1),sb(this,"_logLevel",1),sb(this,"_logLevelToUpload",2),!Lb&&!Mb&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){tw.on(TO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&Qb[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),tw.on(TO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),tw.once(TO.JOIN_FAILED,(()=>{this.startUpload()})),tw.on(TO.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(xw(i.userId)&&Vw(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 cb(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:Rb(),sdkAppId:String(r),userId:i,version:Nb,log:n.map((e=>e.log)).join("\n")}),r),n.forEach((e=>e.uploaded=!0))}}catch(Ob){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return ew({retryFunction:()=>cN({url:gw(t,qb.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(Ab());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(Qb[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Mw(Qb[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(xw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(wb){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;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:r,sdkAppId:n,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=Qb[e])?void 0:o.toLowerCase())||"info";EO?console[s]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...t):console[s](...t)}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(1,t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(2,t)}warn(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(3,t)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.log(4,t)}createLogger(e){return new gO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Qb[t]&&(this._logLevelToUpload=t)}},yO=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},IO=new class{constructor(){sb(this,"_prefix","TRTC"),sb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){FD()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(FD())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(nL){SO.warn(nL)}}getItem(e){if(!FD())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(wb){SO.warn(wb)}}setItem(e,t){if(FD())try{let i={expiresIn:Date.now()+ek,value:t};this._queue.set(this.getRealKey(e),i)}catch(wk){SO.warn(wk)}}deleteItem(e){if(!FD())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(wb){return SO.warn(wb),!1}}clear(){if(FD())try{localStorage.clear()}catch(nL){SO.warn(nL)}}},vO={};rb(vO,{HTTPS_API:()=>FO,IS_GET_CAPABILITIES_SUPPORTED:()=>iP,IS_GET_SETTINGS_SUPPORTED:()=>tP,IS_SEI_SUPPORTED:()=>rP,IS_SPC_SUPPORTED:()=>XO,basis:()=>cP,checkSystemRequirementsInternal:()=>xO,decodeSupportStatus:()=>MO,encodeSupportStatus:()=>LO,getBrowserInfo:()=>bO,getDisplayResolution:()=>HO,isAddTransceiverSupported:()=>QO,isBrowserSupported:()=>kO,isGetReceiversSupported:()=>zO,isGetSendersSupported:()=>qO,isGetTransceiversSupported:()=>YO,isGetUserMediaSupported:()=>jO,isMediaDevicesSupported:()=>DO,isMediaSessionSupported:()=>sP,isMediaStreamTrackProcessorSupported:()=>PO,isReplaceTrackSupported:()=>ZO,isScreenCaptureApiAvailable:()=>UO,isSelectedCandidatePair:()=>BO,isSetParametersSupported:()=>eP,isSmallStreamAPISupported:()=>WO,isSmallStreamSupported:()=>JO,isStopTransceiverSupported:()=>$O,isTRTCSupported:()=>VO,isUnifiedPlanDefault:()=>KO,isUsedInHttpProtocol:()=>OO,isWebAudioSupported:()=>GO,isWebCodecSupported:()=>oP,isWebCodecsSupported:()=>NO,isWebRTCSupported:()=>nP,isWebTransportSupported:()=>aP});var AO=nb(pb(),1),RO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},CO=new Map([[NN,["Firefox",DN]],[LN,["Edg",MN]],[RD,["Chrome",kD]],[ND,["Safari",wD]],[HN,["TBS",jN]],[GN,["XWEB",WN]],[qN&&IN,["WeChat",YN]],[ZN,["QQ(Win)",eD]],[XN,["QQ(Mobile)",$N]],[QN,["QQ(Mobile X5)",$N]],[tD,["QQ(Mac)",iD]],[rD,["QQ(iPad)",nD]],[hD,["MI",pD]],[mD,["HW",fD]],[gD,["Samsung",TD]],[ED,["OPPO",SD]],[yD,["VIVO",ID]],[ON,["EDGE",PN]],[VN,["SogouMobile",UN]],[FN,["Sogou",BN]]]);function bO(){let e=CO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var kO=function(){return!(dD||ON||LN&&xN<80||NN&&wN<56)},NO=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},DO=function(){if(!navigator.mediaDevices)return OO()||SO.error(hN.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},wO=!1;function OO(){return"http:"===location.protocol&&!UD&&(wO||SO.error($D({key:uN.NOT_SUPPORTED_HTTP})),wO=!0,!0)}var PO=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},LO=function(){return cb(this,null,(function*(){if(RO.detail.isH264EncodeSupported&&RO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:RO.detail.isH264EncodeSupported,isVp8EncodeSupported:RO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let r=new RTCPeerConnection,n=document.createElement(ok.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(),RO.detail.isH264EncodeSupported=t,RO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:RO.detail.isH264EncodeSupported,isVp8EncodeSupported:RO.detail.isVp8EncodeSupported}}catch(wk){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},MO=function(){return cb(this,null,(function*(){if(RO.detail.isH264DecodeSupported&&RO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:RO.detail.isH264DecodeSupported,isVp8DecodeSupported:RO.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(wk){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},xO=function(){return cb(this,null,(function*(){if(RO.result&&RO.detail.isH264EncodeSupported&&RO.detail.isVp8EncodeSupported&&RO.detail.isH264DecodeSupported&&RO.detail.isVp8DecodeSupported)return RO;let e=kO(),t=nP(),i=NO(),r=DO(),{isH264EncodeSupported:n,isVp8EncodeSupported:o}=yield LO(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield MO();if(!n||!o){let e=yield LO();SO.warn("detect encode again h264:".concat(n," vp8:").concat(o," result: ").concat(JSON.stringify(e))),n=e.isH264EncodeSupported,o=e.isVp8EncodeSupported}if(n&&s&&(ED||yD||OD)&&!HN&&vD()<79){let{encode:e,decode:t}=yield function(){return cb(this,null,(function*(){return new Promise((e=>cb(this,null,(function*(){let t={encode:!1,decode:!1},i=()=>{};try{SO.warn("start detect h264 supported by encoding and decoding canvas stream");let r=document.createElement("canvas"),n=r.getContext("2d");r.width=640,r.height=480;let o=setInterval((()=>{n.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))}),33),s=-1,a=-1;i=()=>{clearInterval(s),clearInterval(o),clearTimeout(a),l.close(),d.close(),c.getTracks().forEach((e=>e.stop()))},a=setTimeout((()=>{i(),e(t)}),3e3);let c=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=AO.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=AO.default.write(p),yield d.setLocalDescription(h),yield l.setRemoteDescription(h),s=setInterval((()=>cb(this,null,(function*(){t.encode&&t.decode&&(i(),e(t));let r=yield l.getStats(),n=yield d.getStats();t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===ok.VIDEO&&e.framesEncoded>0&&(t.encode=!0)})),t.decode||n.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===ok.VIDEO&&e.framesDecoded>0&&(t.decode=!0)}))}))),500)}catch(r){i(),SO.warn(r),e(t)}}))))}))}();n=e,s=t}return RO.result=e&&t&&r&&(n||o)&&(s||a),RO.detail.isBrowserSupported=e,RO.detail.isWebRTCSupported=t,RO.detail.isWebCodecsSupported=i,RO.detail.isMediaDevicesSupported=r,RO.detail.isScreenShareSupported=UO(),RO.detail.isSmallStreamSupported=JO(),RO.detail.isH264EncodeSupported=n,RO.detail.isVp8EncodeSupported=o,RO.detail.isH264DecodeSupported=s,RO.detail.isVp8DecodeSupported=a,RO.result||SO.error("".concat(navigator.userAgent," ").concat(lO(RO.detail,!1))),IO.setItem(lP,{ua:navigator.userAgent,checkResult:RO}),RO}))},VO=function(){return RO.result},UO=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)};var FO=(e,t,i)=>{"http:"===location.protocol&&!UD&&(e[t]=()=>{throw new Ib({code:Sb.INVALID_OPERATION,message:hN.NOT_SUPPORTED_HTTP})})},BO=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(Uw(e.selected)&&!e.selected)};function HO(){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 jO(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function GO(){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 WO(){return"captureStream"in HTMLCanvasElement.prototype}function JO(){return!(qN||AN||bD&&bD<63)&&!(!kO()||!WO())}var KO=function(){if(Mw(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Vk}),e.addTransceiver(ok.AUDIO),t=!0}catch(wb){}return null==e||e.close(),t};function zO(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function qO(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function YO(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function QO(){return 11!==LD&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var XO=!(!QO()||AD&&bD<86);function $O(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function ZO(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function eP(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&qO()}var tP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,iP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,rP="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&vD()>=86,nP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function oP(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Mw(window.AudioDecoder)||(e.AudioDecoder=!0),Mw(window.AudioEncoder)||(e.AudioEncoder=!0),Mw(window.VideoDecoder)||(e.VideoDecoder=!0),Mw(window.VideoEncoder)||(e.VideoEncoder=!0),Mw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function sP(){return"mediaSession"in navigator&&!Mw(navigator.mediaSession.setActionHandler)}function aP(){return!Mw(window.WebTransport)}function cP(){let e={browser:"".concat(BD.name,"/").concat(BD.version),os:KD(),displayResolution:HO(),isScreenShareSupported:UO(),isWebRTCSupported:nP(),isGetUserMediaSupported:jO(),isWebAudioSupported:GO(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:oP(),isMediaSessionSupported:sP(),isWebTransportSupported:aP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var lP="checkResult";!function(){OO();let e=IO.getItem(lP);e&&e.ua===navigator.userAgent&&(RO=e.checkResult),xO()}();var dP=nb(lb(),1),uP=Symbol("instance"),hP=Symbol("cacheResult"),pP=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,TP.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},mP=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var _P=new Map;function fP(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=_P.get(r)||[];_P.has(r)||_P.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=EP.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return i.sync?r[hP]:Promise.resolve(r[hP]);r.state instanceof pP&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;Array.isArray(e)?0==e.length?r.state instanceof pP&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new mP(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 mP(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 pP(u,t,s);TP.call(r,h);let p=e=>{var n;return r[hP]=e,h.aborted||(TP.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[hP])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return TP.call(r,u,e),d(new mP(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 gP="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 TP(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(EP.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var EP=class extends dP.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=EP.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[uP];r?this.name=r.name+"-"+r.count++:i[uP]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=_P.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);_P.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=EP.instances.get(e),t||EP.instances.set(e,t=new EP(e,void 0,Object.create(EP.prototype)))):(t=EP.instances2.get(e),t||EP.instances2.set(e,t=new EP(e.constructor.name,void 0,Object.create(EP.prototype)))),t}static getState(e){var t;return null===(t=EP.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};gP(EP.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){TP.call(this,e)}};EP.STATECHANGED="stateChanged",EP.UPDATEAFSM="updateAFSM",EP.INIT="[*]",EP.ON="on",EP.OFF="off",EP.instances=new Map,EP.instances2=new WeakMap;var SP=(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)},yP=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},IP=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),vP=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sN,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=eb(e===oN?{delay:2e3,count:0,backgroundTask:!0}:e===rN?{delay:1e4,count:0}:e===nN?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),Fw(t)&&(i=eb(eb({},i),t)),Lw(e)&&(t=e,e=sN);let r=eb({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=qw(),r=()=>{if(t=qw()-i,t>=e.delay&&(i=qw()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=SP(r,{timeout:e.delay})};return e.ricID=SP(r,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=qw(),r=()=>document.hidden&&e.backgroundTask?(t=qw()-i,i=qw(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(r,e.delay-Math.floor(t%e.delay))):(t=qw()-i,t>=e.delay&&(i=qw()-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=qw()-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&&IP(r),n&&yP(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)}};vP.taskMap=new Map,vP.currentTaskID=1;var AP=vP;ok.SEI_MESSAGE;var RP={LOADED_DATA:ok.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"},CP={};rb(CP,{create:()=>kP,remove:()=>NP});var bP=new WeakMap;function kP(e,t){bP.has(e)||bP.set(e,[]);let i=bP.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 NP(e){let t=bP.get(e);t&&(t.forEach((e=>e())),bP.delete(e))}var DP=class extends EP{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,sb(this,"id"),sb(this,"element",null),sb(this,"track"),sb(this,"url"),sb(this,"attr"),sb(this,"muted"),sb(this,"_log"),sb(this,"_pausedRetryCount"),sb(this,"_isElementPlayingFired",!1),sb(this,"_interval"),sb(this,"_delayDestroyTimeoutId",0),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Yk,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return cb(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(wb){let t=$D({key:uN.PLAY_FAILED,data:{media:this.kind,error:wb}});if(this.track&&!this.track.muted&&this._log.warn(wb),t.includes("NotAllowedError"))throw new Ib({code:Sb.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(ok.ENDED),this._interval>0&&AP.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():xD?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 kP(this.element,this.element).add(ok.PLAYING,e).add(ok.ENDED,e).add(ok.PAUSE,e).add(ok.ERROR,e).add(ok.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==CP||CP.create(this.track,this.track).add(ok.ENDED,e).add(ok.MUTE,e).add(ok.UNMUTE,e),this.track.readyState===ok.ENDED&&this.handleTrackEvent({type:ok.ENDED}),this.track.muted&&this.handleTrackEvent({type:ok.MUTE})}}bindAutoPlayEvent(){tw.on(TO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&NP(this.track)}unbindEvents(){this.element&&NP(this.element),this.unbindTrackEvents(),tw.off(TO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case ok.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(ok.PLAYING),this._interval&&(AP.clearTask(this._interval),this._interval=-1);break;case ok.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(ok.ENDED);break;case ok.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(ok.PAUSE),AN&&(this._interval=AP.run(sN,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case ok.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),rw.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Pk.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case ok.LOADEDDATA:this.kind===ok.VIDEO&&this.emit(RP.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case ok.ENDED:this.handleStopped(ok.ENDED);break;case ok.MUTE:this.handlePaused(ok.MUTE);break;case ok.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(ok.UNMUTE)}}handlePlaying(e){this.emit(RP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(RP.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(RP.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};ob([fP([],"PLAYING",{sync:!0})],DP.prototype,"handlePlaying",1),ob([fP("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],DP.prototype,"handlePaused",1),ob([fP([],"STOPPED",{sync:!0})],DP.prototype,"handleStopped",1);var wP="trtc_autoplay",OP="".concat(wP,"_mask"),PP="".concat(wP,"_wrapper"),LP="".concat(wP,"_header"),MP="".concat(wP,"_content"),xP="".concat(wP,"_action_wrapper"),VP="".concat(wP,"_question"),UP="".concat(wP,"_collapse"),FP="".concat(wP,"_action_confirm"),BP="".concat(wP,"_detail"),HP="#2473E8",jP="dialog",GP="".concat(jP,"-show"),WP="".concat(jP,"-1"),JP="".concat(jP,"-2"),KP=!1,zP=()=>!!document.querySelector(".".concat(PP)),qP="".concat(Gb,"/").concat(Nw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),YP="<br><a href='".concat(qP,"' target='_blank'>").concat(Nw()?"其他方案?":"Any other solution?","</a>"),QP="".concat(Nw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(YP):"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(YP)),XP=class{constructor(){if(sb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),sb(this,"_dialogNode",null),sb(this,"_bodyPosition",""),sb(this,"_showDetail",!1),sb(this,"_isCollapseClicked",!1),sb(this,"_isQuestionClicked",!1),Nw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!KP){let e=document.createElement("style");e.innerHTML=".".concat(OP,"{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(OP," div:not(.").concat(xP,"){display:block !important;}.").concat(PP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(PP," a{color:").concat(HP,";}.").concat(LP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(MP,"{margin:8px 0;}.").concat(xP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(UP,"{margin-right:auto;cursor:pointer}.").concat(VP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(FP,"{margin-left:8px;color:#fff;background:").concat(HP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(FP,":hover{opacity:0.9;}.").concat(UP,",.").concat(FP,",.").concat(MP,",.").concat(VP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(PP,"{width:80vw;}}"),document.head.appendChild(e),KP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(OP,"\"><div class='").concat(PP,"'><div class='").concat(LP,"'>").concat(location.host,"</div><div class='").concat(MP,"'>").concat(this.content,"</div><div class='").concat(BP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(QP,"</div><div class='").concat(xP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=FP,t.innerText=Nw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=VP,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=UP,r.innerText="".concat(Nw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,o=n.querySelector(".".concat(xP));return o.appendChild(r),o.appendChild(i),o.appendChild(t),n}addDiaLog(){zP()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(PP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",SO.info("show autoplay dialog"),rw.uploadEvent({log:GP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){SO.warn("confirm clicked, try resume stream"),tw.emit(TO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(BP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||rw.uploadEvent({log:WP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(qP,"_blank"),this._isQuestionClicked||rw.uploadEvent({log:JP}),this._isQuestionClicked=!0}},$P=class extends DP{constructor(e){super(e,ok.VIDEO),sb(this,"viewMirror",!1),sb(this,"objectFit"),sb(this,"container"),sb(this,"canvas"),this.container=e.container,this.canvas=e.canvas,Mw(e.viewMirror)||(this.viewMirror=e.viewMirror),Mw(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var e;let t=document.createElement(ok.VIDEO);this.track&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(ok.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(ok.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var t;super.handleElementEvent(e);let i=e.type;if(i===ok.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&&!zP()&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let e=this.element.style.transform;i===ok.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):i===ok.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(RP.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}};function ZP(e,t){return cb(this,null,(function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),SO.info("worklet addModule success")}catch(wb){throw SO.info("worklet addModule catch error. ".concat(wb.message)),wb}}))}"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var eL=new window.AudioContext({sampleRate:48e3}),tL=()=>{"suspended"===eL.state?(eL.resume(),document.addEventListener("click",tL)):"interrupted"===eL.state?eL.resume():document.removeEventListener("click",tL)};document.addEventListener("click",tL),eL.onstatechange=()=>{SO.info("context state: ".concat(eL.state)),tL()};var iL,rL,nL,oL=e=>eL,sL=class{constructor(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.countMap=new Map,this.distributionMap=new Map,this.log=SO.createLogger({id:"kv"}),e&&(tw.on("102",(e=>{let{track:t,cost:i}=e;this.addSuccessEvent({key:t.kind===ok.AUDIO?uL.START_MICROPHONE:hL.START_CAMERA,cost:i})})),tw.on("103",(e=>{let{track:t,error:i}=e;this.addFailedEvent({key:t.kind===ok.AUDIO?uL.START_MICROPHONE:hL.START_CAMERA,error:i})})))}getReportData(){let e={msg_sdk_basic_info:{uint32_sdk_version:pO(this.version||Nb),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(Vw(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=Sb.UNKNOWN;Vw(i)?r=i:(!Mw(i.extraCode)||!Mw(i.code))&&(r=i.extraCode||i.code),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:r,useUV:!1})}},aL=((rL=aL||{})[rL.enterRoom=500700]="enterRoom",rL[rL.exitRoom=500701]="exitRoom",rL[rL.switchRole=500702]="switchRole",rL[rL.destroy=500703]="destroy",rL[rL.startLocalAudio=500704]="startLocalAudio",rL[rL.updateLocalAudio=500705]="updateLocalAudio",rL[rL.stopLocalAudio=500706]="stopLocalAudio",rL[rL.startLocalVideo=500707]="startLocalVideo",rL[rL.updateLocalVideo=500708]="updateLocalVideo",rL[rL.stopLocalVideo=500709]="stopLocalVideo",rL[rL.startScreenShare=500710]="startScreenShare",rL[rL.updateScreenShare=500711]="updateScreenShare",rL[rL.stopScreenShare=500712]="stopScreenShare",rL[rL.startRemoteVideo=500713]="startRemoteVideo",rL[rL.updateRemoteVideo=500714]="updateRemoteVideo",rL[rL.stopRemoteVideo=500715]="stopRemoteVideo",rL[rL.muteRemoteAudio=500716]="muteRemoteAudio",rL[rL.setRemoteAudioVolume=500717]="setRemoteAudioVolume",rL[rL.use=500718]="use",rL[rL.sendSEIMessage=5e5]="sendSEIMessage",rL[rL.sendCustomMessage=500001]="sendCustomMessage",rL),cL=((iL=cL||{})[iL.AudioMixer=550700]="AudioMixer",iL[iL.AIDenoiser=551700]="AIDenoiser",iL[iL.VirtualBackground=570700]="VirtualBackground",iL[iL.Beauty=571700]="Beauty",iL[iL.Watermark=572700]="Watermark",iL),lL=(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))(lL||{}),dL=(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))(dL||{}),uL=(e=>(e[e.START_MICROPHONE=501700]="START_MICROPHONE",e[e.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",e[e.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",e))(uL||{}),hL=((nL=hL||{})[nL.START_CAMERA=511700]="START_CAMERA",nL),pL=new sL(!0),mL=new sL(!1),_L=pL,fL=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(),_L.addSuccessEvent({key:502701})}catch(wk){SO.error(wk),_L.addFailedEvent({key:502701,error:wk})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),_L.addSuccessEvent({key:502702})}catch(wb){SO.error(wb),_L.addFailedEvent({key:502702,error:wb})}}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}},gL=class extends fL{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}},TL=class{constructor(){this.source=new fL,this.gain=new fL,this.destination=new fL}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(this.source.node.context.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.deleteNode(),this.source.setNode(function(e){let t=yL.get(e);if(t)return t;let i=oL();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return yL.set(e,t),t}(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},EL=class extends TL{constructor(e){super(),this.context=e,this.denoiser=new fL,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()}},SL=class{constructor(){this.audioContext=oL(),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]}},yL=new WeakMap;var IL=class{constructor(e){sb(this,"_volume",0),sb(this,"_log"),sb(this,"_scriptProcessorNode",null),sb(this,"_audioWorkletNode",null),sb(this,"_interval",200),sb(this,"ready",this.preload());let{log:t}=e;this._log=t,tw.on(TO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return IL.workletReady||(IL.workletReady=ZP(IL.audioContext,URL.createObjectURL(new Blob(['class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);'],{type:"application/javascript"})))),IL.workletReady.then((()=>this.initAudioWorklet())).catch((()=>this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(IL.audioContext,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this.handleAudioLevelInterval({interval:this._interval})}catch(nL){rw.logFailedEvent({userId:this._log.userId,eventType:Pk.LOAD_WORKLET,error:nL}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=oL().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{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(nL){this._log.error("volumeMeter init script processor error: ".concat(nL))}}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,tw.off(TO.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})}},vL=IL;sb(vL,"audioContext",oL()),sb(vL,"workletReady");var AL=class extends fL{constructor(e){super(),sb(this,"_volumeMeter"),this._volumeMeter=new vL(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return cb(this,null,(function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)}))}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}},RL=nb(lb(),1),CL=e=>t=>t.deviceId===e,bL=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";sb(this,"kind"),sb(this,"type"),sb(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&&DL(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(CL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");SO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(CL(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");SO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},kL=class extends RL.EventEmitter{constructor(){super(),sb(this,"audioInputs",new bL(ok.AUDIO)),sb(this,"videoInputs",new bL(ok.VIDEO)),sb(this,"audioOutputs",new bL(ok.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||AP.run(oN,(()=>{this.update()}),{delay:1e4}))}init(){wL().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return cb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield wL(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},NL=Mb||Lb?null:new kL;function DL(e){return e.deviceId===e.groupId&&""===e.groupId}function wL(){return cb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(OO()||!DO())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{DL(e)&&(e.kind===ok.AUDIO_INPUT?i.audio=!0:e.kind===ok.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(Ob){SO.debug("capture before getDevices failed: ",Ob)}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&&xL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function OL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return NL.update(e?1:0).then((e=>e.audioInputs.devices))}function PL(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return NL.update(e?2:0).then((e=>e.videoInputs.devices))}var LL=!1;function ML(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return cb(this,null,(function*(){return NL.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var xL=new Set;function VL(e,t){return cb(this,null,(function*(){let i=(yield OL()).find((e=>e.deviceId===Qk));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var UL,FL=class extends TL{constructor(e){super(),this.log=e,sb(this,"volumeMeter"),sb(this,"volumeDestination"),sb(this,"analyser",new gL),this.volumeMeter=new AL({log:this.log}),this.volumeDestination=new fL,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},BL=class extends DP{constructor(e){super(e,ok.AUDIO),sb(this,"_outputDeviceId"),sb(this,"_volume",1),sb(this,"_destination",oL().createMediaStreamDestination()),sb(this,"pipeline"),sb(this,"volumeMeterMode","worklet"),this.pipeline=new FL(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if(("15.2"===PD||"15.3"===PD||"15.4"===PD)&&this.muted)return void this._log.info("audioElement is muted.");let e=UL||new Audio;e.setAttribute("autoplay","autoplay"),e.srcObject=this.getMediaStream(),e.muted=this.muted,this.element=e,e===UL&&(UL=void 0),this.bindElementEvents()}play(){return cb(this,null,(function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(oL().createAnalyser()),this.setVolume(this._volume),function(){cb(this,null,(function*(){try{LL||(LL=!0,SO.info("speakers:".concat((yield ML()).map((e=>" ".concat(e.deviceId.slice(0,8),": ").concat(e.label))))))}catch(IF){}}))}(),ab(BL.prototype,this,"play").call(this)}))}stop(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destory(),super.stop(e)}setSinkId(e){return cb(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()}},HL=class extends BL{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(RP.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)}},jL=class extends BL{constructor(e){super(e),sb(this,"_sourceElement"),this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}setTrack(e){var t;this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(RP.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==(t=e.getSettings())?void 0:t.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),NP(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.destory();let t=this._sourceElement||this.element;t&&DD&&(UL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},GL=class extends EP{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:o=(1===r?jL:$P)}=e;var s;super(),sb(this,"id",yO()),sb(this,"userId",""),sb(this,"isRemote"),sb(this,"mediaType"),sb(this,"room"),sb(this,"user"),sb(this,"_log"),sb(this,"_inputTrack"),sb(this,"_outputTrack"),sb(this,"isPlayCalled"),sb(this,"container",null),sb(this,"player"),sb(this,"subVideoPlayerMap"),sb(this,"muted",!1),sb(this,"abortCtrl"),sb(this,"objectFit","cover"),sb(this,"mirror"),sb(this,"isScreen",!1),sb(this,"manager"),sb(this,"trackSettings"),this.userId=t||"",this.mediaType=r,this._log=SO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=n||this.room)?void 0:s.userId,remoteUserId:this instanceof lM?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof lM}),this.player=new o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this.log}),this.player.on(RP.PLAYER_STATE_CHANGED,(e=>{tw.emit(TO.PLAYER_STATE_CHANGED,eb({track:this},e)),this.emit("player-state-changed",e)})),this.kind===ok.VIDEO&&(this.player.on(RP.LOADED_DATA,(()=>{tw.emit(TO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(RP.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)}get log(){return this._log||SO}get kind(){return 1===this.mediaType?ok.AUDIO:ok.VIDEO}get strMediaType(){return 4===this.mediaType?ok.VIDEO:2===this.mediaType?ok.SCREEN:ok.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}play(e,t){return cb(this,null,(function*(){let i=Bw(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!Mw(t.muted)&&this.setPlayerMute(t.muted),t&&!Mw(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof $P&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Bw(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!Mw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===ok.VIDEO)&&this.setPlayerMute(!0),t&&!Mw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof $P&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof $P&&this.player.setContainer(i)),tw.emit(TO.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(),Bw(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(iL){throw this.handleAutoPlayFailed(),this.emit("error",iL),iL}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==ok.VIDEO||Mw(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Uw(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 cb(this,null,(function*(){if(!this._outputTrack||this.kind===ok.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&&(Mw(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new $P({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(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(jw(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}resume(){return cb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),tw.emit(e?TO.TRACK_MUTED:TO.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){kP(e,e).add(ok.MUTE,this.onTrackMuted).add(ok.UNMUTE,this.onTrackUnmuted).add(ok.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ok.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){NP(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.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(jw(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 XP;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof $P?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"))}};ob([fP([],EP.INIT,{sync:!0})],GL.prototype,"close",1);var WL=Object.prototype.hasOwnProperty;var JL=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(Dw(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(WL.call(e,t))return!1;return!0}return!1},KL=ew({retryFunction:function(e){return cb(this,null,(function*(){let t=function(e){return{audio:qL(e),video:YL(e)}}(e);SO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId"];t.audio&&(i=yield OL(),SO.info("microphones: ".concat(cO(i,{keysToInclude:n})))),t.video&&(r=yield PL(),SO.info("cameras: ".concat(cO(r,{keysToInclude:n}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return iP&&e.getTracks().forEach((e=>{SO.info("".concat(e.kind," capabilities: ").concat(cO(e.getCapabilities(),{keysToInclude:aN})))})),e}catch(iL){let{message:n}=iL;throw"NotFoundError"===iL.name&&(e.video&&r&&0===r.length&&(n=$D({key:uN.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(n=$D({key:uN.MICROPHONE_NOT_FOUND}))),new Ib({code:Sb.INITIALIZE_FAILED,name:iL.name,message:n,constraint:iL.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,(!ND||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)):2===s?n[0].useDeviceIdOnly=!0:3===s&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&zL(n[0].microphoneId,!1),n[0].cameraId&&zL(n[0].cameraId,!0)},onRetrying:e=>{SO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{rw.logFailedEvent({eventType:Pk.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{rw.logSuccessEvent({eventType:Pk.GET_USER_MEDIA_RETRY}),rw.uploadEvent({log:"stat-".concat(Pk.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function zL(e,t){return cb(this,null,(function*(){let i=(t?yield PL():yield OL()).find((t=>t.deviceId===e));i&&Lw(i.getCapabilities)&&SO.warn(cO(i.getCapabilities(),{keysToInclude:aN}))}))}function qL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!JL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(Vw(e.channelCount)&&(t.channelCount=e.channelCount),Uw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),Uw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Uw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!JL(t)||t)}function YL(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&&!JL(i)?i:(e.width&&(i.width={ideal:e.width},t&&!NN&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!NN&&(i.height.max=e.height)),NN&&sD&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!JL(i)||i)}var QL=KL;function XL(e){return ZL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return cb(this,null,(function*(){return yield e.apply(this,r),t.apply(this,r)}))}))}function $L(e){return ZL(((t,i)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return cb(this,null,(function*(){let i=yield t.apply(this,r);return yield e.call(this,...r),i}))}))}function ZL(e){return function(t,i,r){return r.value=e(r.value,i),r}}var eM=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&SO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{SO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),tM=0,iM=class{constructor(){this.log=SO.createLogger({id:"fq".concat(++tM)}),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=eb({},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()}))}},rM=new WeakMap,nM=new WeakMap;function oM(){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=rM.get(this)||new iM;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];return rM.set(this,t),t.push({fn:n,args:r,context:this},e)},r}}function sM(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=rM.get(this))?void 0:t.queue)||i.forEach((e=>o.push(e))),null==(r=nM.get(this))||r.forEach((e=>null==e?void 0:e.queue.forEach((e=>o.push(e))))),o.forEach((t=>{t.reject(new Ib({code:Sb.API_CALL_ABORTED,message:e}))})),rM.delete(this),nM.delete(this),n.apply(this,a)},r}}function aM(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=nM.get(this)||new Map,s=r.get(o(t))||new iM;return r.set(o(t),s),nM.set(this,r),s.push({fn:n,args:t,context:this})},r}}var cM=class extends GL{constructor(e,t){super({mediaType:e,PlayerClass:t}),sb(this,"isRemote",!1),sb(this,"deviceId"),sb(this,"groupId",""),sb(this,"label",""),sb(this,"_isRecapturing",!1),sb(this,"_lastRecaptureTime",0),sb(this,"_onMuteTimeoutId",-1),sb(this,"profile")}get isPublished(){return"publish"===this.state}setStateToCapture(){}capture(e){return cb(this,null,(function*(){var t;try{let i,r=qw();tw.emit(TO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield QL(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),tw.emit(TO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:qw()-r}),i}catch(Ob){throw tw.emit(TO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:Ob}),this.log.error("getUserMedia error observed ".concat(Ob)),Ob}}))}setInputMediaStreamTrack(e){return this.state===EP.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),tw.emit(TO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return cb(this,null,(function*(){if(this.mediaTrack&&tP){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return cb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:n,kind:o}=e;return function*(){return t===i&&(o!==ok.AUDIO||t!==Qk||(yield VL(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),wL().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===ok.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(ok.AUDIO_INPUT);return!!xL.has(i)}(this.mediaTrack)||this.kind===ok.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(ok.VIDEO_INPUT);return!!xL.has(i)}(this.mediaTrack)||this._isRecapturing||e&&sD&&ND)}onTrackMuted(){if(super.onTrackMuted(),eM(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<iN)return void setTimeout((()=>this.onTrackMuted()),iN);this._onMuteTimeoutId=setTimeout((()=>cb(this,null,(function*(){var e;if(null!=(e=this.mediaTrack)&&e.muted){if((AN||RN)&&"visible"!==document.visibilityState)return;this.recapture(yield this.getRecoverCaptureDeviceId())}}))),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return cb(this,null,(function*(){if(ab(cM.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<iN)return void setTimeout((()=>this.onTrackEnded()),iN);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return cb(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 OL():yield PL()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return cb(this,null,(function*(){let e=this instanceof hM;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(dM.get(t)||0)+1;if(dM.set(t,i),i>=3){let r=e?(yield PL()).find((e=>!dM.has(e.deviceId))):(yield OL()).find((e=>!dM.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)}},lM=cM;ob([fP(EP.INIT,"capture",{ignoreError:!0,sync:!0})],lM.prototype,"setStateToCapture",1),ob([oM()],lM.prototype,"capture",1),ob([fP("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),tw.emit(TO.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error",i=e.cause;i.message.includes("timeout")?t="timeout":i.code===Sb.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],lM.prototype,"publish",1),ob([ZL((e=>function(){return cb(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"})}))})),fP([],"capture",{sync:!0})],lM.prototype,"unpublish",1);var dM=new Map;tw.on(TO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&dM.delete(e.track.deviceId)}));var uM=class extends lM{constructor(e){super(1,HL),sb(this,"mediaType",1),sb(this,"volume",0),sb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),sb(this,"playerMuted",!0),sb(this,"pipeline"),this.manager=e,this.pipeline=new EL(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 cb(this,null,(function*(){yield ab(uM.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};_L.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),_L.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),_L.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),this.updatePlayingState(!!e)}))}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:r=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,customSource:i})}switchDevice(e){return cb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==Qk)return;if(yield VL(this.groupId,this.label))return}try{this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),tw.emit(TO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(wk){throw this.log.error("switch microphone failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}}))}listenDeviceChange(){NL&&!NL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&NL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return cb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield OL();t[0]?this.recapture(t[0].deviceId):NL.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return cb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:r,autoGainControl:n}=e;return function*(){let e=!1;!Mw(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!Mw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,e=!0),!Mw(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&&_L.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;bD<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(_L.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(),NL.off("audioInputAdded",this.handleMicrophoneAdded,this),NL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return cb(this,null,(function*(){try{yield ab(uM.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield OL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield ab(uM.prototype,this,"recapture").call(this,i.deviceId)}}))}},hM=class extends lM{constructor(e){super(arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,$P),sb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),sb(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),sb(this,"small"),sb(this,"isNeedToSetBandwidth"),sb(this,"muteImage"),sb(this,"manager"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(tb(eb({},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(tP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}setMute(e){return cb(this,null,(function*(){var t,i,r;if(xw(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,ab(hM.prototype,this,"setMute").call(this,!1)}else yield null==(r=this.manager)?void 0:r.deleteWatermark("mute"),this.muteImage=void 0,ab(hM.prototype,this,"setMute").call(this,e)}))}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:r=!1,customSource:n}=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,customSource:n})}setProfile(e){let t=eb({},e),i=t.width>t.height;t.width*t.height<=19200&&RN&&AD&&(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&&VD&&(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(tb(eb({},this.profile),{width:1920,height:1080})))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:ok.VIDEO,videoType:ok.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return tP&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:uO()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return cb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),tw.emit(TO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(wk){throw this.log.error("switch camera failed ".concat(wk)),this.deviceId&&this.recapture(this.deviceId),wk}}))}listenDeviceChange(){NL&&!NL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&NL.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return cb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield PL();t[0]?this.recapture(t[0].deviceId):NL.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return cb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}play(e,t){return cb(this,null,(function*(){return Mw(this.mirror)&&!this.isScreen&&this.setMirror("view"),ab(hM.prototype,this,"play").call(this,e,t)}))}close(){NL.off("videoInputAdded",this.handleCameraAdded,this),NL.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return cb(this,null,(function*(){try{yield ab(hM.prototype,this,"recapture").call(this,e)}catch(wk){let i=(yield PL()).find((t=>t.deviceId!==e));if(!i)throw wk;yield ab(hM.prototype,this,"recapture").call(this,i.deviceId)}}))}},pM=yO();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:pM,exposeOrigin:!0,permittedOrigins:["*"]})}catch(IF){}var mM,_M=function(e){return cb(this,null,(function*(){let t=null,i=function(e){let t={preferCurrentTab:"current-tab"===e.preferDisplaySurface,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:ND?{max:e.width}:{ideal:e.width,max:e.width},height:ND?{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);SO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(RD&&bD<74||ND||NN)&&SO.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(iL){SO.warn("screen applyConstraints failed: ".concat(iL))}e.captureElement&&(yield function(e,t){return cb(this,null,(function*(){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&Lw(e.cropTo))try{if((null==(i=e.getCaptureHandle())?void 0:i.handle)!==pM)return;let r=yield CropTarget.fromElement(t);yield e.cropTo(r)}catch(r){SO.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 Mw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);SO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r}))},fM=class extends hM{constructor(e){super(e,2),sb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),sb(this,"objectFit","contain"),sb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return cb(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 _M({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:Sb.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return cb(this,null,(function*(){throw new Error("Method not implemented.")}))}},gM=class extends uM{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}};var TM=class extends SL{constructor(e){super(),this.room=e,sb(this,"_localAudioTrack"),sb(this,"_localScreenAudioTrack"),sb(this,"log",SO.createLogger({id:"am"})),sb(this,"denoiser"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let 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=function(e){return cb(this,null,(function*(){let t=oL();mM||(mM=ZP(t,URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield mM;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()}})}))}(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}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){if(e instanceof gM)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof uM)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof IM)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;null==(e=this._localAudioTrack)||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),null==(t=this._localScreenAudioTrack)||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof gM?delete this._localScreenAudioTrack:e instanceof uM&&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()}};function EM(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return ZL(((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:Sb.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});SO.warn(i),2===t?s(i):1===t&&n()}),1e3*e);i.apply(this,o).then(n,s).finally((()=>{clearTimeout(a)}))}))}))}var SM=class extends GL{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,sb(this,"tinyId"),sb(this,"isRemote",!0),sb(this,"jitterBufferDelay",0),this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise((e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)}))}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===SM.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed:".concat(this.isSubscribed," hasFlag:").concat(this.hasFlag," hasTrack:").concat(!!this.outMediaTrack));super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}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()}},yM=SM;sb(yM,"STATE_SUBSCRIBE","subscribe"),ob([EM(5,1)],yM.prototype,"waitHasMediaTrack",1),ob([fP(EP.INIT,yM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),tw.emit(TO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],yM.prototype,"subscribe",1),ob([fP(yM.STATE_SUBSCRIBE,EP.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),tw.emit(TO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],yM.prototype,"unsubscribe",1);var IM=class extends yM{constructor(e,t){super(e,t,1),sb(this,"volume",0),sb(this,"mediaType",1),sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},vM=class extends yM{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),sb(this,"mediaType",4),sb(this,"source"),sb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}get isBig(){return 4===this.mediaType}get isSmall(){return 8===this.mediaType}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){"publish"===e||"both"===e||super.setMirror(e)}},AM=class extends vM{constructor(e,t){super(e,t,2),sb(this,"mediaType",2),sb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function RM(){}var CM=e=>e(),bM=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,kM=1,NM=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new LM(e,this,this.streamId++);return MM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},DM=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=RM,this.error=RM,this.next=RM,this.dispose=RM,this.subscribe=RM,this.doDefer()}subscribe(e){return e instanceof NM?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(CM),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}},wM=class extends DM{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}};function OM(e,t,i){if(bM()){let r=Object.defineProperties(Object.setPrototypeOf(e,NM.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}});MM.create(r);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof NM&&MM.addSource(r,t)}return r}return e}function PM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var LM=class extends wM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{MM.defer(this.source,this.id)}))}next(e){MM.next(this.source,this.id,e),this.sink.next(e)}complete(){MM.complete(this.source,this.id),this.sink.complete()}error(e){MM.complete(this.source,this.id,e),this.sink.error(e)}},MM={addSource(e,t){PM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){PM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;PM("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){PM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){PM("defer",{id:e.id,streamId:t})},pipe(e){PM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){PM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=kM++),PM("create",{name:e.toString(),id:e.id})}},xM=class extends DM{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};var VM=function(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 NM){let n=OM((t=>{let o=new e(t,...r);o.sourceId=n.id,o.subscribe(i)}),t,arguments);return n.source=i,MM.pipe(n),n}return t=>i(new e(t,...r))}}}(class extends wM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},"map");!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];i.reduce(((e,t)=>t(e)),e)}(function(e){return OM((t=>{let i=0,r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}(250),VM((()=>performance.now())),function(){return e=>{let t=new xM(e);if(e instanceof NM){let i=OM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,MM.pipe(i),i}return OM(t.add.bind(t),"share",arguments)}}());var UM=new Map;function FM(e,t){let i=tb(eb({},t),{timestamp:Ab()});UM.has(e)?UM.get(e).push(i):UM.set(e,[i])}tw.on(TO.JOIN_SUCCESS,(e=>{let{room:t}=e;FM(t.userId,{eventId:32788,eventDesc:"join room"})})),tw.on(TO.LEAVE_START,(e=>{let{room:t}=e;FM(t.userId,{eventId:32789,eventDesc:"leave room"})})),tw.on(TO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),FM(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),tw.on(TO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),FM(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),tw.on(TO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===ok.AUDIO?FM(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):FM(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),tw.on(TO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===ok.AUDIO?FM(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):FM(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),tw.on(TO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&FM(t.room.userId,{eventId:32777,eventDesc:"".concat(ok.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&FM(t.room.userId,{eventId:32776,eventDesc:"".concat(ok.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&FM(t.room.userId,{eventId:32803,eventDesc:"".concat(ok.SUBSCRIBE," ").concat(ok.SMALL_VIDEO),remoteUserId:t.userId}))})),tw.on(TO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&FM(t.room.userId,{eventId:32779,eventDesc:"".concat(ok.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&FM(t.room.userId,{eventId:32778,eventDesc:"".concat(ok.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&FM(t.room.userId,{eventId:32804,eventDesc:"".concat(ok.UNSUBSCRIBE," ").concat(ok.SMALL_VIDEO),remoteUserId:t.userId}))})),tw.on(TO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&FM(t.room.userId,{eventId:t.kind===ok.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===ok.VIDEO?"camera":"microphone")})})),tw.on(TO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&FM(t.room.userId,{eventId:t.kind===ok.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),tw.on(TO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===n?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===n?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&FM(r.userId,{eventId:t,eventDesc:i})})),tw.on(TO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:r,prevState:n,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===n?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===n&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&FM(r.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var BM=nb(lb(),1),HM=class extends BM.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,sb(this,"userMap",new Map),sb(this,"remotePublishedUserMap",new Map)}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,"]");Mw(t)||(r+=":".concat(eN[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=Zw(r,n),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==r&&(e.flag=r,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:r}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:n,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:Zw(0,n),muteState:s,flag:r})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function jM(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return ZL(((e,n)=>{let o=new Map;return tw.on(TO.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:Sb.INVALID_OPERATION,message:$D({key:uN.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 GM,WM=!0,JM={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"},KM={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},zM=((GM=zM||{})[GM.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",GM[GM.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",GM[GM.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",GM[GM.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",GM[GM.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",GM[GM.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",GM[GM.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",GM[GM.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",GM[GM.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",GM[GM.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",GM[GM.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",GM[GM.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",GM[GM.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",GM[GM.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",GM[GM.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",GM[GM.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",GM[GM.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",GM[GM.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",GM[GM.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",GM[GM.INVALID_OPERATION=5100]="INVALID_OPERATION",GM[GM.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",GM[GM.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",GM[GM.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",GM[GM.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",GM[GM.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",GM[GM.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",GM[GM.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",GM[GM.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",GM[GM.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",GM[GM.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",GM[GM.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",GM[GM.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",GM[GM.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",GM[GM.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",GM[GM.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",GM[GM.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",GM[GM.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",GM[GM.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",GM[GM.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",GM[GM.DEVICE_ERROR=5300]="DEVICE_ERROR",GM[GM.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",GM[GM.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",GM[GM.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",GM[GM.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",GM[GM.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",GM[GM.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",GM[GM.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",GM[GM.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",GM[GM.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",GM[GM.SERVER_ERROR=5400]="SERVER_ERROR",GM[GM.NEED_TO_BUY=5401]="NEED_TO_BUY",GM[GM.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",GM[GM.OPERATION_FAILED=5500]="OPERATION_FAILED",GM[GM.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",GM[GM.REJOIN_FAILED=5502]="REJOIN_FAILED",GM[GM.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",GM[GM.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",GM[GM.OPERATION_ABORT=5998]="OPERATION_ABORT",GM[GM.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",GM);var qM=tb(eb({},hN),{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(Pw(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(Pw(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=YM(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=YM(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=YM(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=YM(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=YM(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=YM(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=YM(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 YM(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var QM=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=zM[i];try{t=qM[a]}catch(o){t=qM.UNKNOWN_ERROR}return Lw(t)?s=t(r):xw(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:i||t,params:eb({fnName:o,error:s},n)}),super(c),sb(this,"name","RtcError"),sb(this,"code"),sb(this,"extraCode"),sb(this,"functionName"),sb(this,"message"),sb(this,"handler"),sb(this,"originError"),this.name=zM[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");oD?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):sD&&(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:KM.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case Sb.INVALID_PARAMETER:o.code=KM.INVALID_PARAMETER,o.message=e.message;break;case Sb.INVALID_OPERATION:o.code=KM.INVALID_OPERATION;break;case Sb.NOT_SUPPORTED:case Sb.NOT_SUPPORTED_H264:o.code=KM.ENV_NOT_SUPPORTED,e.getCode()===Sb.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(hN.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Sb.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case Sb.SERVER_TIMEOUT:case Sb.SWITCH_ROLE_FAILED:o.code=KM.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case Sb.API_CALL_ABORTED:o.code=KM.OPERATION_ABORT;break;case Sb.DEVICE_NOT_FOUND:case Sb.DEVICE_AUTO_RECOVER_FAILED:case Sb.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 Sb.UNKNOWN:break;default:o.code=KM.OPERATION_FAILED}r=new QM(o),n&&(r.stack+=n.substr(n.indexOf("\n")))}else{if(e instanceof QM)return e;r=new QM({code:KM.UNKNOWN_ERROR,fnName:t,originError:e})}return r}};var XM=QM,$M={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}}},ZM={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}}},ex={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(xw(e)&&!document.getElementById(e))throw new XM({code:KM.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},tx={name:"userId",required:!0,type:"string"},ix={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[JM.AUDIO_PROFILE_STANDARD,JM.AUDIO_PROFILE_STANDARD_STEREO,JM.AUDIO_PROFILE_HIGH,JM.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function rx(e,t){if(!e)throw new XM({code:KM.INVALID_OPERATION,extraCode:5101,fnName:t})}function nx(e,t,i){if(!e)throw new XM({code:KM.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var ox={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 XM({code:KM.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(xw(e.roomId))throw new XM({code:KM.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new XM({code:KM.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new XM({code:KM.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new XM({code:KM.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:ex,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:$M},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&OO())throw new XM({code:KM.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:tb(eb({},ex),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:$M}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:ix},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&OO())throw new XM({code:KM.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:ix}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ex,publish:{type:"boolean"},option:ZM},validate(e,t,i,r,n){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&OO())throw new XM({code:KM.ENV_NOT_SUPPORTED,extraCode:5201});if(!UO())throw new XM({code:KM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ex,publish:{type:"boolean"},option:ZM}},muteRemoteAudio:[tx,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[tx,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ex,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){rx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(nx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new XM({code:KM.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:tb(eb({},ex),{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){rx(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(nx(!!r,i,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new XM({code:KM.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&&Mw(e.streamType))throw new XM({code:KM.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){rx(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(!rP)throw new XM({code:KM.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new XM({code:KM.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new XM({code:KM.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new XM({code:KM.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});if(rx(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new XM({code:KM.INVALID_PARAMETER,fnName:i,extraCode:5109})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}],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 XM({code:KM.INVALID_PARAMETER,extraCode:5018,fnName:i});if(0===e.byteLength)throw new XM({code:KM.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(rx(this._room.isJoined,i),"live"===this._room.scene&&"audience"===this._room.role)throw new XM({code:KM.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}}},sx={TRTC:ox},ax=class extends Error{};function cx(e,t){let i=rO(e);for(let r=0;r<t.length;r++)iO(i[r],t[r]);return i}function lx(e){this._resolve=Promise.resolve(e)}function dx(e){this._reject=Promise.reject(e)}var ux=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=cx;let i=ux.instances.get(e);i?i.set(t,this):ux.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=ux.instances.get(e);return i&&i.get(t)||new ux(e,t)}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 ax("start failed")),null==(r=this.currentOp)||r.action(),t},o={type:e,action:()=>t(...o.args).then(r,n),args:i,resolve:lx,reject:dx};try{switch(this.state){case 1:if(0===e)throw new ax("already started");break;case 4:if(2===e)throw new ax("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 ax("already start");break;case 3:switch(e.type){case 2:throw new ax("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ax("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new ax("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 ax("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ax("start not allowed after update");case 0:throw new ax("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new ax("keep start")),new ax("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}},hx=ux;hx.instances=new WeakMap;var px=new WeakMap,mx=(e,t)=>{if(t instanceof ax){let{stack:i}=t;t=new XM({code:KM.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function _x(e,t){return ZL(((i,r)=>function(){for(var n=arguments.length,o=new Array(n),s=0;s<n;s++)o[s]=arguments[s];let a=hx.get(this,"string"==typeof e?e:e.call(this,...o));return t&&(a.startSame=t.bind(this)),a.action(0,i.bind(this),o).catch(mx.bind(null,r))}))}function fx(e,t){let{merge:i,debounce:r}=t||{};return ZL(((t,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=hx.get(this,"string"==typeof e?e:e.call(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=px.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(mx.bind(null,n)).then(r,o)}),e);px.has(this)?null==(l=px.get(this))||l.set(i(...s),{timeoutId:u,resolve:r}):px.set(this,new Map([[i(...s),{timeoutId:u,resolve:r}]]))}))}return c.action(2,t.bind(this),s).catch(mx.bind(null,n))}))}function gx(e){return ZL(((t,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];return hx.get(this,"string"==typeof e?e:e.call(this,...n)).action(3,t.bind(this),n).catch(mx.bind(null,i))}))}var Tx={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"};function Ex(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function Sx(e){return e===JM.QOS_PREFERENCE_CLEAR?"detail":e===JM.QOS_PREFERENCE_SMOOTH?"motion":""}var yx=new WeakMap;function Ix(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(e,o,s){let a=ew({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=yx.get(e))&&t.has(o)?n():s(r)}),s,a):null!=(c=yx.get(e))&&c.has(o)?n():s(r)},onRetrying(t,i){var n;Lw(r)&&r.call(this,t,i),null!=(n=yx.get(e))&&n.has(o)&&(yx.get(e).get(o).stopRetry=i)},onRetryFailed:n});return s.value=function(){let t=yx.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}):yx.set(e,new Map([[o,{args:r}]])),a.apply(this,r).finally((()=>{var t;return null==(t=yx.get(e))?void 0:t.delete(o)}))},s}}function vx(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=yx.get(e))&&n.has(t)){let{stopRetry:n,args:s}=yx.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=yx.get(e))||o.delete(t))}return s.apply(this,c)},o}}var Ax=class{constructor(){sb(this,"_log"),this._log=SO.createLogger({id:"fd"})}download(e,t){return cb(this,null,(function*(){let{type:i="blob"}=t||{};try{let t,r=qw();if(t=Lw(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!t||!t.data)throw new Error("data is empty");let n=qw()-r;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(n,"ms")),_L.addSuccessEvent({key:522700,cost:qw()-r}),t.data}catch(Ob){throw this._log.error("failed to download: ".concat(e,", error: ").concat(Ob)),_L.addFailedEvent({key:522700,error:Ob}),Ob}}))}downloadWithFetch(e,t){return cb(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(wk){throw wk}}))}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 cb(this,null,(function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=qw(),r=null,n=null;if(Lw(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(e=>e.startsWith("file://"))(e)&&Lw(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=qw()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(t,"ms")),_L.addSuccessEvent({key:522701,cost:t}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),_L.addFailedEvent({key:522701,error:n}),n}))}};ob([Ix({settings:{timeout:0,retries:3},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],Ax.prototype,"download",1);var Rx=new Ax;var Cx=new WeakMap;function bx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Nx.call(this,t,n,i,this._name)}catch(Ob){return Promise.reject(Ob)}return e.apply(this,n)}))}function kx(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ZL(((e,i)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];try{Nx.call(this,t,n,i,this._name)}catch(Ob){throw Ob}return e.apply(this,n)}))}function Nx(e,t,i,r){if(Bw(e))for(let n=0;n<e.length;n++)Dx.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Dx.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function Dx(e){let{rule:t,value:i,key:r,fnName:n,className:o}=e;function s(e){return{code:KM.INVALID_PARAMETER,extraCode:e,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(Mw(i)){if(t.required)throw new XM(s(5001));if(Mw(t.defaultValue))return void(Lw(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),Lw(t.type[r])&&i instanceof t.type[r]&&(e=!0),xw(t.type[r])&&Pw(i)===t.type[r].toLowerCase()&&(e=!0);if(!e)throw new XM({code:KM.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map((e=>Ww(e)?Jw(e):xw(e)?e:Pw(e)))},value:i}})}else if(!Mw(t.type)&&Pw(i)!==t.type)throw new XM(s(5002));if(!1===t.allowEmpty){let e=Vw(i)&&(0===i||Number.isNaN(i)),t=xw(i)&&""===i.trim();if(e||t)throw new XM(s(5003))}if(t.notLessThanZero&&Vw(i)&&i<0)throw new XM(s(5006));if(!Mw(t.min)&&Vw(i)&&i<t.min)throw new XM(s(5007));if(!Mw(t.max)&&Vw(i)&&i>t.max)throw new XM(s(5008));if(xw(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new XM(s(5004))}else if(Lw(t.instanceOf)&&!(i instanceof t.instanceOf))throw new XM(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new XM(s(5005));let{properties:a}=t;Dw(a)&&Fw(i)&&Object.keys(a).forEach((e=>{Dx.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:n,className:o})}));let{arrayItem:c}=t;Dw(c)&&Bw(i)&&i.forEach(((e,t)=>{Dx.call(this,{rule:c,value:e,key:"".concat(r,"[").concat(t,"]"),fnName:n,className:o})})),Lw(t.validate)&&t.validate.call(this,i,r,n,o,this)}function wx(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{getRemoteId:t=(()=>""),replaceArg:i,getKVReportKey:r}=e;return ZL(((e,n)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];function c(e,t,r){if(r&&r.includes(e))return"hided";if(i){let e=i(...s);if(s[e.argIndex]===t)return e.value}if(t===s||e in s)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(Pw(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(Pw(t))}}let l=this._log||SO;s.length>0?l.info("".concat(n,"() ").concat(JSON.stringify(s,((e,t)=>c(e,t,["userSig","privateMapKey"]))))):l.info("".concat(n,"()"));let d=r?r(...s):aL[n];try{let i=e.apply(this,s),r=qw();return Gw(i)?i.then((e=>(l.info("".concat(n,"() success ").concat(t.call(this,...s))),_L.addSuccessEvent({key:d,cost:qw()-r}),e))).catch((e=>{throw e=XM.convertFrom.call(this,e,n,1===s.length?s[0]:s),l.error("".concat(n,"() failed ").concat(t.call(this,...s)," ").concat(e," params: ").concat(JSON.stringify(s,c))),_L.addFailedEvent({key:d,error:e}),e})):(_L.addSuccessEvent({key:d}),i)}catch(u){throw u=XM.convertFrom.call(this,u,n),l.error("".concat(n,"() failed ").concat(u," params: ").concat(JSON.stringify(s,c))),_L.addFailedEvent({key:d,error:u}),u}}))}var Ox=e=>ZL(((t,i)=>function(r,n){return cb(this,null,(function*(){let o=this._plugins.get(r);if(!o)throw this._log.error("plugin ".concat(String(r)," is not found")),new XM({code:KM.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});return Nx.call(this,o.getValidateRule(e),[n],i,"TRTC"),t.call(this,o,n)}))})),Px=0,Lx=class{constructor(e,t){sb(this,"player"),sb(this,"publisher"),sb(this,"mixInput"),this.mixInput=new EL(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||(Mw(e.volume)||(this.volume=e.volume),Mw(e.loop)||(this.loop=e.loop),Mw(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 Mx(e,t){if(t&&"function"!=typeof t)throw new XM({code:KM.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var xx=class{constructor(e){this.core=e,sb(this,"log"),sb(this,"mixedMusicMap",new Map),sb(this,"cacheMusicMap",new Map),Px+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Px)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(Px)),this.core=e}getName(){return xx.Name}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return xx.startValidateRule;case"update":return xx.updateValidateRule;case"stop":return xx.stopValidateRule}}start(e){return cb(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 Lx(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.")),_L.addEnum({key:502700,value:3}),this.kvUpload(e)}))}update(e){return cb(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),Mw(i)||o.setOperation(i),Mw(r)||o.seek(r),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(t," not found."))}))}stop(e){return cb(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&&_L.addCount({key:502711}),i&&_L.addCount({key:502703}),r&&_L.addCount({key:502704}),n&&_L.addCount({key:502705}),o&&_L.addCount({key:502706}),s&&_L.addCount({key:502707}),"function"!=typeof a&&_L.addCount({key:502709}),"function"!=typeof l&&_L.addCount({key:502710}),"function"!=typeof c&&_L.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()}},Vx=xx;sb(Vx,"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 XM({code:KM.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new XM({code:KM.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});Mx("onTimeUpdate",e.onTimeUpdate),Mx("onEnded",e.onEnded),Mx("onDurationChange",e.onDurationChange)}}),sb(Vx,"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){Mx("onTimeUpdate",e.onTimeUpdate),Mx("onEnded",e.onEnded),Mx("onDurationChange",e.onDurationChange)}}),sb(Vx,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),sb(Vx,"Name","AudioMixer");var Ux=e=>(e=Number(e))>0&&e<14e8,Fx=0,Bx=class{constructor(e){this.core=e,sb(this,"log"),sb(this,"preloadPromise"),sb(this,"audioContext",oL()),sb(this,"workletNode"),Fx+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Fx)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(Fx)),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 XM({code:KM.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(e){return this.preloadPromise||(this.preloadPromise=this.doPreload(e)),this.preloadPromise}doPreload(e){return cb(this,null,(function*(){let t=yield this.core.fileDownloader.download(e,{type:"blob"}),i=URL.createObjectURL(t);try{yield ZP(this.audioContext,i)}finally{URL.revokeObjectURL(i)}}))}getName(){return Bx.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return Bx.startValidateRule(this.core);case"update":return Bx.updateValidateRule;case"stop":return Bx.stopValidateRule}}start(e){return cb(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 cb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:r,timestamp:n}=e;return function*(){let e="https://".concat(function(e){let t;return t=Ux(e)?jx.MAIN_OVERSEA:jx.MAIN,t}(t),"/api/v1/audioAiAuth?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)}}()}))}(tb(eb({},e),{timestamp:t}));if(!i)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new XM({code:KM.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 cb(this,null,(function*(){}))}stop(){return cb(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(){}},Hx=Bx;sb(Hx,"updateValidateRule",{type:"object"}),sb(Hx,"stopValidateRule",{type:"object"}),sb(Hx,"Name","AIDenoiser");var jx={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var Gx=nb(lb(),1),Wx=class extends Gx.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 cb(this,null,(function*(){if(!this.observer)try{"PressureObserver"in window&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(wb){SO.info("PressureDetector start error:",wb)}}))}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&SO.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;null==(e=this.observer)||e.disconnect(),this.observer=null}},Jx=new Wx,Kx=0,zx=new Set,qx=null;Db("5.6.3");var Yx={RtcError:XM,ErrorCode:KM,ErrorCodeDictionary:zM},Qx=class extends Tb.EventEmitter{constructor(e,t){super(),sb(this,"_room"),sb(this,"_eventListened",new Set),sb(this,"_localVideoTrack",null),sb(this,"_localAudioTrack",null),sb(this,"_localScreenTrack",null),sb(this,"_localScreenAudioTrack",null),sb(this,"_localVideoConfig",null),sb(this,"_localScreenConfig",null),sb(this,"_localAudioConfig",null),sb(this,"_remoteVideoConfigMap",new Map),sb(this,"_remoteAudioConfigMap",new Map),sb(this,"_remoteAudioMuteMap",new Map),sb(this,"_mediaTrackMap",new WeakMap),sb(this,"_log",SO.createLogger({id:"t".concat(++Kx)})),sb(this,"_plugins",new Map),sb(this,"_networkQuality",null),sb(this,"_speakerId"),this._room=new e(eb({logger:this._log,frameWorkType:Qx.frameWorkType},t)),this._log.debug(JSON.stringify(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(Vx,t.assetsPath),this._use(Hx,t.assetsPath),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(Tx.AUDIO_VOLUME,{result:e.sort(((e,t)=>t.volume-e.volume))})})),this._room.videoManager.on("error",(e=>{let{reason:t,error:i}=e;this._log.error(new XM({code:KM.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),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(Ob){let i=$D({key:uN.CATCH_HANDLER_ERROR,data:{name:t,event:n[0]},addDocLink:!1});return SO.warn("".concat(i,"\n\n").concat(Ob.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){var i;WM&&(WM=!1,5!==SO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Gb,"/en/index.html")),console.info("* Changelog: ".concat(Gb,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),SO.info("TRTC Web SDK Version:",Nb),SO.info("UA:",navigator.userAgent),SO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(i=self.frameElement)?void 0:i.tagName)?" in iframe":"")),GD().then((e=>{if(e){let t="UAData: ".concat(e.platform,"/").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=" ".concat(e.architecture,"/").concat(e.bitness)),e.mobile&&(t+=" mobile"),e.model&&(t+=" model: ".concat(e.model)),e.fullVersionList&&(t+=" ".concat(e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(","))),SO.info(t)}})));let r=new Qx(e,t||{});return zx.add(r),Jx.start(),r}_listenEvents(){kP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(Tx.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(Tx.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(Tx.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(Tx.ERROR,XM.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(Tx.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(Tx.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{kP(t,t).add("player-state-changed",(i=>{let r=tb(eb({},i),{userId:e.userId});t.kind===ok.VIDEO&&(r.streamType=Ex(t.streamType)),this.emit(t.kind===ok.AUDIO?Tx.AUDIO_PLAY_STATE_CHANGED:Tx.VIDEO_PLAY_STATE_CHANGED,r)})).add("error",(e=>{e.getCode()===Sb.PLAY_NOT_ALLOWED&&this.emit(Tx.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{NP(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?Tx.REMOTE_AUDIO_AVAILABLE:Tx.REMOTE_AUDIO_UNAVAILABLE,{userId:r}),s?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:i})),o!==a&&(this.emit(a?Tx.REMOTE_VIDEO_AVAILABLE:Tx.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?Tx.REMOTE_VIDEO_AVAILABLE:Tx.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}),i.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}))})).add("firewall-restriction",(()=>{this.emit(Tx.ERROR,new XM({code:KM.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(Tx.SEI_MESSAGE,tb(eb({},e),{streamType:Ex(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,r,n,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(r=this._networkQuality)?void 0:r.downlinkRTT)||0,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)/dN},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)/dN},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(Tx.STATISTICS,l)})).add("custom-message",(e=>{this.emit(Tx.CUSTOM_MESSAGE,e)})),kP(this,NL).add("audioInputAdded",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>cb(this,null,(function*(){if(this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),qx&&qx.deviceId===Xk){let e=(yield ML()).find((e=>e.deviceId===Xk));e&&qx.groupId!==e.groupId&&(qx=e,this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>cb(this,null,(function*(){this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield ML())[0];t&&qx&&(qx.deviceId===e.deviceId||qx.deviceId===Xk&&qx.groupId!==t.groupId)&&(qx=t,this.emit(Tx.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(function(e,t,i){return{room:e,assetsPath:i,fileDownloader:Rx,innerEmitter:tw,constants:bb,environment:pN,utils:Cb,eventLogger:rw,log:e.getLogger(),errorModule:t,kvStatManager:_L,clearStarted(t,i){let r=t.getAlias(),n=hx.instances.get(e);if(n)if(i){let e=n.get(r+i);if(!e)return;e.started=!1}else n.forEach(((e,t)=>{t.startsWith(r)&&(e.started=!1)}))}}}(this._room,Yx,t));this._plugins.set(e.Name,i)}enterRoom(e){return cb(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),!xw(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,Uw(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);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};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,r,Qx.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return cb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return cb(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(){NP(this),this.removeAllListeners(),this._room.destroy(),zx.delete(this),0===zx.size&&Jx.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 cb(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 uM(e._room.audioManager),s={},a={muted:!0};n&&(Mw(n.microphoneId)?Mw(n.audioTrack)||(s.customSource=n.audioTrack):s.deviceId=n.microphoneId,n&&Vw(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),Mw(n.profile)||(xw(n.profile)?ik[n.profile]&&o.setProfile(ik[n.profile]):o.setProfile(n.profile)),Vw(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),Mw(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),Mw(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),Mw(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",(t=>{e.emit(Tx.ERROR,new XM({code:KM.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(Tx.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=XM.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,tb(eb({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),Mw(r)||o.setMute(r),kP(o,o).add("player-state-changed",(t=>{e.emit(Tx.AUDIO_PLAY_STATE_CHANGED,tb(eb({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),e._localAudioTrack=o,e._localAudioConfig=tb(eb({},t),{publish:i}),yield e._updateAudioPlayOption({playOption:a,track:o})}()}))}updateLocalAudio(e){return cb(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):Mw(r.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(r.audioTrack)),Mw(r.captureVolume)||this._localAudioTrack.setCaptureVolume(r.captureVolume),Mw(r.earMonitorVolume)||(n.muted=!(r.earMonitorVolume>0),n.volume=r.earMonitorVolume),yield this._localAudioTrack.update3A(r)),this._room.isJoined&&!Mw(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),Mw(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),iO(this._localAudioConfig,e)}))}stopLocalAudio(){return cb(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),NP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return cb(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 hM(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:Mw(o.useFrontCamera)?Mw(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?ok.FACING_MODE_USER:ok.FACING_MODE_ENVIRONMENT,Mw(o.profile)||(xw(o.profile)?rk[o.profile]&&s.setProfile(rk[o.profile]):s.setProfile(o.profile)),Mw(o.fillMode)||(c.objectFit=o.fillMode),Mw(o.mirror)||(c.mirror=o.mirror),Mw(o.small)||(JO()?xw(o.small)?s.small=rk[o.small]:!0===o.small?s.small=rk["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(Tx.ERROR,new XM({code:KM.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(Tx.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=XM.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,tb(eb({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),Mw(n)||(yield s.setMute(n)),s.mediaTrack)if(null!=o&&o.qosPreference){let e=Sx(o.qosPreference);s.mediaTrack.contentHint=e}else null!=o&&o.videoTrack||(s.mediaTrack.contentHint=Sx(JM.QOS_PREFERENCE_SMOOTH));kP(s,s).add("player-state-changed",(t=>{e.emit(Tx.VIDEO_PLAY_STATE_CHANGED,tb(eb({},t),{userId:"",streamType:"main"}))})),r&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),e._localVideoTrack=s,e._localVideoConfig=tb(eb({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:s})}()}))}updateLocalVideo(e){return cb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:r,option:n}=e,o={};if(n){if(Mw(n.profile)||(xw(n.profile)?rk[n.profile]&&this._localVideoTrack.setProfile(rk[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&Mw(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):Mw(n.useFrontCamera)?Mw(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?ok.FACING_MODE_USER:ok.FACING_MODE_ENVIRONMENT),Mw(n.fillMode)||(o.objectFit=n.fillMode),Mw(n.mirror)||(o.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let e=Sx(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(n.small){let e=!this._localVideoTrack.small;JO()?(!0===n.small?this._localVideoTrack.small=rk["120p"]:xw(n.small)?this._localVideoTrack.small=rk[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&&!Mw(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),Mw(r)||(yield this._localVideoTrack.setMute(r)),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),iO(this._localVideoConfig,e)}))}stopLocalVideo(){return cb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),NP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return cb(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 fM(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=XM.convertFrom(t.error)),e.emit(Tx.PUBLISH_STATE_CHANGED,tb(eb({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null,a={},c={};n&&(Mw(n.profile)||(xw(n.profile)?nk[n.profile]&&o.setProfile(nk[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(a.systemAudio=!0,a.echoCancellation=n.echoCancellation,a.noiseSuppression=n.noiseSuppression,a.autoGainControl=n.autoGainControl),Mw(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=Sx(n.qosPreference);o.mediaTrack.contentHint=e}else null!=n&&n.videoTrack||(o.mediaTrack.contentHint=Sx(JM.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(ok.ENDED,(()=>{e._stopScreenShare(),e.emit(Tx.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new gM(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),kP(o,o).add("player-state-changed",(t=>{e.emit(Tx.VIDEO_PLAY_STATE_CHANGED,tb(eb({},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=tb(eb({},t),{view:i,publish:r}),yield e._updateVideoPlayOption({view:i,playOption:c,track:o})}()}))}updateScreenShare(e){return cb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:r}=e,n={};if(r&&(Mw(r.fillMode)||(n.objectFit=r.fillMode),r.qosPreference)){let e=Sx(r.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!Mw(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}),iO(this._localScreenConfig,e)}))}stopScreenShare(){return cb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return cb(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&&(Mw(n.fillMode)||(a.objectFit=n.fillMode),Mw(n.mirror)||(a.mirror=n.mirror),"main"===r&&!Mw(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&&!Mw(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:null==n?void 0:n.viewRoot})}))}updateRemoteVideo(e){return cb(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&&(Mw(s.fillMode)||(l.objectFit=s.fillMode),Mw(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&&!Mw(s.small)&&this._room.changeType(s.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:d,prevConfig:h}),iO(h,e);let p=Mw(null==s?void 0:s.receiveWhenViewVisible)?null==(t=h.option)?void 0:t.receiveWhenViewVisible:s.receiveWhenViewVisible,m=Mw(r)?h.view:r,_=Mw(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 cb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return cb(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 cb(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._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return cb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return cb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return cb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return this.listeners(e).includes(t)||(super.on(e,t,i),this._eventListened.add(e)),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getAudioTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"};var t,i;let r,n="main";if(xw(e)?r=e:(r=e.userId,e.streamType&&(n=e.streamType)),!r)return"sub"===n?(null==(t=this._localScreenAudioTrack)?void 0:t.mediaTrack)||null:(null==(i=this._localAudioTrack)?void 0:i.mediaTrack)||null;{let e=this._room.remotePublishedUserMap.get(r);if(e)return e.remoteAudioTrack.mediaTrack}return null}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}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)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return cb(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let n={};i&&(Mw(i.volume)||(n.volume=i.volume));let o=r.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:n,track:o})}catch(ZU){throw this._remoteAudioConfigMap.delete(t),ZU}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return cb(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 cb(this,arguments,(function(e){let{view:t,playOption:i,track:r,prevConfig:n}=e;return function*(){if(r.setMirror(i.mirror),Mw(t)&&n&&n.view&&!$w(i)){let e=nO(n.view);e.length>0&&(yield r.play(e,i))}if(!Mw(t)){let e=nO(t);e.length>0?yield r.play(e,i):r.stop()}}()}))}_updateAudioPlayOption(e){return cb(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){}Mw(t.muted)||i.setPlayerMute(t.muted),Mw(t.volume)||i.setAudioVolume(t.volume/100)}()}))}_listenOutputTrackChanged(e){0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(()=>this._emitTrackEvent(e)))}_emitTrackEvent(e){let t=e.isRemote?e.userId:"";e.outMediaTrack&&this._mediaTrackMap.get(e.outMediaTrack)!==t&&(this._mediaTrackMap.set(e.outMediaTrack,t),this.emit(Tx.TRACK,{userId:t,streamType:Ex(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(Mw(i))return;let o=this._remoteVideoConfigMap.get("".concat(t.userId,"_").concat(Ex(t.streamType)));if(!o)return;let s=o.observer||void 0;if(null===i||Bw(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(nO(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 cb(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._room.remotePublishedUserMap.forEach((e=>{NP(e.remoteAudioTrack),NP(e.remoteVideoTrack),NP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return cb(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),NP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return cb(this,null,(function*(){if(qx&&!DL(qx))this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:qx});else{let e=yield ML();if(e[0]&&!DL(e[0]))qx=e[0],this.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!qx||DL(qx))&&(this._initActiveSpeaker(),tw.off("102",this._initActiveSpeaker))};tw.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){this._room.sendSEI(e,t||{seiPayloadType:243}),_L.addCount({key:5e5,useUV:!0})}sendCustomMessage(e){var t,i;null==(i=(t=this._room).sendCustomMessage)||i.call(t,e),_L.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){SO.setLogLevel(e),Mw(t)||(t?SO.enableUploadLog():SO.disableUploadLog())}static isSupported(){return xO()}static getCameraList(){return PL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getMicrophoneList(){return OL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static getSpeakerList(){return ML(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}static setCurrentSpeaker(e){return cb(this,null,(function*(){(yield ML()).forEach((t=>{t.deviceId===e&&(zx.forEach((i=>{i.setCurrentSpeaker(e),i.emit(Tx.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),qx=t)}))}))}static _addKVStat(e){let{type:t,key:i,value:r,base:n,useUV:o,version:s}=e;switch(s&&(mL.version=s),t){case"count":mL.addCount({key:i,useUV:o});break;case"enum":mL.addEnum({key:i,value:r,useUV:o});break;case"number":mL.addNumber({key:i,value:r,split:n})}}},Xx=Qx;sb(Xx,"_loggerManager",SO),sb(Xx,"EVENT",Tx),sb(Xx,"ERROR_CODE",KM),sb(Xx,"TYPE",JM),sb(Xx,"frameWorkType",30),ob([wx({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"}})})],Xx.prototype,"use",1),ob([bx(sx.TRTC.enterRoom),_x("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})),ZL((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),wx()],Xx.prototype,"enterRoom",1),ob([wx()],Xx.prototype,"exitRoom",1),ob([bx(sx.TRTC.switchRole),fx("room",{merge:(e,t)=>t}),wx()],Xx.prototype,"switchRole",1),ob([wx()],Xx.prototype,"destroy",1),ob([bx(sx.TRTC.startLocalAudio),_x("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)})),wx()],Xx.prototype,"startLocalAudio",1),ob([bx(sx.TRTC.updateLocalAudio),fx("audio",{debounce:{delay:200,getKey:()=>"".concat(Kx,"-localAudio"),isNeedToDebounce:e=>{var t;return!Mw(null==(t=e.option)?void 0:t.captureVolume)}}}),wx()],Xx.prototype,"updateLocalAudio",1),ob([gx("audio"),wx()],Xx.prototype,"stopLocalAudio",1),ob([bx(sx.TRTC.startLocalVideo),_x("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)})),wx()],Xx.prototype,"startLocalVideo",1),ob([bx(sx.TRTC.updateLocalVideo),fx("video"),wx()],Xx.prototype,"updateLocalVideo",1),ob([gx("video"),wx()],Xx.prototype,"stopLocalVideo",1),ob([bx(sx.TRTC.startScreenShare),_x("screen",(()=>!0)),wx()],Xx.prototype,"startScreenShare",1),ob([bx(sx.TRTC.updateScreenShare),fx("screen"),wx()],Xx.prototype,"updateScreenShare",1),ob([wx()],Xx.prototype,"stopScreenShare",1),ob([bx(sx.TRTC.startRemoteVideo),_x((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Xx.prototype,"startRemoteVideo",1),ob([bx(sx.TRTC.updateRemoteVideo),fx((e=>"v".concat(e.userId).concat(e.streamType))),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Xx.prototype,"updateRemoteVideo",1),ob([bx(sx.TRTC.stopRemoteVideo),ZL((e=>function(t){return cb(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)}))})),wx({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Xx.prototype,"stopRemoteVideo",1),ob([gx((e=>"v".concat(e.userId).concat(e.streamType)))],Xx.prototype,"_stopRemoteVideo",1),ob([bx(...sx.TRTC.muteRemoteAudio),wx({getRemoteId:e=>e})],Xx.prototype,"muteRemoteAudio",1),ob([kx(...sx.TRTC.setRemoteAudioVolume),function(e,t){return ZL(((i,r)=>function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var s,a;let c=null==(s=Cx.get(this))?void 0:s.get(t(...n));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,n)}),e);Cx.has(this)?null==(a=Cx.get(this))||a.set(t(...n),l):Cx.set(this,new Map([[t(...n),l]]))}))}(200,(e=>e)),wx({getRemoteId:e=>e})],Xx.prototype,"setRemoteAudioVolume",1),ob([Ox("start"),_x(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>cL[e.getName()]})],Xx.prototype,"startPlugin",1),ob([Ox("update"),fx(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>lL[e.getName()]})],Xx.prototype,"updatePlugin",1),ob([Ox("stop"),gx(((e,t)=>e.getAlias()+e.getGroup(t))),wx({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>dL[e.getName()]})],Xx.prototype,"stopPlugin",1),ob([kx(...sx.TRTC.enableAudioVolumeEvaluation)],Xx.prototype,"enableAudioVolumeEvaluation",1),ob([wx()],Xx.prototype,"getVideoSnapshot",1),ob([wx()],Xx.prototype,"setCurrentSpeaker",1),ob([_x((e=>"a".concat(e.userId)),(()=>!0))],Xx.prototype,"_startRemoteAudio",1),ob([ZL((e=>function(t){return cb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(tb(eb({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),gx((e=>"a".concat(e.userId)))],Xx.prototype,"_stopRemoteAudio",1),ob([gx("room")],Xx.prototype,"_exitRoom",1),ob([gx("screen")],Xx.prototype,"_stopScreenShare",1),ob([bx(...sx.TRTC.sendSEIMessage),jM({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}})],Xx.prototype,"sendSEIMessage",1),ob([bx(sx.TRTC.sendCustomMessage),jM({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Xx.prototype,"sendCustomMessage",1),ob([bx(sx.TRTC.create)],Xx,"_create",1);var $x=Xx,Zx=class{constructor(){this._set=new Set,tw.on(TO.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 eV(){return cb(this,null,(function*(){let e,t;try{let t=yield OL();e=t&&t.length}catch(u){}try{let e=yield PL();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=vO.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};rw.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),rw.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var tV=nb(lb(),1),iV=Symbol("instance"),rV=Symbol("cacheResult"),nV=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,lV.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},oV=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var sV=new Map;function aV(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=sV.get(r)||[];sV.has(r)||sV.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=dV.get("function"==typeof i.context?i.context.call(this,...o):i.context)),r.state===t)return r[rV];r.state instanceof nV&&r.state.action==i.abortAction&&r.state.abort(r);let l=null;if(Array.isArray(e)?0==e.length?r.state instanceof nV&&r.state.abort(r):("string"!=typeof r.state||!e.includes(r.state))&&(l=new oV(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 oV(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 nV(d,t,s);lV.call(r,u);let h=e=>{var n;return r[rV]=e,u.aborted||(lV.call(r,t),null===(n=i.success)||void 0===n||n.call(this,r[rV])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(lV.call(r,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new oV(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 cV="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 lV(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(dV.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var dV=class extends tV.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=dV.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[iV];r?this.name=r.name+"-"+r.count++:i[iV]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=sV.get(e)||[],i=new Set,r=[],n=[],o=new Set,s=Object.getPrototypeOf(e);sV.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=dV.instances.get(e),t||dV.instances.set(e,t=new dV(e,void 0,Object.create(dV.prototype)))):(t=dV.instances2.get(e),t||dV.instances2.set(e,t=new dV(e.constructor.name,void 0,Object.create(dV.prototype)))),t}static getState(e){var t;return null===(t=dV.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};cV(dV.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){lV.call(this,e)}};dV.STATECHANGED="stateChanged",dV.UPDATEAFSM="updateAFSM",dV.INIT="[*]",dV.ON="on",dV.OFF="off",dV.instances=new Map,dV.instances2=new WeakMap;var uV=nb(lb()),hV="1",pV="5",mV="2",_V="3",fV="5",gV="4",TV={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},EV=[TV.UPDATE_REMOTE_MUTE_STAT,TV.UPLINK_NETWORK_STATS,TV.USER_LIST_RES,TV.MUTE_RESULT,TV.SERVER_FIRST_PACKAGE_RECEIVED,TV.RECEIVE_CUSTOM_MSG],SV={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},yV="publish_change",IV="join",vV="leave",AV="quality_report",RV="mute_uplink",CV="publish",bV="publish_state_change",kV="unpublish",NV="subscribe",DV="unsubscribe",wV="subscribe_change",OV="start_publishing",PV="stop_publishing",LV="start_push_user_cdn",MV="stop_push_user_cdn",xV="start_mcu_mix",VV="stop_mcu_mix",UV="get_user_list",FV="change_role",BV="update_constraint_config",HV="rebuild_pc",jV="join/v2",GV="publish/v2",WV="subscribe/v3",JV="ability_status_report",KV="reconnect",zV="channel_msg",qV=new Set;var YV=class extends uV.default{constructor(e){var t,i;super(),sb(this,"room"),sb(this,"url"),sb(this,"backupUrl"),sb(this,"race"),sb(this,"destroyed",!1),sb(this,"_socketInUse"),sb(this,"_socket"),sb(this,"_backupSocket"),sb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),sb(this,"_currentState","DISCONNECTED"),sb(this,"_isReconnecting",!1),sb(this,"_seq",0),sb(this,"_log"),sb(this,"_lastMessageTime",-1),sb(this,"_connnectStartTime",-1),sb(this,"_stopConnectRetry"),sb(this,"bytesSent",0),sb(this,"bytesReceived",0),sb(this,"keepAlive",!1),this.room=e.room,this.race=!!Mw(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-qV.size>0&&this.room.enableSPC&&(this.keepAlive=!0,qV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=SO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return cb(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=qw();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 zw(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?ok.BACKUP:ok.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?ok.MAIN:ok.BACKUP),t(new Ib({code:Sb.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===ok.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(wk){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(wk){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||1e3!==e.code)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?ok.MAIN:ok.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(ok.MAIN),this.unbindAndCloseSocket(ok.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=dO(e.data);let t=JSON.parse(e.data),{cmd:i,data:r}=t,n=Object.values(TV),o=Object.keys(TV)[n.indexOf(i)],s=SV[o];switch(EV.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case TV.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){vb=e-(new Date).getTime();let t=new Date;t.setTime(e),SO.info("baseTime from server: ".concat(t," offset: ").concat(vb))}(r.svrTime),this._log.info("ChannelSetup Success"),_L.addSuccessEvent({key:521701,cost:qw()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(hV,{signalInfo:this._signalInfo});else{let e=new Ib({code:Sb.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:$D({key:uN.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),_L.addFailedEvent({key:521701,error:e}),this.emit(pV,e)}break;case TV.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._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return cb(this,null,(function*(){try{sw(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(wb){}}))}reconnect(){return cb(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:KV,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:SV.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),_L.addSuccessEvent({key:521702,cost:qw()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(_L.addFailedEvent({key:521702,error:o.code}),this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(wb){this._log.error(wb),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+=dO(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(n,l);let e=new Ib({code:Sb.API_CALL_TIMEOUT,message:$D({key:uN.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),r),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(n,l),e(t))};this.on(n,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return ew({retryFunction:this.sendWaitForResponse,onError:e=>{let{retry:t}=e;this.isOnline?t():(this._log.warn("retry ".concat(i," when connected")),this.once(_V,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"),qV.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(ok.MAIN),this.unbindAndCloseSocket(ok.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"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof nV&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(dV.STATECHANGED,i))};this.room.on(dV.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(mV,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(_V):"DISCONNECTED"===e&&this.emit(fV))}};ob([Ix({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())}})],YV.prototype,"connect",1);var QV=nb(lb()),XV=0,$V=!1,ZV=new Set,eU=!1,tU=class{constructor(e){sb(this,"userId"),sb(this,"tinyId"),sb(this,"_sdpSemantics"),sb(this,"_isUplink"),sb(this,"_room"),sb(this,"_log"),sb(this,"_signalChannel"),sb(this,"_isErrorObserved",!1),sb(this,"_waitForPeerConnectionConnectedPromise"),sb(this,"_waitForPeerConnectionConnectedPromiseReject",null),sb(this,"_peerConnection",null),sb(this,"_emitter",new QV.default),sb(this,"_currentState","DISCONNECTED"),sb(this,"_isReconnecting",!1),sb(this,"_reconnectionCount",0),sb(this,"_reconnectionTimer",-1),sb(this,"_isFirstConnection",!0),sb(this,"_prevTime",-1),sb(this,"_enableSEI"),sb(this,"_sei"),sb(this,"_localAddress"),sb(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=SO.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}beforeConnect(){this._prevTime<0&&(this._prevTime=qw())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,_L.addSuccessEvent({key:521705,cost:Math.min(qw()-this._prevTime,3e4)})):this._isReconnecting&&_L.addSuccessEvent({key:521706,cost:qw()-this._prevTime}),this._prevTime=-1}catch(nL){throw this._isFirstConnection?(this._isFirstConnection=!1,_L.addFailedEvent({key:521705,error:nL})):this._isReconnecting&&this._reconnectionCount>=3&&_L.addFailedEvent({key:521706,error:nL}),nL}}initialize(){let e={encodedInsertableStreams:this._enableSEI&&rP,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),ZV.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:Sb.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(!zO()||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===bk.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===bk.FAILED||e.target.connectionState===bk.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new Ib({message:r,code:Sb.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===bk.CONNECTED||e.target.connectionState===bk.COMPLETED)&&(this.logSelectedCandidate(),rw.logSuccessEvent({userId:this._room.userId,eventType:Pk.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(XV=0,$V=!1,eU=!0,ZV.add(this)):ZV.delete(this),tw.emit(TO.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 cb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(BO(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:Sb.API_CALL_ABORTED,message:$D({key:uN.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{tw.off(TO.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{n();let e=new Ib({code:Sb.API_CALL_TIMEOUT,message:"connection timeout"});var i;XV+=1,i=this._signalChannel.isConnected,XV>2&&!$V&&0===ZV.size&&i&&(this._log.warn("firewall restriction"),$V=!0,this._emitter.emit("firewall-restriction")),t(e)}),Jk);tw.on(TO.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(_V,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Dk()){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?Sb.UPLINK_RECONNECTION_FAILED:Sb.DOWNLINK_RECONNECTION_FAILED,message:$D({key:this._isUplink?uN.UPLINK_RECONNECTION_FAILED:uN.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(_V,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"))}},iU=nb(gb()),rU=function(e){return iU.default.parse(e)},nU=function(e){return iU.default.write(e)};function oU(e){return Object.keys(e).filter((t=>e[t]))}var sU=class extends tU{constructor(e){super(tb(eb({},e),{isUplink:!1})),sb(this,"_flag",0),sb(this,"role","anchor"),sb(this,"remoteAudioTrack"),sb(this,"remoteVideoTrack"),sb(this,"remoteAuxiliaryTrack"),sb(this,"ssrc",{audio:0,video:0,auxiliary:0}),sb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new IM(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new vM(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new AM(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Zw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===ok.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let t=e.streams[0],{track:i}=e,r=t.id===_k?ok.MAIN:ok.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=ok.AUDIO;i.kind===ok.VIDEO&&(n=r===ok.MAIN?ok.VIDEO:ok.AUXILIARY);let o=this.remoteAudioTrack;n===ok.VIDEO?o=this.remoteVideoTrack:n===ok.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=rU(e);return t.media.forEach((e=>{e.type===ok.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),nU(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=rU(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),nU(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return cb(this,null,(function*(){var i,r;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===bk.NEW||(null==(r=this._peerConnection)?void 0:r.connectionState)===bk.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:Sb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Pb}}))}unsubscribe(e){return cb(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=eb({},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(oU(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=DV,n=SV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=wV,n=SV.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:$D({key:uN.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return cb(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(wk){throw e.closePeerConnection(!0),wk}}()}))}exchangeSDP(e){return cb(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:NV,commandDesc:"exchange sdp",data:r,responseCommand:SV.SUBSCRIBE_RESULT,timeout:xk});if(!this._peerConnection){let e=new Ib({code:Sb.INVALID_OPERATION,message:$D({key:uN.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(wk){throw this._isSDPExchanging=!1,wk}}))}createOffer(){return cb(this,null,(function*(){let e={voiceActivityDetection:!1};QO()&&this._sdpSemantics===Vk?(this._peerConnection.addTransceiver(ok.AUDIO,{direction:sk.RECVONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:sk.RECVONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:sk.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield MO();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=rU(e);return t.media.forEach((e=>{var t,i;if(e.type===ok.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(" ")}})),nU(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=rU(e);return t.media.forEach((e=>{e.type===ok.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),nU(t)}(t.sdp),this._sdpSemantics===Vk&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return cb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:r,sdp:n}=e&&e.data&&e.data.data||{};if(t===Fk)throw new Ib({code:Sb.NOT_SUPPORTED_H264,message:$D({key:uN.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new Ib({code:t,message:$D({key:uN.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(n)),yield this._peerConnection.setRemoteDescription({type:r,sdp:n}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",tb(eb({},e),{userId:this.userId}))}),this.updateSSRC(n)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{rU(e).media.forEach((e=>{if(e.ssrcs)if(e.type===ok.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(_k)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(_k)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(fk)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(wk){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return cb(this,null,(function*(){if(!(ab(sU.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(wk){let t=Ow(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}},aU=sU;ob([ZL((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:Sb.API_CALL_ABORTED,message:$D({key:uN.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],aU.prototype,"subscribe",1),ob([$L(tU.prototype.afterConnect),XL(tU.prototype.beforeConnect)],aU.prototype,"connect",1);var cU=aU,lU={voiceActivityDetection:!1},dU=class extends tU{constructor(e){super(tb(eb({},e),{isUplink:!0})),sb(this,"localMainAudioTrack",null),sb(this,"localMainVideoTrack",null),sb(this,"localAuxAudioTrack",null),sb(this,"localAuxVideoTrack",null),sb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),sb(this,"_isPublishingAux",!1),sb(this,"_publishingLocalAudioTrack"),sb(this,"_publishingLocalVideoTrack"),sb(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}),sb(this,"flag",0)}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&&(YO()?(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===ok.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 cb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r,isAuxiliary:n}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=n,r&&!n&&r.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),QO()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:r,smallTrack:o}),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)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,r),t.sendMutedFlag()}()}))}publishByTransceiver(e){return cb(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||ok.AUDIO,{direction:sk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?ok.VIDEO:s||ok.VIDEO,{direction:sk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(n||ok.VIDEO,{direction:sk.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||ok.VIDEO,{direction:sk.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:ok.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:r.profile.bitrate,type:ok.VIDEO,videoType:o?ok.AUXILIARY:ok.BIG}),e.push(i),n&&(yield c[2].sender.replaceTrack(n),yield t.setBandwidth({bandwidth:r.small.bitrate,type:ok.VIDEO,videoType:ok.SMALL}),e.push(2))}yield t.setTransceiverDirection(sk.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 cb(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 cb(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(sk.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(sk.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 cb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:r}=e;return function*(){if(!YO())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&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=tb(eb({},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=tb(eb({},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(sk.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 cb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:bV,data:t,responseCommand:SV.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:kV,commandDesc:"unpublish",responseCommand:SV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Sb.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),tP){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:BV,data:this._mediaSettings,responseCommand:SV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return cb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?ok.AUXILIARY:ok.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),QO()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return cb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===ok.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===sk.INACTIVE&&(yield this.setTransceiverDirection(sk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return cb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;YO()&&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===ok.VIDEO&&e instanceof hM&&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===Uk||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=rU(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===ok.VIDEO)return!0;return!1}removeSender(e){let t=null;YO()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&Lw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return cb(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?ok.AUXILIARY:ok.MAIN," stream")),QO()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return cb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===ok.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(sk.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return cb(this,null,(function*(){if(!NN)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._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(sk.INACTIVE,"|").concat(sk.RECVONLY,"|").concat(sk.SENDONLY,")")))&&o++,t.includes(o)){if(e===sk.INACTIVE&&i.includes("a=".concat(sk.RECVONLY)))return r=!0,"a=".concat(e);if(e===sk.SENDONLY&&i.includes("a=".concat(sk.INACTIVE)))return r=!0,"a=".concat(sk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return cb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===ok.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===ok.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===ok.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return cb(this,null,(function*(){var t;let i,r=null==(t=this._peerConnection)?void 0:t.getSenders();if(!r||0===r.length||!e.mediaTrack)return;if(i=QO()?e.kind===ok.AUDIO?r[0]:r[1]:r.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(n?ok.AUXILIARY:ok.MAIN," stream")),e.kind===ok.AUDIO?yield i.replaceTrack(e.outMediaTrack):e.kind===ok.VIDEO&&(n?r[3]&&(yield r[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return cb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(lU);NN&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let r=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===ok.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:yV,data:n,responseCommand:SV.UPDATE_OFFER_RESULT,timeout:Mk,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(Ob){throw this._log.error(Ob),Ob}}))}setBandwidth(e){return cb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n,sdp:o}=e;return function*(){if(!eP())return o?r===ok.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(QO()){let t=0;r===ok.VIDEO&&(t=n===ok.SMALL?2:n===ok.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===ok.VIDEO?t.updateVideoBandwidthRestriction(o,i,n):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let r="AS";NN&&(r="TIAS",t*=1e3);let n=0,o=-1;return i===ok.SMALL?n=1:i===ok.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 NN&&(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 cb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(wb){throw this.closePeerConnection(!0),this.uninstallEvents(),wb}}))}exchangeSDP(){return cb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(wb){throw wb}}))}createOffer(){return cb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(lU);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(wb){throw wb}}))}doExchangeSDP(){let e={command:CV,responseCommand:SV.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof fM||this.localAuxVideoTrack instanceof fM,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=rU(e);return r.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),nU(r)}acceptAnswer(e){return cb(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?ok.AUXILIARY:ok.BIG;s=yield this.setBandwidth({bandwidth:e,type:ok.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:ok.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:ok.VIDEO,videoType:ok.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(ZU){throw this._log.error("failed to accept remote answer ".concat(ZU)),ZU}}))}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(RV,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return cb(this,null,(function*(){if(!(ab(dU.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:kV,responseCommand:SV.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(wk){let t=Ow(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)&&tw.emit(TO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{rU(e).media.forEach(((e,t)=>{if(e.type===ok.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===Uk&&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(wk){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ok.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===ok.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===ok.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===ok.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===ok.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Fk?(this._log.error(hN.NOT_SUPPORTED_H264ENCODE),new Ib({code:Sb.NOT_SUPPORTED_H264,message:$D({key:uN.NOT_SUPPORTED_H264ENCODE})})):new Ib({code:Sb.UNKNOWN,message:$D({key:uN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:SV.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},uU=dU;ob([ZL((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:Sb.API_CALL_ABORTED,message:$D({key:uN.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this._emitter.off("closed",n)}))}))}))],uU.prototype,"publish",1),ob([$L(tU.prototype.afterConnect),XL(tU.prototype.beforeConnect)],uU.prototype,"connect",1);var hU=uU,pU=class{constructor(e,t){this.room=e,sb(this,"_log"),sb(this,"_prevReportTime"),sb(this,"_prevReport",{}),sb(this,"_prevEncoderImplementation"),sb(this,"_prevQualityLimitationReason"),sb(this,"_prevAuxQualityLimitationReason"),sb(this,"_prevDecoderImplementationMap",new Map),sb(this,"totalBytesSent",0),sb(this,"totalBytesReceived",0),sb(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return cb(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),r=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var n;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===ok.VIDEO){let n,o;if(i.ssrc===r.video?(n=ok.VIDEO,o=e.localMainVideoTrack):i.ssrc===r.small?n=ok.SMALL:i.ssrc===r.auxiliary&&(o=e.localAuxVideoTrack,n=ok.AUXILIARY),!n)return;t[n].bytesSent=i.bytesSent,t[n].packetsSent=i.packetsSent,t[n].framesEncoded=i.framesEncoded,Mw(i.keyFramesEncoded)||(t[n].keyFramesEncoded=i.keyFramesEncoded),Mw(i.nackCount)||(t[n].nackCount=i.nackCount),Mw(i.pliCount)||(t[n].pliCount=i.pliCount),Mw(i.retransmittedPacketsSent)||(t[n].retransmittedPacketsSent=i.retransmittedPacketsSent),Mw(i.totalEncodeTime)||(t[n].totalEncodeTime=i.totalEncodeTime),Mw(i.totalPacketSendDelay)||(t[n].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===r.video?(!Mw(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!Mw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===r.auxiliary&&!Mw(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevAuxQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevAuxQualityLimitationReason=i.qualityLimitationReason)}else t.audio.bytesSent=i.bytesSent,t.audio.packetsSent=i.packetsSent;else"candidate-pair"===i.type?BO(i)&&Vw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===ok.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===ok.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(ok.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(ok.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!Mw(i.audioLevel)&&(null==(n=e.localMainAudioTrack)?void 0:n.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!Mw(i.frameWidth)){let n=ok.SMALL;i.trackIdentifier===e.getVideoTrackId(ok.VIDEO)||i.ssrc===r.video?n=ok.VIDEO:(i.trackIdentifier===e.getVideoTrackId(ok.AUXILIARY)||i.ssrc===r.auxiliary)&&(n=ok.AUXILIARY),t[n].frameWidth=i.frameWidth,t[n].frameHeight=i.frameHeight,t[n].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(iL){this._log.warn("failed to getStats on sender connection ".concat(iL))}return t}))}getReceiverStats(e){return cb(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:r}=e,{muteState:n,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===ok.AUDIO){if(i.ssrc!==r.audio||!n.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,t.audio.p2pDelay=o.stat.end2EndDelay,i.jitterBufferDelay&&(t.audio.totalJitter=i.jitterBufferDelay,t.audio.totalJitterCount=i.jitterBufferEmittedCount),t.hasAudio=!0}else{if(NN&&0===i.bytesReceived)return;let s;i.ssrc===r.video&&n.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,n.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===r.auxiliary&&n.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&BO(i)&&Vw(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);Mw(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===r.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===r.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!Mw(i.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&i.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(Ob){this._log.warn("failed to getStats on receiver connection ".concat(Ob))}return t}))}getStats(e,t){return cb(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=qw(),n=yield e.getStats(),o=qw();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(JL(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r}=e;if(!JL(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*dN,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*dN);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:n}=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(gk)),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};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=r.get("".concat(e.userId,"_").concat(Tk)),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};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let r=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*r/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let r=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(r=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(r,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/n),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/n),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/n),oD&&115===vD()&&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),Mw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),Mw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),Mw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),Mw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),Mw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/n)),Mw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/n))}));let a=o.msg_down_stream_info;return i.msg_down_stream_info=i.msg_down_stream_info.filter((e=>a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid)))),i.msg_down_stream_info.forEach((e=>{let t=a.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(JL(e.msg_audio_status)||JL(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,r=t.msg_audio_status,o=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)/o)||0;let s=this.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);s&&(s.remoteAudioTrack.stat.jitterBufferDelay=i.uint32_audio_cache_ms),i.uint32_audio_origin_lost=this.getDifferenceValue(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/n),i.uint32_audio_total_bitrate=Math.round(8*a/n)}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,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(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/n);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/n),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/n)}))}})),i}getStatsReport(e){return cb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:r,freezeMap:n}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,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}},mU=nb(lb()),_U=class extends mU.default{constructor(e){let{signalChannel:t,room:i}=e;super(),sb(this,"_room"),sb(this,"_signalChannel"),sb(this,"_log"),sb(this,"_uplinkRTT",0),sb(this,"_uplinkLoss",0),sb(this,"_downlinkRTT",0),sb(this,"_downlinkLoss",0),sb(this,"_downlinkPrevStatMap",new Map),sb(this,"_downlinkLossAndRTTMap",new Map),sb(this,"_interval",-1),sb(this,"_uplinkNetworkQuality",0),sb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=SO.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this._uplinkRTT,", loss: ").concat(this._uplinkLoss)),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:i}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(t,", loss: ").concat(i))}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(SV.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(mV,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.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 cb(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)===bk.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;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 cb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!zO())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&&Vw(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===ok.AUDIO||e.mediaType===ok.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(iL){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!==bk.DISCONNECTED&&e.connectionState!==bk.FAILED&&e.connectionState!==bk.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=AP.run(rN,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];tw.emit(TO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(_U.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})}),{delay:2e3})):this._log.info("network quality calculating is already started")}stop(){this._log.debug("stopped"),-1!==this._interval&&(AP.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})}}))}},fU=_U;sb(fU,"EVENT_NETWORK_QUALITY","0");var gU=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._eventMap=new Map,this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=SO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&Lw(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 Gw(o)?o.catch((e=>SO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(wk){SO.error("".concat(t.name,"() error observed ").concat(wk))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=AP.run(rN,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Nb,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,GD().then((e=>{this._basicInfo.string_os_version=zD(),this._basicInfo.string_device_name=e&&e.mobile?e.model:this._basicInfo.string_os_version}))}addEvent(e,t){return this._eventMap.set(e,t),tw.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("unload",this.handleUnload),this._room.once("banned",(()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId}))),this.addEvent(TO.JOIN_START,this.handleJoinStart).addEvent(TO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(TO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(TO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(TO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(TO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(TO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(TO.JOIN_FAILED,this.handleJoinFailed).addEvent(TO.LEAVE_START,this.handleLeaveStart).addEvent(TO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(TO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(TO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(TO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(TO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(TO.PUBLISH_START,this.handlePublishStart).addEvent(TO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(TO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(TO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(TO.PLAY_TRACK_START,this.handlePlayStart).addEvent(TO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(TO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:r}=e;!jw(t)||!this.hitTest(t.room)||"PLAYING"===i&&(r===ok.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(TO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(TO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(TO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(TO.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(TO.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)=>tw.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),AP.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage()),e.params&&(Mw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Mw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),Mw(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()):Sb.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:tb(eb({},EU),{msg_user_info:new SU({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 SU({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(!jw(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(!jw(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_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:r,uint32_video_height:n}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=r,this._localStreamStat.totalVideoHeight+=n,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/dN*100)>0&&(this._localStreamStat.totalAudioLevel+=e/dN,this._localStreamStat.audioLevelCount++)}i.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*$C(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/dN*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/dN,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,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():Sb.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&lk))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&hk))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&uk))>=0}hitTest(e){return e===this._room}checkStorage(){return cb(this,null,(function*(){try{let e=IO.getItem(this._storageKey);e&&(yield this.upload(e),IO.deleteItem(this._storageKey))}catch(nL){this._log.warn(nL)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&IO.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,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,ok.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,ok.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,TU);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>TU&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+TU):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>TU&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+TU):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>TU&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+TU)}getReportData(){this._basicInfo.uint32_networkType=Iw();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new SU({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:tO(this._signalInfo.relayIp),uint32_client_ip:tO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*$C(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:tO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return mO(e),e}report(){return cb(this,null,(function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),IO.deleteItem(this._storageKey),this.initData()}catch(nL){this._log.warn(nL)}}))}upload(e){return cb(this,null,(function*(){if(UD&&!uD||0===e.msg_path_enter_room.uint64_start_time||[Fb,Bb,Hb].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=yield lN(e),r=i instanceof ArrayBuffer,n="".concat(gw(t,qb.KEY_POINT),"&gzip=").concat(+r),o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,i)),o||cN({url:n,body:i}),this.uploadKVStat(_L),this.uploadKVStat(mL)}))}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return cb(this,null,(function*(){let t=e.getReportData();if(0===t.stats_count.length&&0===t.stats_distribution.length)return;t.msg_sdk_basic_info=tb(eb({},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 lN(t),r="".concat(gw(+this._room.sdkAppId,qb.KV_STAT),"&gzip=").concat(+(i instanceof ArrayBuffer)),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(r,i)),n||cN({url:r,body:i})}))}};ob([Ix({settings:{timeout:500,retries:3}})],gU.prototype,"upload",1);var TU=5e3,EU={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},SU=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},yU=gU,IU=class{constructor(){sb(this,"_startTime"),sb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=qw())}stop(){0===this._endTime&&(this._endTime=qw())}getDuration(){return 0===this._endTime?qw()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},vU=class{constructor(e){sb(this,"_room",null),sb(this,"_durationMap"),sb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(TO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(TO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(TO.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"),ok.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),ok.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),ok.VIDEO);let s=null==(n=this._room)?void 0:n.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,ok.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,ok.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,ok.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>tw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>tw.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 IU,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,ok.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let e=new IU,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,ok.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,ok.AUDIO),this.stopDurationItem(o,ok.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new IU,o=this._durationMap.get(r);o?this.isRecording(o[t])||o[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===ok.AUDIO?[n]:[],video:t===ok.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()}},AU=class{constructor(e){sb(this,"_room"),sb(this,"_renderFreezeMap",new Map),sb(this,"_isVideoPlayingEventFiredMap",new Map),sb(this,"_dataFreezeMap",new Map),sb(this,"_monitorFreezeData",new Map),sb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(TO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(TO.PLAY_TRACK_START,this.onPlayTrackStart).set(TO.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(TO.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(TO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:r,type:n}=e;if(jw(t)&&this.hitTest(t.room)&&n===ok.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}r===ok.MUTE?this.onVideoTrackMuted(t):r===ok.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(TO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>tw.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>tw.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 IU;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>Hk?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 cb(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=qw();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=qw();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!jw(t)||!this.hitTest(t.room)||t.kind!==ok.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()<Hk&&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=qw()-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()}},RU=nb(lb(),1),CU=[-1,-1,1,-1,-1,1,1,1],bU=[0,0,1,0,0,1,1,1],kU=class extends EP{constructor(e,t){if(super(),this.context=e,sb(this,"name"),sb(this,"input"),sb(this,"output"),sb(this,"texture"),sb(this,"ctx2d",null),sb(this,"fbo"),sb(this,"width",0),sb(this,"height",0),sb(this,"x",0),sb(this,"y",0),sb(this,"program"),sb(this,"vertexShader"),sb(this,"fragmentShader"),sb(this,"totalFrames",0),sb(this,"dropFrames",0),sb(this,"matchInputSize",!0),sb(this,"texCoordBuffer"),sb(this,"positionBuffer"),sb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),sb(this,"cost",0),sb(this,"_canvas",null),sb(this,"_image"),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof FU){if(e.ctx&&t.create2d){let e=document.createElement("canvas"),t="function"==typeof e.transferControlToOffscreen?e.transferControlToOffscreen():e;t.width=this.width,t.height=this.height,this.ctx2d=t.getContext("2d"),this._image=t,this._canvas=t}}else try{let i=e.ctx;this.texCoordBuffer=this.createBuffer(bU),this.positionBuffer=this.createBuffer(CU),!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(Ob){this.context.destroy(Ob)}}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 UU&&this.render(e)||this.context instanceof FU&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),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 UU){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},eb({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}};ob([fP(EP.INIT,"connected",{sync:!0})],kU.prototype,"connect",1),ob([fP("connected",EP.INIT,{ignoreError:!0,sync:!0})],kU.prototype,"disconnect",1),ob([fP([],"closed",{sync:!0})],kU.prototype,"close",1);var NU=[0,1,1,1,0,0,1,0],DU=class extends kU{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),sb(this,"_intervalId",0),sb(this,"_sequence",0),sb(this,"checkGLError",!1),e instanceof FU?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(NU)}start(e){this._intervalId=AP.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(AP.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof UU){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),AP.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},wU=class extends DU{constructor(e,t){super(e,t),sb(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,r)},r=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,r)};e instanceof UU&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}},OU=class extends wU{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},PU=class extends wU{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;SO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(SO.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))}},LU=class extends kU{constructor(e,t){super(e,eb({name:"imageSource"},t)),sb(this,"_lastImage"),sb(this,"_totalFrames",0),sb(this,"_autoResize",!1),this._autoResize=!1!==(null==t?void 0:t.autoResize)}_render(e,t){let{width:i,height:r}=this;if(this.image instanceof HTMLVideoElement){if(Lw(this.image.getVideoPlaybackQuality)&&!DD){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}if(({videoWidth:i,videoHeight:r}=this.image),!i||!r)return!1;this.image.width=i,this.image.height=r}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:r}=this.image),this.image!==this._lastImage)this._lastImage=this.image;else if(i===this.width&&r===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:r}=this.image),this._lastImage=this.image);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,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,r)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},MU=class extends LU{constructor(e,t,i){super(e,i),sb(this,"_player"),this._player=new $P({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(e){this._player.setTrack(e)}close(){super.close(),this._player.stop()}},xU=class extends EP{constructor(e){super(),sb(this,"frameRate"),sb(this,"_canvas"),sb(this,"log"),sb(this,"hasAlpha",!1),sb(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new MU(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new wU(this,e)}createVideoImageSource(e,t){return new LU(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},VU={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},UU=class extends xU{constructor(){super(...arguments),sb(this,"defaultProgam"),sb(this,"defaultVShader"),sb(this,"defaultFShader"),sb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",VU),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,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}};ob([fP(EP.INIT,"created",{sync:!0})],UU.prototype,"create",1),ob([fP("created",EP.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],UU.prototype,"destroy",1);var FU=class extends xU{constructor(){super(...arguments),sb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};ob([fP(EP.INIT,"created",{sync:!0})],FU.prototype,"create",1),ob([fP("created",EP.INIT,{ignoreError:!0,sync:!0})],FU.prototype,"destroy",1);var BU=[1,0,0,0,1,1,0,1],HU=class extends kU{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof UU)try{this.setTexBuffer(BU)}catch(wb){e.destroy(wb)}}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)}},jU=class{constructor(e,t){this.node=e,this.layout=t,sb(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}},GU=class extends kU{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),sb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new jU(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 UU&&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},eb({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 UU))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(iL){}}))}},WU=class extends MU{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log}),sb(this,"ready",!1),sb(this,"_bgTexture"),sb(this,"_waterMarkTexture"),sb(this,"_lastMaskTexture"),sb(this,"_lastMaskFbo"),sb(this,"_textureValid",!1),sb(this,"_selfieTextureValid",!1),sb(this,"_selfieSegmentation"),sb(this,"wasm"),sb(this,"_prePrograme"),sb(this,"_segmentationMask"),sb(this,"_weixin",!1),this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return cb(this,null,(function*(){let t=e.Wasm,i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:r,height:n}=e.waterMark;this.wasm.setWaterMark(t,i,r,n)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._weixin){let e=this.context.createShader(i.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(i.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),i.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0}))}onPredict(e){let t=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():this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality&&!DD){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:r}=this.image;this.image.width=i,this.image.height=r;let n=!1;if(this.totalFrames)this._weixin?this.useTexture():this._selfieSegmentation.bindTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),n=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===r&&n?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,r),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._selfieSegmentation.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,i,r):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,i,r,0)),this._selfieSegmentation.send(i,r)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}},JU=class extends RU.EventEmitter{constructor(e){super(),this.room=e,sb(this,"videoContext"),sb(this,"_glVideoContext"),sb(this,"_2dVideoContext"),sb(this,"destination"),sb(this,"smallVideoContext"),sb(this,"smallDestination"),sb(this,"smallTrackSource"),sb(this,"smallImageSource"),sb(this,"_isMirror",!1),sb(this,"cameraTrack"),sb(this,"cameraNode"),sb(this,"mirrorNode"),sb(this,"mixNode"),sb(this,"screenTrack"),sb(this,"screenNode"),sb(this,"selfModel",!1),sb(this,"blurRadius",3),sb(this,"arTrack"),sb(this,"Wasm"),sb(this,"waterMarkNode"),sb(this,"_waterMarkOption"),sb(this,"watermarkImageList",[]),sb(this,"_isMixScreen",!1),sb(this,"_virtualBackground"),sb(this,"virtualBackgroundInstance"),sb(this,"isUsingArTrack",!1),sb(this,"_bgAssetPath"),sb(this,"log",SO.createLogger({id:"vm"})),sb(this,"_checkId",0),sb(this,"_use2d",!1),sb(this,"_autoSwitchRenderMode",!0),sb(this,"_selfieSegmentation"),e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new FU({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _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 FU({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new UU({frameRate:15,logger:this.log,name:"m"});try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",((e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()}))}catch(wb){this.emit("error",{reason:"create",error:wb}),this.sendCreateResult("videoCtxGl",wb)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=AP.run(oN,(()=>{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(),AP.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(DD||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg)&&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?_L.addFailedEvent({key:t,error:e}):_L.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 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 PU(this.smallVideoContext,r)),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),DD&&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(Ob){this.log.error("set main output failed",Ob)}}update(){return cb(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.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),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=new OU(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new WU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=r.frameRate,this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new HU(this.videoContext)),i=i.connect(this.mirrorNode),i.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new GU(this.videoContext),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 fM)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof hM)return this.log.info("change video input",null==(i=e.mediaTrack)?void 0:i.label),this.setCameraTrack(e);if(e instanceof vM){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);let t=e.mediaTrack;if(17===LD&&!e.source&&e.player.element){let t=new FU({frameRate:15,logger:this.log,name:e.userId});t.create({alpha:!1});let i=t.createVideoImageSource(e.player.element);e.source=i;let r=new DU(t);i.connect(r),e.player.setCanvas(t._canvas)}return e.setOutputMediaStreamTrack(t)}this.log.warn("change unknown input",null==(n=e.mediaTrack)?void 0:n.label)}removeInput(e){var t;e instanceof fM?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof hM?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof vM&&e.source&&e.source.context.destroy()}setCameraTrack(e){return cb(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 cb(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:Sb.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)})),hO(i.toDataURL())}))}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some((t=>t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((e=>e.type!==t))),this.watermarkImageList.push(e))}setWatermark(e){return cb(this,null,(function*(){let t;try{t=yield hO((null==e?void 0:e.imageElement)||e.imageUrl)}catch(c){throw new Ib({code:Sb.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:o=t.height,type:s="watermark",zIndex:a=2}=e;this.pushWaterMarkImageList({x:i,y:r,width:n,height:o,image:t,zIndex:a,type:s,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))}))}deleteWatermark(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return cb(this,null,(function*(){this.watermarkImageList=this.watermarkImageList.filter((t=>t.type!==e)),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()}))}freshWatermark(){return cb(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 cb(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virtualBackground=yield hO(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}else this._virtualBackground=void 0;this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return cb(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}},KU=0,zU=class extends EP{constructor(e){super("room"),this.seq=++KU,this.role="anchor",this.localTracks=new Set,this.enableAutoPlayDialog=!0,this.autoReceiveAudio=!0,this.autoReceiveVideo=!0,this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this._isUsingCachedSchedule=!1,this._log=SO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,Uw(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Uw(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Uw(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new yU({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new vU({room:this}),this.badCaseDetector=new AU({room:this}),this.audioManager=new TM(this),this.videoManager=new JU(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoining(){return"joining"===this.state.toString()}get isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return cb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return cb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return cb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(xw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Dw(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?(lw([o,o]),Ub("https://".concat(o))):(r&&Ub(r),n&&lw(n))}tw.once(TO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:cw.main,sched_back_domain:cw.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return cb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return cb(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 cb(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:Sb.INVALID_OPERATION,message:$D({key:uN.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(hN.INVALID_DESTROY),new Ib({code:Sb.INVALID_OPERATION,message:$D({key:uN.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,tw.emit(TO.ROOM_DESTROY,{room:this})}schedule(e,t){return cb(this,null,(function*(){var i,r;let n=qw();try{let{isCached:o,result:s,detailCost:a}=yield aw({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Nb,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(cO(s,{keysToExclude:["username","credential"]}))),o&&tw.once(TO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=eb(eb({},this.scheduleResult),s),Vw(null==(i=s.config)?void 0:i.retryCount)&&Nk(s.config.retryCount),xw(null==(r=s.config)?void 0:r.loggerDomain)&&Ub(s.config.loggerDomain),tw.emit(TO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),_L.addSuccessEvent({key:521700,cost:qw()-n,split:50})}catch(o){throw _L.addFailedEvent({key:521700,error:o}),o}}))}},qU=nb(lb()),YU=nb(gb()),QU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n}=e,o=rU(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:ok.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:ok.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(XU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),n&&s.media.push(o.media.find((e=>"dc"===e.mid))),nU(s)},XU=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:ok.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:ok.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;a<i.video.codecs.length;a++)$U(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));$U(s,i.video.codecs[e])}else if(o)for(let a=0;a<r.video.codecs.length;a++)$U(s,r.video.codecs[a]);else $U(s,r.video.codecs[0]);return s.payloads=s.payloads.trim(),s},$U=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...(t.rtcpfb||t.rtcpFb).map((e=>({payload:t.payload,type:e.id,subtype:e.params[0]})))],e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))};var ZU,eF=e=>{let t=YU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===ok.AUDIO||e.type===ok.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===ok.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===ok.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),YU.default.write(t)},tF=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}},iF=class{constructor(e,t){this._singlePC=e,this._log=t,sb(this,"_seiMessageList",[]),sb(this,"_smallSeiMessageList",[]),sb(this,"_seiPayloadType",243),sb(this,"_seiAbortMap",new Map),sb(this,"_nonSeiAbortMap",new Map),sb(this,"onSEIMessage",null)}isRunning(e){return this._seiAbortMap.has(e)}start(e){let t=e.direction===ok.TRANSCEIVER_DIRECTION_SENDONLY,i=(t?e.sender:e.receiver).createEncodedStreams(),r=i.readable,n=i.writable,o=new TransformStream({transform:t?(t,i)=>this.encodeVideoFrame(t,i,e):(t,i)=>this.decodeVideoFrame(t,i,e)}),s=new AbortController;r.pipeThrough(o).pipeTo(n,s).catch((e=>{"destroy"!==e&&this._log.warn(e)})),this._seiAbortMap.set(e,s)}restart(e){this.stop(e),this.start(e)}stop(e){var t;null==(t=this._seiAbortMap.get(e))||t.abort(),this._seiAbortMap.delete(e)}destroy(){this._seiAbortMap.forEach((e=>e.abort("destroy"))),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach((e=>e.abort("destroy"))),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach(((e,t)=>{var i,r;if("inactive"!==e.direction&&e.mid)if(t<4)1===t||2===t?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let n=(t-4)%3==1,o=(t-4)%3==2;(null==(r=null==(i=e.receiver)?void 0:i.track)?void 0:r.kind)===ok.VIDEO&&(n||o)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}}))}catch(nL){this._log.warn(nL)}}pipeSenderOrReceiver(e){let t=e.direction===ok.TRANSCEIVER_DIRECTION_SENDONLY?e.sender:e.receiver,{readable:i,writable:r}=t.createEncodedStreams(),n=new AbortController;this._nonSeiAbortMap.set(e,n),i.pipeTo(r,n).catch((()=>{}))}push(e,t){var i,r;t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==(r=null==(i=this._singlePC.getPeerConnection())?void 0:i.getSenders()[2])?void 0:r.track)&&this._smallSeiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0,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}encodeVideoFrame(e,t,i){try{let t=2===Number(i.mid)?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&t.length>0&&!this.isEmptyFrame(e)){let i=9-this.getNaluCount(e.data);if(i<=0)return;let r=t.splice(0,i).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 t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));e.data=o,this._log.debug("".concat(r.length," sei sent"))}}catch(Ob){this._log.warn(Ob)}t.enqueue(e)}decodeVideoFrame(e,t,i){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],r=new DataView(e.data),n=0,o=-1,s=-1;for(let i=0;i<e.data.byteLength;i++){let a=r.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,t.push(new tF(new DataView(r.buffer.slice(o,s)))),o=a,s=-1),6!==r.getUint8(i+1)){e.data=new DataView(r.buffer.slice(a)).buffer;break}}n=0}else n=0}this._log.debug("".concat(t.length," sei received")),Lw(this.onSEIMessage)&&t.reverse().forEach((e=>{let t=Number(i.mid);this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,mid:t,streamType:(t-4)%3==2?"auxiliary":"main"})}))}}catch(Ob){this._log.warn(Ob)}t.enqueue(e)}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 tF(new DataView(new Uint8Array(n).buffer),!0)}},rF=((ZU=rF||{}).TRACK="track",ZU.DATA_CHANNEL_MESSAGE="data_channel_msg",ZU[ZU.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",ZU[ZU.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",ZU.RECONNECTED="spc-reconnected",ZU.RECONNECT_FAILED="spc-reconnect-failed",ZU.ERROR="error",ZU.SEI_MESSAGE="sei-message",ZU),nF=0,oF=!1,sF=new Set,aF=1,cF=class extends qU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:r}=e;super(),sb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),sb(this,"currentState","DISCONNECTED"),sb(this,"_room"),sb(this,"_signalChannel"),sb(this,"_peerConnection",null),sb(this,"_datachannel",null),sb(this,"_enableCustomMessage"),sb(this,"_log"),sb(this,"_downlinkMIDMap",new Map),sb(this,"_downlinkMIDUserIDMap",new Map),sb(this,"_reconnectionTimer",-1),sb(this,"reconnectionCount",0),sb(this,"clientAbility"),sb(this,"_serverAbility",null),sb(this,"addDownlinkQueue",new Set),sb(this,"removeDownlinkQueue",new Set),sb(this,"_parsedAnswer",null),sb(this,"_updateSDPPromise",null),sb(this,"_waitForPCConnectedPromise"),sb(this,"_waitForPCConnectedPromiseReject",null),sb(this,"_isSDPLogged",!1),sb(this,"seiCodec",null),this._room=i,this._enableCustomMessage=r,this._signalChannel=t,this._log=SO.createLogger({id:"spc".concat(aF++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&rP&&(this._log.info("create sei codec"),this.seiCodec=new iF(this,this._log),this.seiCodec.onSEIMessage=e=>{this.emit("sei-message",{userId:this._downlinkMIDUserIDMap.get(e.mid),data:e.data,seiPayloadType:e.seiPayloadType,streamType:e.streamType})})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((e=>"h264"===e.codec.toLowerCase()))),e}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return null!=(e=this._serverAbility)&&e.useVp8?"vp8":"h264"}get isUsingH264(){return"h264"===this.videoCodec}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=rU(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&&!Mw(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}}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 cb(this,null,(function*(){let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&rP,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let e=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(e)),"checking"===e&&0===this.stat.iceStartTime?this.stat.iceStartTime=Date.now():"connected"===e&&0===this.stat.iceEndTime&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=e=>this.emit("track",e),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=e=>{let t=new dF(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(ok.AUDIO,{direction:ok.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:ok.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:ok.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:ok.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this.clientAbility=((e,t)=>{var i,r;let n=rU(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(n.media[0].iceUfrag),o.ice.password=n.media[0].icePwd||"",n.fingerprint&&(o.dtls.hash=n.fingerprint.type,o.dtls.fingerprint=n.fingerprint.hash,o.dtls.setup=n.setup||""),n.media[0].fingerprint&&(o.dtls.hash=n.media[0].fingerprint.type,o.dtls.fingerprint=n.media[0].fingerprint.hash),o.dtls.setup=n.media[0].setup||"";let s=n.media[0],a=n.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:r}=e;if(t===c.payload){let e={id:i,params:[]};r&&e.params.push(r),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(r=a.rtp[l+1])?void 0:r.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),_L.addSuccessEvent({key:521707}),this.clientAbility}catch(wk){throw _L.addFailedEvent({key:521707,error:wk}),this._log.error("initialize failed ".concat(wk," \noffer: ").concat(null==e?void 0:e.sdp)),wk}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return cb(this,null,(function*(){var i;try{if("CONNECTED"===this.currentState)return;let r=qw(),n={type:"answer",sdp:QU({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(n),yield this.waitForPeerConnectionConnected(),t||_L.addSuccessEvent({key:521703,cost:qw()-r}),null==(i=this.seiCodec)||i.handleEncodedStreams()}catch(iL){let i=iL instanceof Ib&&iL.code===Sb.API_CALL_ABORTED;throw i||this._log.error("connect failed: ".concat(iL),e),this.reset(),!i&&!this.isReconnecting&&(_L.addFailedEvent({key:521703,error:iL}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),iL}}))}reconnect(){return cb(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(_V,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:HV,responseCommand:SV.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),_L.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),tw.emit(TO.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(wb){if(!this.isReconnecting)return;if(null!=wb&&wb.message.includes("timeout")){let e=Ow(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(null==wb?void 0:wb.code," ").concat(wb)),_L.addFailedEvent({key:521704,error:wb}),this.reconnectionCount>=Dk()&&this._log.warn("SDK has tried reconnect for ".concat(Dk()," 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 cb(this,null,(function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_V,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===bk.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===bk.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===bk.FAILED||e.target.connectionState===bk.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===bk.CONNECTED||e.target.connectionState===bk.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),tw.emit(TO.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,zO()&&0!==this._peerConnection.getReceivers().length&&e?e.state:Ck):Ck}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(rF.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return cb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(BO(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&&yw(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();this._waitForPCConnectedPromiseReject=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:Sb.API_CALL_ABORTED,message:$D({key:uN.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{tw.off(TO.LEAVE_SUCCESS,r,this),this.off(rF.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{n();let e=new Ib({code:Sb.API_CALL_TIMEOUT,message:"connection timeout"});var i;nF+=1,i=this._signalChannel.isConnected,nF>2&&!oF&&0===sF.size&&i&&(this._log.warn("firewall restriction"),oF=!0,this.emit(rF.FIREWALL_RESTRICTION)),t(e)}),Jk);tw.on(TO.LEAVE_SUCCESS,r,this),this.on(rF.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return cb(this,null,(function*(){var t;if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP(),null==(t=this.seiCodec)||t.handleEncodedStreams(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(Ob){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(Ob)),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().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=ok.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));this._parsedAnswer||(this._parsedAnswer=rU(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(ok.AUDIO,{direction:ok.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:ok.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(ok.VIDEO,{direction:ok.TRANSCEIVER_DIRECTION_RECVONLY}),o=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=XU({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:rU(this._peerConnection.localDescription.sdp),useAllCodec:!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=ok.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(ok.MAIN," ").concat(l,"-audio")}],s.direction=ok.TRANSCEIVER_DIRECTION_SENDONLY,s.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(ok.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(ok.MAIN," ").concat(l,"-bigvideo")}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],a.direction=ok.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(ok.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(ok.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(ok.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 cb(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=rU(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 cb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(eP()){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=rU(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=rU(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=rU(this._peerConnection.remoteDescription.sdp));let s=NN?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:NN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:NN?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:NN?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:NN?1e3*i:i}]),r&&(o.media[2].bandwidth=[{type:s,limit:NN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:NN?1e3*r:r}]),n&&(o.media[3].bandwidth=[{type:s,limit:NN?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:NN?1e3*n:n}]);let a={type:"offer",sdp:nU(o)};return this.updateSDP({localDescription:a})}setScaleResolutionDownBy(e,t){if(1===t)return;let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),i.encodings[0].scaleResolutionDownBy=t,e.setParameters(i)}updateSDP(){let{localDescription:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=nU(this._parsedAnswer);return this._updateSDPPromise=new Promise(((i,r)=>cb(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(ZU){this._log.error(ZU),!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(ZU)}})))),this._updateSDPPromise}filterSDPDirection(){return rU(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:eF(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.seiCodec&&(this.seiCodec.destroy(),this.seiCodec=null),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var i;null==(i=this.seiCodec)||i.push(e,t)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((e=>t[e]))}};ob([sM("reconnect")],cF.prototype,"startReconnection",1),ob([aM((e=>e.userId))],cF.prototype,"addDownlink",1),ob([aM((e=>e))],cF.prototype,"removeDownlink",1),ob([oM(!0)],cF.prototype,"updateSDP",1);var lF=class{constructor(e){sb(this,"tag"),sb(this,"len"),sb(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}},dF=class{constructor(e){sb(this,"tinyId"),sb(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let n=t.getUint16(i+2),o=new lF(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)}))}},uF=new Set;function hF(){let e=Math.floor(4294967296*Math.random());return uF.has(e)?hF():(uF.add(e),e)}var pF=nb(lb()),mF=class extends pF.default{constructor(e){super(),sb(this,"userId"),sb(this,"tinyId"),sb(this,"_sdpSemantics"),sb(this,"_isUplink"),sb(this,"_room"),sb(this,"_log"),sb(this,"_signalChannel"),sb(this,"_currentState","DISCONNECTED"),sb(this,"_prevTime",-1),sb(this,"_enableSEI"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=SO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(tw.emit(TO.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"))}},_F=class extends mF{constructor(e){super(tb(eb({},e),{isUplink:!0})),sb(this,"localMainAudioTrack",null),sb(this,"localMainVideoTrack",null),sb(this,"localAuxAudioTrack",null),sb(this,"localAuxVideoTrack",null),sb(this,"_isPublishingAux",!1),sb(this,"_publishingLocalAudioTrack"),sb(this,"_publishingLocalVideoTrack"),sb(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}),sb(this,"_flag",0),sb(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc: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=AP.run(sN,(()=>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(zD()," ").concat(WD())),_L.addCount({key:521e3})}AP.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&&(YO()?(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===ok.AUDIO?n.audio=!0:(n.bigVideo=!0,this._room.videoManager.hasSmall&&(n.smallVideo=!0)))})))}return n}get serverPublishState(){return{audio:!!(this.flag&hk),bigVideo:!!(this.flag&lk),smallVideo:!!(this.flag&dk),auxVideo:!!(this.flag&uk)}}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack)}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.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,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 cb(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;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:Sb.NOT_SUPPORTED_H264,message:$D({key:uN.NOT_SUPPORTED_H264ENCODE})});RN&&115===vD()&&r.profile.width*r.profile.height<=230400&&(t._log.warn("fallback video to 480p"),r.setProfile(rk["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:GV,responseCommand:SV.SPC_PUBLISH_RESULT,data:tb(eb({},t.singlePC.uplinkSSRC),{state:h,muteState:p}),retries:3}),yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:r,smallTrack:u,isAuxiliary:n}),null==(e=t.singlePC.seiCodec)||e.handleEncodedStreams(),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,n)r&&(t.localAuxVideoTrack=r),i&&(t.localAuxAudioTrack=i);else{if(r){t.localMainVideoTrack=r;let{scaleResolutionDownBy:e}=r;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(o=t.localMainAudioTrack)?void 0:o.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(l=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:l.bitrate,auxVideo:null==(d=t.localAuxVideoTrack)?void 0:d.profile.bitrate}),t.sendMediaSettings(),t.installTrackMuteEvents(i,r)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!QO())return;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=null==t?void 0:t.outMediaTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(n){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(r){let e=a[2].sender.replaceTrack(r);l.push(2),c.push(e)}let d=this.setTransceiverDirection(sk.SENDONLY,l);return c.push(d),Promise.all(c)}enableSmall(e){return cb(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(sk.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(sk.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 cb(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&&(yield o[0].replaceTrack(null),s.push(0),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),n&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=tb(eb({},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=tb(eb({},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(sk.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 cb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:bV,data:t,responseCommand:SV.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:kV,commandDesc:"unpublish",responseCommand:SV.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===Sb.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),tP){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:BV,data:this._mediaSettings,responseCommand:SV.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return cb(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?ok.AUXILIARY:ok.MAIN," stream")),YO()&&(yield this.addTrackByTransceiver(e,t))}))}addTrackByTransceiver(e,t){return cb(this,null,(function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===ok.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===sk.INACTIVE&&(yield this.setTransceiverDirection(sk.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return cb(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?ok.AUXILIARY:ok.MAIN," stream")),YO()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return cb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===ok.AUDIO)yield i[0].sender.replaceTrack(null);else{let e=t?3:1;yield i[e].sender.replaceTrack(null),1===e&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(sk.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return cb(this,null,(function*(){if(!NN)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._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(sk.INACTIVE,"|").concat(sk.RECVONLY,"|").concat(sk.SENDONLY,")")))&&o++,t.includes(o)){if(e===sk.INACTIVE&&i.includes("a=".concat(sk.RECVONLY)))return r=!0,"a=".concat(e);if(e===sk.SENDONLY&&i.includes("a=".concat(sk.INACTIVE)))return r=!0,"a=".concat(sk.RECVONLY)}return i})).join("\r\n");r&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return cb(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;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(r.kind," track on ").concat(n?ok.AUXILIARY:ok.MAIN," stream")),r.kind===ok.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===ok.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r)))}))}setBandwidth(e){return cb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:r,videoType:n}=e;return function*(){if(t.singlePC){let e={};r===ok.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:RV,responseCommand:SV.MUTE_RESULT,data:this.muteState,retries:3}).catch((()=>{})))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&tw.emit(TO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ok.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===ok.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===ok.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===ok.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===ok.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===Fk?(this._log.error(hN.NOT_SUPPORTED_H264ENCODE),new Ib({code:Sb.NOT_SUPPORTED_H264,message:$D({key:uN.NOT_SUPPORTED_H264ENCODE})})):new Ib({code:Sb.UNKNOWN,message:$D({key:uN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:SV.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return cb(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};function fF(e){return Object.keys(e).filter((t=>e[t]))}var gF=class extends mF{constructor(e){super(tb(eb({},e),{isUplink:!1})),sb(this,"_flag",0),sb(this,"role","anchor"),sb(this,"remoteAudioTrack"),sb(this,"remoteVideoTrack"),sb(this,"remoteAuxiliaryTrack"),sb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new IM(this._room,this),this.remoteVideoTrack=new vM(this._room,this),this.remoteAuxiliaryTrack=new AM(this._room,this),this.initialize()}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Zw(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===ok.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let 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;if(!t.id.includes(this.tinyId))return;let r=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(r," ").concat(i.kind));let n=ok.AUDIO;i.kind===ok.VIDEO&&(n=r===ok.MAIN?ok.VIDEO:ok.AUXILIARY);let o=this.remoteAudioTrack;n===ok.VIDEO?o=this.remoteVideoTrack:n===ok.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}subscribe(e,t){return cb(this,null,(function*(){try{if(this._log.info("subscribe ".concat(t," ").concat(fF(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(Ob){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(Ob.message," ").concat(JSON.stringify(this.muteState))),new Ib({code:Sb.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):Ob}}))}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"),AD&&bD<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return cb(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=eb({},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(fF(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=DV,n=SV.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},r=wV,n=SV.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:$D({key:uN.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 cb(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*(){var r;if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let i={audioSsrc:hF(),bigVideoSsrc:hF(),bigVideoRtxSsrc:hF(),auxVideoSsrc:hF(),auxVideoRtxSsrc:hF()},{audioSsrc:r,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:r,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let r=yield e._signalChannel.sendWaitForResponseWithRetry({command:WV,responseCommand:SV.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(n){throw yield e.removeDownlink(),n}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{null!=(r=e._room.scheduleResult.config)&&r.jitterDelay&&e.setJitterBufferDelay(e._room.scheduleResult.config.jitterDelay,e._room.scheduleResult.config.jitterDelayAux)}}}()}))}removeDownlink(){return cb(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),this.setJitterBufferDelay(0),yield this.singlePC.removeDownlink(this.userId))}))}setJitterBufferDelay(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.singlePC||!this._peerConnection)return;this._log.info("set jitterBuffer main: ".concat(e," aux: ").concat(t));let i=this.singlePC.getReceiversByUserId(this.userId);return this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e,this.remoteAuxiliaryTrack.jitterBufferDelay=t,new Promise((r=>{this.doSetJitterBufferDelay({delay:e,auxDelay:t,receivers:i,resolve:r})}))}doSetJitterBufferDelay(e){let{delay:t,auxDelay:i,receivers:r,resolve:n}=e,o=-1;try{if(0===t)return r.forEach((e=>e.jitterBufferTarget=0)),n();if(r.forEach((e=>{var r;let n=e.track===this.remoteAuxiliaryTrack.outMediaTrack,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();o=setTimeout((()=>{this.doSetJitterBufferDelay({delay:t,auxDelay:i,receivers:r,resolve:n})}),1e3)}catch(s){this._log.warn("set jitterBuffer delay error: ".concat(s)),clearTimeout(o),n()}}};ob([oM(),ZL((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:Sb.API_CALL_ABORTED,message:$D({key:uN.CONNECTION_ABORTED,data:e})}))};this.on("closed",n),e.apply(this,i).then(t,r).finally((()=>{this.off("closed",n)}))}))}))],gF.prototype,"subscribe",1),ob([oM()],gF.prototype,"unsubscribe",1),ob([aM((()=>"jitter"))],gF.prototype,"setJitterBufferDelay",1);var TF=gF;var EF=nb(lb());var SF=class extends EF.EventEmitter{constructor(e,t){super(),this.room=e,this.signalChannel=t,sb(this,"log"),sb(this,"cmdIdSeqMap",new Map),sb(this,"messageMap",new Map),this.log=SO.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(SV.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}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(zV,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||Math.abs(r.lastSeq-e.seq)>SF.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 this.emit("message",e)}}emitMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];var i;let r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),n=e;if(r){if(t){let e=[...r.cachedMessageMap.values()].sort(((e,t)=>e.message.seq-t.message.seq));e[0]&&(n=e[0].message)}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.emit("message",n);let o=null==r?void 0:r.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},yF=SF;sb(yF,"SEQ_INTERVAL",300);var IF,{isString:vF,isUndefined:AF,getNetworkType:RF,isEmpty:CF}=Cb,bF=class extends zU{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=XO,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._turnServers=[],this._syncUserListInterval=-1,this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160},this.enableSEI=!1,this._enableAudioVolumeEvaluation=!1,this._audioVolumeIntervalId=0,this._enableMultiAuxStream=!1,this._pureAudioPushMode=!1,this.enableHWEncoder=!1,this._stats=new pU(this,this._log),this.userManager=new HM(this.userId,this._log),this._version=Nb,this.sdpSemantics=Uk,AF(e.sdpSemantics)?vO.isUnifiedPlanDefault()&&(this.sdpSemantics=Vk):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(RF())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!AF(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&XO,!AF(e.enableSPC)&&XO&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return cb(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)YC.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&zC)for(var r of zC(e))t.indexOf(r)<0&&QC.call(e,r)&&(i[r]=e[r]);return i})(e,[]);tw.emit(TO.REMOTE_PUBLISH_STATE_CHANGED,eb({room:this},t)),this.emit("remote-publish-state-changed",eb({},t))})),this._joinOptions=e,new Promise(((t,i)=>cb(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===Sb.SPC_INITIALIZED_FAILED))return i(o);null==(r=this._signalChannel)||r.destroy(),yield this.initialize()}yield this.doJoin(e,null==(n=this.singlePC)?void 0:n.clientAbility),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(o){i(o)}this._joinReject=null}))))}))}initSinglePC(){return cb(this,null,(function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new cF({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(wb){throw this.fallbackToMPC(),new Ib({code:Sb.SPC_INITIALIZED_FAILED,message:null==wb?void 0:wb.message})}}}))}doJoin(e,t){return new Promise(((i,r)=>cb(this,null,(function*(){var n,o,s;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this._signalChannel.once(pV,(e=>{this.clearJoinTimeout(),tw.emit(TO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),r(e)})),Uw(null==(o=null==(n=this.scheduleResult)?void 0:n.config)?void 0:o.singlePC)&&XO&&(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:qD(),netType:Iw(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(s=this.scheduleResult.config)?void 0:s.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{r(new Ib({code:Sb.JOIN_ROOM_FAILED,message:$D({key:uN.JOIN_ROOM_TIMEOUT})}))}),c),tw.emit(TO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?jV:IV,a),this._signalChannel.once(SV.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:t,message:n,data:o,tinyId:s}=e.data;tw.emit(TO.JOIN_RECEIVED_CMD_RES,{room:this,code:t}),0===t?(this._log.info("Join room success, start heartbeat"),s&&(this.tinyId=s),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=o.publishers,this.singlePC&&this.singlePC.connect(o.ability).catch((()=>{})),i()):(this._log.error("Join room failed result: ".concat(t," error: ").concat(n)),r(new Ib({code:Sb.JOIN_ROOM_FAILED,extraCode:t,message:$D({key:uN.JOIN_ROOM_FAILED,data:{error:n,code:t}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return cb(this,null,(function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId));let t,i=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,i.push(this.initSinglePC().then((e=>(t=e,e))))),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),i.push(this._signalChannel.connect())),yield Promise.all(i),yield this.doJoin(tb(eb({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),rw.logSuccessEvent({userId:this.userId,eventType:Pk.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(rF.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof _F&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.onSinglePCReconnected()})))};this.singlePC.on(rF.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof hU&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(wk){this._log.warn("reJoin fail ".concat(wk)),this.reset(),rw.logFailedEvent({userId:this.userId,eventType:Pk.REJOIN,error:wk}),this.emit("error",new Ib({code:Sb.JOIN_ROOM_FAILED,message:$D({key:uN.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return cb(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...qV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),r=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(r?"reuse":"setup"," signal channel")),r?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):(this._signalChannel=new YV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this}),this._customMessageManager=new yF(this,this._signalChannel),this._customMessageManager.on("message",(e=>{this.emit("custom-message",e)}))),this._networkQuality||(this._networkQuality=new fU({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(fU.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),kP(this,this._signalChannel).add(mV,(e=>{tw.emit(TO.SIGNAL_CONNECTION_STATE_CHANGED,eb({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(gV,(e=>{this.reset(),this.emit("error",e)})).add(SV.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:r}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:r})})).add(SV.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(SV.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(SV.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(rw.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(hV,(e=>{this.tinyId=e.signalInfo.tinyId,tw.emit(TO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),tw.emit(TO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),r&&tw.emit(TO.JOIN_SIGNAL_CONNECTION_END,{room:this}),r}))}setSignalChannel(e){this._signalChannel=e,e||NP(this)}leave(){return cb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(wk){}this._log.info("leave() => leaving room"),tw.emit(TO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(vV)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=AP.run(rN,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),AP.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return cb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let r=this._signalChannel.isConnected?function(e){if(UM.has(e)){let t=UM.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return UM.delete(e),t}return[]}(this.userId):[],n=eb({str_sdk_version:kb,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Iw()},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);tw.emit(TO.HEARTBEAT_REPORT,{room:this,report:n}),this._signalChannel.send(AV,n),this.emit("heartbeat-report",tb(eb({},n),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag: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}}));tw.emit(TO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r}=e,n=new(this.singlePC?TF:cU)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:r});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,t),this.emit("remote-published",n)}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!==Sb.ICE_TRANSPORT_ERROR&&(i===Sb.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",tb(eb({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=AP.run(rN,this.syncUserList.bind(this)))}stopSyncUserListInterval(){AP.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:UV,responseCommand:SV.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 $D({key:uN.SIGNAL_RESPONSE_FAILED,data:{signalResponse:SV.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||!eU)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)===bk.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((e=>{if(e instanceof tU&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===bk.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return cb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),rw.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 hU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}this.remotePublishedUserMap.forEach((e=>{let t=new cU({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new Ib({code:Sb.INVALID_OPERATION,message:$D({key:uN.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return cb(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:FV,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:SV.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:Sb.SWITCH_ROLE_FAILED,message:$D({key:uN.SWITCH_ROLE_FAILED,data:{message:r,code:i}})});this.role=e})).catch((e=>{throw e instanceof Ib&&e.getCode()===Sb.API_CALL_TIMEOUT&&(e=new Ib({code:Sb.SWITCH_ROLE_FAILED,message:$D({key:uN.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 cb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof uM&&(t instanceof gM?i.audio=t:e.audio=t),t instanceof hM&&(t instanceof fM&&2===t.mediaType?i.video=t:e.video=t)}));let r=CF(e),n=CF(i);(!r||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new _F({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new hU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",tb(eb({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==Sb.ICE_TRANSPORT_ERROR&&(t===Sb.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 cb(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 uM&&(t instanceof gM?i.audio=t:e.audio=t),t instanceof hM&&(t instanceof fM&&2===t.mediaType?i.video=t:e.video=t))}));try{let r=t.map((e=>e.kind)).join(",");CF(e)||(this._log.info("unpublish() => main ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),CF(i)||(this._log.info("unpublish() => aux ".concat(r)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(iL){}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&&ZO()?this.uplinkConnection.replaceTrack(e).then((t=>{tw.emit(TO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return cb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return cb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:ok.VIDEO,videoType:ok.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 cb(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=eb({},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),tw.emit(TO.SUBSCRIBE_START,{room:this,streamType:r,remotePublishedUser:i,subscribeState:n}),this._log.info("subscribe() => ".concat(e," ").concat(r," [").concat(oU(n),"] prev: [").concat(oU(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());tw.emit(TO.SUBSCRIBE_SUCCESS,{room:this,streamType:r,remotePublishedUser:i})}catch(Pb){let i=Pb instanceof Ib?Pb.getCode():Sb.UNKNOWN,n=Pb;throw Pb instanceof Ib?i===Sb.REMOTE_STREAM_NOT_EXIST&&(n=new Ib({code:Sb.API_CALL_ABORTED,message:$D({key:uN.API_CALL_ABORTED,data:{message:Pb.message,userId:e,streamType:r}})}),this._log.warn(n)):(n=new Ib({code:i,message:$D({key:uN.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 cb(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)})),tw.emit(TO.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 AP.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),tw.emit(TO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&AP.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=AP.run(nN,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit("audio-volume",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return cb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return cb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:r,framesSent:n,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return cb(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 cb(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 cb(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(Cb.getTurnServer(e)))):Cb.isPlainObject(e)&&i.push(Cb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:xV,data:e,timeout:5e3,responseCommand:SV.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:VV,data:e,timeout:5e3,responseCommand:SV.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?OV:LV,data:e,timeout:5e3,responseCommand:t?SV.START_PUBLISH_TENCENT_CDN_RES:SV.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?PV:MV,data:e,timeout:5e3,responseCommand:t?SV.STOP_PUBLISH_TENCENT_CDN_RES:SV.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:JV,data:e,timeout:5e3,responseCommand:SV.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Cb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this._signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return cb(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(tN-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=tN}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(tN-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:tN};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(vF(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!AF(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new Ib({code:Sb.INVALID_PARAMETER,message:$D({key:uN.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(!AF(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new Ib({code:Sb.INVALID_PARAMETER,message:$D({key:uN.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!AF(e.userDefinePushArgs)){if(!(vF(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new Ib({code:Sb.INVALID_PARAMETER,message:$D({key:uN.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}CF(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}sendCustomMessage(e){var t;null==(t=this._customMessageManager)||t.send(e)}};return ob([aV(["left",dV.INIT],"joined"),Ix({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),sw(!0),this.reset(),t()):this._signalChannel&&this._signalChannel.isConnected&&this._signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this._signalChannel.close(),this.reset(),t()):(this.reset(),this._log.error(e),i(e))}}),ZL((e=>{let t=new Zx;return function(i,r,n){return cb(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:Sb.INVALID_OPERATION,message:$D({key:uN.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new Ib({code:Sb.INVALID_OPERATION,message:$D({key:uN.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)),tw.emit(TO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield vO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Cb.getEnv();s||(s=Yb.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ak.OLD_CLOUD_LADDER)?s=Yb.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ak.WEBRTC)&&(s=Yb.WEBRTC))),rw.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),eV.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!vO.isWebRTCSupported()||!a&&!c)throw new Ib({code:Sb.NOT_SUPPORTED,message:$D({key:uN.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Cb.getEnv()&&(yield this.schedule(i,n));let t=yield e.call(this,i,r,n);return this.roomId=o,this._joinedTimestamp=Cb.performanceNow(),tw.emit(TO.JOIN_SUCCESS,{room:this}),rw.uploadEvent({log:"stat-conv-".concat(Number(UD),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),tw.emit(TO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],bF.prototype,"join",1),ob([aV("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ZL((e=>function(){return cb(this,null,(function*(){tw.emit(TO.LEAVE_START,{room:this}),yield e.call(this),tw.emit(TO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),sM("leave room"),vx({fnName:"publish",validateArgs:!1}),vx({fnName:"unsubscribe",validateArgs:!1})],bF.prototype,"leave",1),ob([oM(),ZL((e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return cb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;tw.emit("61",{room:this});let t=e.apply(this,i);return i.forEach((e=>e.publish(this,t))),t}))})),Ix({settings:{retries:Dk,timeout:e=>Ow(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),tw.emit(TO.PUBLISH_FAILED,{room:this}))}})],bF.prototype,"publish",1),ob([vx({fnName:"publish"}),(IF="api-call",function(e,t,i){let r=i.value;return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=rM.get(this);if(n){let e=n.queue.filter(((e,i)=>{if(0===i)return!0;let r=!0;return e.args.forEach((e=>{t.find((t=>t===e))||(r=!1)})),!r||(e.reject(new Ib({code:Sb.API_CALL_ABORTED,message:IF})),!1)}));n.queue=e}return r.apply(this,t)},i}),oM(),ZL((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})),$L((function(){var e,t;!this.uplinkConnection&&qO()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((e=>e.track&&e.replaceTrack(null))))}))],bF.prototype,"unpublish",1),ob([aM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),EM(),ZL((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})),Ix({settings:{retries:Dk,timeout:e=>Ow(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),tw.emit(TO.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],bF.prototype,"subscribe",1),ob([vx({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")}))}}),aM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],bF.prototype,"unsubscribe",1),$x.create=$x._create.bind($x,bF),$x}));
|