trtc-sdk-v5 5.3.2-beta.7 → 5.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +1696 -1696
- 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/cdn-streaming.js +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.esm.js +31 -2972
- package/plugins/video-effect/virtual-background/virtual-background.iife.js +31 -2972
- package/plugins/video-effect/watermark/package.json +30 -0
- package/plugins/video-effect/watermark/watermark.esm.d.ts +10 -0
- package/plugins/video-effect/watermark/watermark.esm.js +1 -0
- package/plugins/video-effect/watermark/watermark.iife.js +1 -0
- package/trtc.esm.js +21 -21
- package/trtc.js +1 -1
package/trtc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},n=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=n,o=Function.prototype,s=o.call,a=r&&o.bind.bind(s,s),c=r?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,_=h,m=Object,f=c("".split),g=p((function(){return!m("z").propertyIsEnumerable(0)}))?function(e){return"String"==_(e)?f(e,""):m(e)}:m,T=function(e){return null==e},E=T,S=TypeError,I=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,y=I,A=function(e){return v(y(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},N=C,D=Object.defineProperty,O=function(e,t){try{D(N,e,{value:t,configurable:!0,writable:!0})}catch(i){N[e]=t}return t},w=O,P="__core-js_shared__",M=C[P]||w(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,K=Math.random(),Y=W(1..toString),z=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Y(++J+K,36)},q="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=q,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=G,le=z,de=oe,ue=se,he=C.Symbol,pe=ae("wks"),_e=ue?he.for||he:he&&he.withoutSetter||le,me=function(e){return ce(pe,e)||(pe[e]=de&&ce(he,e)?he[e]:_e("Symbol."+e)),pe[e]},fe="object"==typeof document&&document.all,ge={all:fe,IS_HTMLDDA:void 0===fe&&void 0!==fe},Te=ge.all,Ee=ge.IS_HTMLDDA?function(e){return"function"==typeof e||e===Te}:function(e){return"function"==typeof e},Se=Ee,Ie=ge.all,ve=ge.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:Se(e)||e===Ie}:function(e){return"object"==typeof e?null!==e:Se(e)},ye=ve,Ae=String,Re=TypeError,Ce=function(e){if(ye(e))return e;throw Re(Ae(e)+" is not an object")},be={},ke=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Ne=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),De={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Me=function(e){return Pe?we.createElement(e):{}},Le=Me,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=n,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,Ye=Object,ze=se?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&Ke(t.prototype,Ye(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=ze,ut=nt,ht=function(e,t){var i,n;if("string"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if("string"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at("Can't convert object to primitive value")},pt=TypeError,_t=me("toPrimitive"),mt=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,_t);if(n){if(void 0===t&&(t="default"),i=ct(n,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=mt,gt=ze,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,St=xe,It=Ne,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Nt="writable";De.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Nt in i&&!i[Nt]){var n=Ct(e,t);n&&n[Nt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i)}catch(n){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Dt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Dt)(t)},Pt=wt,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,Kt=Gt,Yt=function(e){return function(t,i,n){var r,o=Wt(t),s=Kt(o),a=Jt(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},zt={includes:Yt(!0),indexOf:Yt(!1)},qt={},Qt=G,Xt=A,$t=zt.indexOf,Zt=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt(Zt,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri)},si=ke,ai=Ne,ci=De,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e};var hi,pi=je("document","documentElement"),_i=z,mi=b("keys"),fi=function(e){return mi[e]||(mi[e]=_i(e))},gi=Ce,Ti=be,Ei=ii,Si=qt,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(r){}var e,t,i;Ni="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Ni[yi][Ei[n]];return Ni()};Si[Ri]=!0;var Di=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Ni(),void 0===t?i:Ti.f(i,t)},Oi=me,wi=Di,Pi=De.f,Mi=Oi("unscopables"),Li=Array.prototype;null==Li[Mi]&&Pi(Li,Mi,{configurable:!0,value:wi(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,Ki=Wi,Yi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},zi=Gi,qi=C,Qi=ve,Xi=Yi,$i=G,Zi=M,en=fi,tn=qt,nn="Object already initialized",rn=qi.TypeError,on=qi.WeakMap;if(zi||Zi.state){var sn=Zi.state||(Zi.state=new on);sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,xi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t},Vi=function(e){return sn.get(e)||{}},Ui=function(e){return sn.has(e)}}else{var an=en("state");tn[an]=!0,xi=function(e,t){if($i(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t},Vi=function(e){return $i(e,an)?e[an]:{}},Ui=function(e){return $i(e,an)}}var cn={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rn("Incompatible receiver, "+e+" required");return i}}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable}:un;var _n=ke,mn=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=xe,vn=Object.getOwnPropertyDescriptor;ln.f=_n?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t)}catch(i){}if(Sn(e,t))return gn(!mn(fn.f,e,t),e[t])};var yn={},An={get exports(){return yn},set exports(e){yn=e}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Nn=Cn(bn,"name"),Dn={EXISTS:Nn,PROPER:Nn&&"something"===function(){}.name,CONFIGURABLE:Nn&&(!Rn||Rn&&kn(bn,"name").configurable)},On=Ee,wn=M,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e)});var Mn=wn.inspectSource,Ln=c,xn=i,Vn=Ee,Un=G,Fn=ke,Bn=Dn.CONFIGURABLE,Hn=Mn,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,Kn=Ln("".slice),Yn=Ln("".replace),zn=Ln([].join),qn=Fn&&!xn((function(){return 8!==Jn((function(){}),"length",{value:8}).length})),Qn=String(String).split("String"),Xn=An.exports=function(e,t,i){"Symbol("===Kn(Wn(t),0,7)&&(t="["+Yn(Wn(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Un(e,"name")||Bn&&e.name!==t)&&(Fn?Jn(e,"name",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,"arity")&&e.length!==i.arity&&Jn(e,"length",{value:i.arity});try{i&&Un(i,"constructor")&&i.constructor?Fn&&Jn(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(r){}var n=jn(e);return Un(n,"source")||(n.source=zn(Qn,"string"==typeof t?t:"")),e};Function.prototype.toString=Xn((function(){return Vn(this)&&Gn(this).source||Hn(this)}),"toString");var $n=Ee,Zn=De,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if($n(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t]}catch(s){}r?e[t]=i:Zn.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},nr={},rr=ti,or=ii.concat("length","prototype");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or)};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,_r=c([].concat),mr=dr("Reflect","ownKeys")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?_r(t,i(e)):t},fr=G,gr=mr,Tr=ln,Er=De,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s<n.length;s++){var a=n[s];fr(e,a)||i&&fr(i,a)||r(e,a,o(t,a))}},Ir=i,vr=Ee,yr=/#|\.prototype\./,Ar=function(e,t){var i=Cr[Rr(e)];return i==kr||i!=br&&(vr(t)?Ir(t):!!t)},Rr=Ar.normalize=function(e){return String(e).replace(yr,".").toLowerCase()},Cr=Ar.data={},br=Ar.NATIVE="N",kr=Ar.POLYFILL="P",Nr=Ar,Dr=C,Or=ln.f,wr=Yi,Pr=ir,Mr=O,Lr=Sr,xr=Nr,Vr=function(e,t){var i,n,r,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Dr:l?Dr[a]||Mr(a,{}):(Dr[a]||{}).prototype)for(n in t){if(o=t[n],r=e.dontCallGetSet?(s=Or(i,n))&&s.value:i[n],!xr(c?n:a+(l?".":"#")+n,e.forced)&&void 0!==r){if(typeof o==typeof r)continue;Lr(o,r)}(e.sham||r&&r.sham)&&wr(o,"sham",!0),Pr(i,n,o,e)}},Ur=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fr=G,Br=Ee,Hr=B,jr=Ur,Gr=fi("IE_PROTO"),Wr=Object,Jr=Wr.prototype,Kr=jr?Wr.getPrototypeOf:function(e){var t=Hr(e);if(Fr(t,Gr))return t[Gr];var i=t.constructor;return Br(i)&&t instanceof i?i.prototype:t instanceof Wr?Jr:null},Yr=i,zr=Ee,qr=ve,Qr=Kr,Xr=ir,$r=me("iterator"),Zr=!1;[].keys&&("next"in(lr=[].keys())?(cr=Qr(Qr(lr)))!==Object.prototype&&(ar=cr):Zr=!0);var eo=!qr(ar)||Yr((function(){var e={};return ar[$r].call(e)!==e}));eo&&(ar={}),zr(ar[$r])||Xr(ar,$r,(function(){return this}));var to={IteratorPrototype:ar,BUGGY_SAFARI_ITERATORS:Zr},io=De.f,no=G,ro=me("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!no(e,ro)&&io(e,ro,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Di,co=Wi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ao(so,{next:co(+!n,i)}),lo(e,r,!1),uo[r]=ho,e},_o=c,mo=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return _o(mo(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(n){}},So=Ce,Io=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(n){}return function(i,n){return So(i),Io(n),t?e(i,n):i.__proto__=n,i}}():void 0),yo=Vr,Ao=Fe,Ro=Ee,Co=po,bo=Kr,ko=vo,No=oo,Do=Yi,Oo=ir,wo=Bi,Po=Dn.PROPER,Mo=Dn.CONFIGURABLE,Lo=to.IteratorPrototype,xo=to.BUGGY_SAFARI_ITERATORS,Vo=me("iterator"),Uo="keys",Fo="values",Bo="entries",Ho=function(){return this},jo=function(e,t,i,n,r,o,s){Co(i,t,n);var a,c,l,d=function(e){if(e===r&&m)return m;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,_=p[Vo]||p["@@iterator"]||r&&p[r],m=!xo&&_||d(r),f="Array"==t&&p.entries||_;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Lo&&(ko?ko(a,Lo):Ro(a[Vo])||Oo(a,Vo,Ho)),No(a,u,!0)),Po&&r==Fo&&_&&_.name!==Fo&&(Mo?Do(p,"name",Fo):(h=!0,m=function(){return Ao(_,this)})),r)if(c={values:d(Fo),keys:o?m:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&Oo(p,l,c[l]);else yo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==m&&Oo(p,Vo,m,{name:r}),wo[t]=m,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,Ko=Bi,Yo=cn,zo=De.f,qo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=Yo.set,es=Yo.getterFor($o),ts=qo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),is=Ko.Arguments=Ko.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{zo(is,"name",{value:"values"})}catch(NU){}var ns={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},rs=Me("span").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=Yi,hs=me,ps=hs("iterator"),_s=hs("toStringTag"),ms=ds.values,fs=function(e,t){if(e){if(e[ps]!==ms)try{us(e,ps,ms)}catch(NU){e[ps]=ms}if(e[_s]||us(e,_s,t),cs[t])for(var i in ds)if(e[i]!==ds[i])try{us(e,i,ds[i])}catch(NU){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=yn,Ss=De,Is=function(e,t,i){return i.get&&Es(i.get,t,{getter:!0}),i.set&&Es(i.set,t,{setter:!0}),Ss.f(e,t,i)},vs=je,ys=Is,As=ke,Rs=me("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[me("toStringTag")]="z";var Os="[object z]"===String(Ds),ws=Ee,Ps=h,Ms=me("toStringTag"),Ls=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=Os?Ps:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(NU){}}(t=Ls(e),Ms))?i:xs?Ps(t):"Object"==(n=Ps(t))&&ws(t.callee)?"Arguments":n},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Mn,Gs=function(){},Ws=[],Js=je("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,Ys=Us(Ks.exec),zs=!Ks.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(NU){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zs||!!Ys(Ks,js(e))}catch(NU){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return qs(qs.call)||!qs(Object)||!qs((function(){e=!0}))||e}))?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=me("species"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i)},ua=n,ha=Function.prototype,pa=ha.apply,_a=ha.call,ma="object"==typeof Reflect&&Reflect.apply||(ua?_a.bind(pa):function(){return _a.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(q),ba=C,ka=ma,Na=va,Da=Ee,Oa=G,wa=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,Ka=0,Ya={},za="onreadystatechange";wa((function(){Xs=ba.location}));var qa=function(e){if(Oa(Ya,e)){var t=Ya[e];delete Ya[e],t()}},Qa=function(e){return function(){qa(e)}},Xa=function(e){qa(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Da(e)?e:Ga(e),i=Ma(arguments,1);return Ya[++Ka]=function(){ka(t,void 0,i)},$s(Ka),Ka},Ba=function(e){delete Ya[e]},Ua?$s=function(e){Ha.nextTick(Qa(e))}:ja&&ja.now?$s=function(e){ja.now(Qa(e))}:Wa&&!Va?(ea=(Zs=new Wa).port2,Zs.port1.onmessage=Xa,$s=Na(ea.postMessage,ea)):ba.addEventListener&&Da(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!wa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=za in La("script")?function(e){Pa.appendChild(La("script"))[za]=function(){Pa.removeChild(this),qa(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,nc,rc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(q)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(q),lc=C,dc=va,uc=ln.f,hc=Za.set,pc=sc,_c=Ca,mc=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(NU){throw Ac.head&&tc(),NU}e&&e.enter()};_c||gc||fc||!Tc||!Ec?!mc&&Ic&&Ic.resolve?((rc=Ic.resolve(void 0)).constructor=Ic,oc=dc(rc.then,rc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,nc=Ec.createTextNode(""),new Tc(Rc).observe(nc,{characterData:!0}),tc=function(){nc.data=ic=!ic}),yc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=yc,bc=function(e){try{return{error:!1,value:e()}}catch(NU){return{error:!0,value:NU}}},kc=C.Promise,Nc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Dc=!Nc&&!Ts&&"object"==typeof window&&"object"==typeof document,Oc=C,wc=kc,Pc=Ee,Mc=Nr,Lc=Mn,xc=me,Vc=Dc,Uc=Nc,Fc=ie;wc&&wc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(Oc.PromiseRejectionEvent),Gc=Mc("Promise",(function(){var e=Lc(wc),t=e!==String(wc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new wc((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=n,!(Hc=i.then((function(){}))instanceof n))return!0}return!t&&(Vc||Uc)&&!jc})),Wc={CONSTRUCTOR:Gc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},Kc=et,Yc=TypeError,zc=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw Yc("Bad Promise constructor");t=e,i=n})),this.resolve=Kc(t),this.reject=Kc(i)};Jc.f=function(e){return new zc(e)};var qc,Qc,Xc,$c=Vr,Zc=Ts,el=C,tl=Fe,il=ir,nl=vo,rl=oo,ol=Cs,sl=et,al=Ee,cl=ve,ll=Ns,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(NU){}},_l=bc,ml=sc,fl=cn,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,Il=Wc.REJECTION_EVENT,vl=Wc.SUBCLASSING,yl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Nl=el.document,Dl=el.process,Ol=Tl.f,wl=Ol,Pl=!!(Nl&&Nl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),r=!0)),i===e.promise?l(kl("Promise-chain cycle")):(n=Ll(i))?tl(n,i,c,l):c(i)):l(o)}catch(NU){d&&!r&&d.exit(),l(NU)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,n=e.reactions;i=n.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var n,r;Pl?((n=Nl.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),el.dispatchEvent(n)):n={promise:t,reason:i},!Il&&(r=el["on"+e])?r(n):e===Ml&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,n=e.value;if(Bl(e)&&(t=_l((function(){Zc?Dl.emit("unhandledRejection",n,i):Ul(Ml,i,n)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Dl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(n){e(t,n,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var n=Ll(t);n?hl((function(){var i={done:!1};try{tl(n,t,jl(Wl,i,e),jl(Gl,i,e))}catch(NU){Gl(i,NU,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(NU){Gl({done:!1},NU,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(qc,this);var t=yl(this);try{e(jl(Wl,t),jl(Gl,t))}catch(NU){Gl(t,NU)}}).prototype,(qc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new ml,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=yl(this),n=Ol(dl(this,Cl));return i.parent=!0,n.ok=!al(e)||e,n.fail=al(t)&&t,n.domain=Zc?Dl.domain:void 0,0==i.state?i.reactions.add(n):hl((function(){xl(n,i)})),n.promise})),Qc=function(){var e=new qc,t=yl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=Ol=function(e){return e===Cl||undefined===e?new Qc(e):wl(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,vl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(NU){}nl&&nl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),rl(Cl,El,!1),ol(El);var Jl=Bi,Kl=me("iterator"),Yl=Array.prototype,zl=function(e){return void 0!==e&&(Jl.Array===e||Yl[Kl]===e)},ql=Vs,Ql=nt,Xl=T,$l=Bi,Zl=me("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[ql(e)]},td=Fe,id=et,nd=Ce,rd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return nd(td(i,e));throw sd(rd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=nt,ud=function(e,t,i){var n,r;ld(e);try{if(!(n=dd(e,"return"))){if("throw"===t)throw i;return i}n=cd(n,e)}catch(NU){r=!0,n=NU}if("throw"===t)throw i;if(r)throw n;return ld(n),i},hd=va,pd=Fe,_d=Ce,md=Qe,fd=zl,gd=Gt,Td=Ge,Ed=ad,Sd=ed,Id=ud,vd=TypeError,yd=function(e,t){this.stopped=e,this.result=t},Ad=yd.prototype,Rd=function(e,t,i){var n,r,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),m=hd(t,d),f=function(e){return n&&Id(n,"normal",e),new yd(!0,e)},g=function(e){return u?(_d(e),_?m(e[0],e[1],f):m(e[0],e[1])):_?m(e,f):m(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=Sd(e)))throw vd(md(e)+" is not iterable");if(fd(r)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1)}n=Ed(e,r)}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value)}catch(NU){Id(n,"throw",NU)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=me("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(NU){}var Dd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(NU){}return i},Od=kc,wd=Wc.CONSTRUCTOR||!Dd((function(e){Od.all(e).then(void 0,(function(){}))})),Pd=Fe,Md=et,Ld=Jc,xd=bc,Vd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Ld.f(t),n=i.resolve,r=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||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ud=Vr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var Kd=Fe,Yd=et,zd=Jc,qd=bc,Qd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{race:function(e){var t=this,i=zd.f(t),n=i.reject,r=qd((function(){var r=Yd(t.resolve);Qd(e,(function(e){Kd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Xd=Fe,$d=Jc;Vr({target:"Promise",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},nu=Vr,ru=Wc.CONSTRUCTOR,ou=iu;je("Promise"),nu({target:"Promise",stat:!0,forced:ru},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e},du=ve,uu=h,hu=me("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},_u=Vs,mu=String,fu=function(e){if("Symbol"===_u(e))throw TypeError("Cannot convert a Symbol value to a string");return mu(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in yu||Su(e,"flags")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Nu=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Du={BROKEN_CARET:Nu,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=De.f,wu=i,Pu=C.RegExp,Mu=wu((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=Nr,ju=lu,Gu=Yi,Wu=nr.f,Ju=Ge,Ku=pu,Yu=fu,zu=Au,qu=Du,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=ir,$u=i,Zu=G,eh=cn.enforce,th=Cs,ih=Mu,nh=Vu,rh=me("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!#%&*+<=>@^]*>/,_h=/a/g,mh=/a/g,fh=new oh(_h)!==_h,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||$u((function(){return mh[rh]=!1,oh(_h)!=_h||oh(mh)==mh||"/a/i"!=oh(_h,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?"":Yu(e),t=void 0===t?"":Yu(t),h=e,ih&&"dotAll"in _h&&(n=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in _h&&(r=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),nh&&(o=function(e){for(var t,i=e.length,n=0,r="",o=[],s={},a=!1,c=!1,l=0,d="";n<=i;n++){if("\\"===(t=lh(e,n)))t+=lh(e,++n);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:r+=t}return[r,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r="",o=!1;n<=i;n++)"\\"!==(t=lh(e,n))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),r+=t):r+="[\\s\\S]":r+=t+lh(e,++n);return r}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch(NU){}return s},Ih=Wu(oh),vh=0;Ih.length>vh;)Qu(Sh,oh,Ih[vh++]);sh.constructor=Sh,Sh.prototype=sh,Xu(Fu,"RegExp",Sh,{constructor:!0})}th("RegExp");var yh=Fe,Ah=c,Rh=fu,Ch=Tu,bh=Du,kh=Di,Nh=cn.get,Dh=Mu,Oh=Vu,wh=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||Oh)&&(Mh=function(e){var t,i,n,r,o,s,a,c=this,l=Nh(c),d=Rh(e),u=l.raw;if(u)return u.lastIndex=c.lastIndex,t=yh(Mh,u,d),c.lastIndex=u.lastIndex,t;var h=l.groups,p=Bh&&c.sticky,_=yh(Ch,c),m=c.source,f=0,g=d;if(p&&(_=Vh(_,"y",""),-1===xh(_,"g")&&(_+="g"),g=Uh(d,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Lh(d,c.lastIndex-1))&&(m="(?: "+m+")",g=" "+g,f++),i=new RegExp("^(?:"+m+")",_)),Hh&&(i=new RegExp("^"+m+"$(?!\\s)",_)),Fh&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(r[o]=void 0)})),r&&h)for(r.groups=s=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=r[a[1]];return r});var jh=Mh;Vr({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,Kh=ta,Yh=ve,zh=me("species"),qh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(Kh(t)&&(t===qh||Jh(t.prototype))||Yh(t)&&null===(t=t[zh]))&&(t=void 0)),void 0===t?qh:t},Xh=va,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),np=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,_=Zh(c),m=$h(_),f=Xh(l,d),g=ep(m),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in m)&&(p=f(h=m[T],T,_),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:n||r?r:S}},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=rp.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=ns,up=ss,hp=cp,pp=Yi,_p=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch(NU){e.forEach=hp}};for(var mp in dp)dp[mp]&&_p(lp[mp]&&lp[mp].prototype);_p(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Sp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r}},vp={left:Ip(!1),right:Ip(!0)}.left;Vr({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=me,kp=Yi,Np=bp("species"),Dp=RegExp.prototype,Op=c,wp=Mt,Pp=fu,Mp=I,Lp=Op("".charAt),xp=Op("".charCodeAt),Vp=Op("".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Mp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=xp(o,s))<55296||n>56319||s+1===a||(r=xp(o,s+1))<56320||r>57343?e?Lp(o,s):n:e?Vp(o,s,s+2):r-56320+(n-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),Kp=Hp("".slice),Yp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=zp;return void 0!==r&&(r=jp(r),c=Yp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return Kp(t,0,i);case"'":return Kp(t,s);case"<":l=r[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o}l=n[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,e_=jh,t_=TypeError,i_=ma,n_=Fe,r_=c,o_=function(e,t,i,n){var r=bp(e),o=!Cp((function(){var t={};return t[r]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Np]=function(){return i},i.flags="",i[r]=/./[r]),i.exec=function(){return t=!0,null},i[r](""),!t}));if(!o||!s||i){var a=yp(/./[r]),c=t(r,""[e],(function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Dp.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Dp,r,c[1])}n&&kp(Dp[r],"sham",!0)},s_=i,a_=Ce,c_=Ee,l_=T,d_=Mt,u_=Ht,h_=fu,p_=I,__=function(e,t,i){return t+(i?Bp(e,t).length:1)},m_=nt,f_=qp,g_=function(e,t){var i=e.exec;if($p(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n}if("RegExp"===Zp(e))return Qp(e_,e,t);throw t_("RegExp#exec called on incompatible receiver")},T_=me("replace"),E_=Math.max,S_=Math.min,I_=r_([].concat),v_=r_([].push),y_=r_("".indexOf),A_=r_("".slice),R_="$0"==="a".replace(/./,"$0"),C_=!!/./[T_]&&""===/./[T_]("a","$0"),b_=!s_((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));o_("replace",(function(e,t,i){var n=C_?"$":"$0";return[function(e,i){var n=p_(this),r=l_(e)?void 0:m_(e,T_);return r?n_(r,e,n,i):n_(t,h_(n),e,i)},function(e,r){var o=a_(this),s=h_(e);if("string"==typeof r&&-1===y_(r,n)&&-1===y_(r,"$<")){var a=i(t,o,s,r);if(a.done)return a.value}var c=c_(r);c||(r=h_(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=g_(o,s);if(null===h)break;if(v_(u,h),!l)break;""===h_(h[0])&&(o.lastIndex=__(s,u_(o.lastIndex),d))}for(var p,_="",m=0,f=0;f<u.length;f++){for(var g=h_((h=u[f])[0]),T=E_(S_(d_(h.index),s.length),0),E=[],S=1;S<h.length;S++)v_(E,void 0===(p=h[S])?p:String(p));var I=h.groups;if(c){var v=I_([g],E,T,s);void 0!==I&&v_(v,I);var y=h_(i_(r,void 0,v))}else y=f_(g,s,T,E,I,r);T>=m&&(_+=A_(s,m,T)+y,m=T+g.length)}return _+A_(s,m)}]}),!b_||!R_||C_);var k_=zt.includes,N_=Fi;Vr({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return k_(this,e,arguments.length>1?arguments[1]:void 0)}}),N_("includes");var D_=Mt,O_=fu,w_=I,P_=RangeError,M_=c,L_=Ht,x_=fu,V_=function(e){var t=O_(w_(this)),i="",n=D_(e);if(n<0||Infinity==n)throw P_("Wrong number of repetitions");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i},U_=I,F_=M_(V_),B_=M_("".slice),H_=Math.ceil,j_=function(e){return function(t,i,n){var r,o,s=x_(U_(t)),a=L_(i),c=s.length,l=void 0===n?" ":x_(n);return a<=c||""==l?s:((o=F_(l,H_((r=a-c)/l.length))).length>r&&(o=B_(o,0,r)),e?s+o:o+s)}},G_={start:j_(!1),end:j_(!0)},W_=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),J_=G_.start;Vr({target:"String",proto:!0,forced:W_},{padStart:function(e){return J_(this,e,arguments.length>1?arguments[1]:void 0)}});var K_=i,Y_=ke,z_=me("iterator"),q_=!K_((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),!t.size&&!Y_||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[z_]||"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})),Q_=ir,X_=function(e,t,i){for(var n in t)Q_(e,n,t[n],i);return e},$_=Tt,Z_=De,em=Wi,tm=function(e,t,i){var n=$_(t);n in e?Z_.f(e,n,em(0,i)):e[n]=i},im=Ut,nm=Gt,rm=tm,om=Array,sm=Math.max,am=function(e,t,i){for(var n=nm(e),r=im(t,n),o=im(void 0===i?n:i,n),s=om(sm(o-r,0)),a=0;r<o;r++,a++)rm(s,a,e[r]);return s.length=a,s},cm=am,lm=Math.floor,dm=function(e,t){var i=e.length,n=lm(i/2);return i<8?um(e,t):hm(e,dm(cm(e,0,n),t),dm(cm(e,n),t),t)},um=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},hm=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},pm=dm,_m=Vr,mm=C,fm=Fe,gm=c,Tm=ke,Em=q_,Sm=ir,Im=Is,vm=X_,ym=oo,Am=po,Rm=cn,Cm=Ns,bm=Ee,km=G,Nm=va,Dm=Vs,Om=Ce,wm=ve,Pm=fu,Mm=Di,Lm=Wi,xm=ad,Vm=ed,Um=Ra,Fm=pm,Bm=me("iterator"),Hm="URLSearchParams",jm=Hm+"Iterator",Gm=Rm.set,Wm=Rm.getterFor(Hm),Jm=Rm.getterFor(jm),Km=Object.getOwnPropertyDescriptor,Ym=function(e){if(!Tm)return mm[e];var t=Km(mm,e);return t&&t.value},zm=Ym("fetch"),qm=Ym("Request"),Qm=Ym("Headers"),Xm=qm&&qm.prototype,$m=Qm&&Qm.prototype,Zm=mm.RegExp,ef=mm.TypeError,tf=mm.decodeURIComponent,nf=mm.encodeURIComponent,rf=gm("".charAt),of=gm([].join),sf=gm([].push),af=gm("".replace),cf=gm([].shift),lf=gm([].splice),df=gm("".split),uf=gm("".slice),hf=/\+/g,pf=Array(4),_f=function(e){return pf[e-1]||(pf[e-1]=Zm("((?:%[\\da-f]{2}){"+e+"})","gi"))},mf=function(e){try{return tf(e)}catch(NU){return e}},ff=function(e){var t=af(e,hf," "),i=4;try{return tf(t)}catch(NU){for(;i;)t=af(t,_f(i--),mf);return t}},gf=/[!'()~]|%20/g,Tf={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Ef=function(e){return Tf[e]},Sf=function(e){return af(nf(e),gf,Ef)},If=Am((function(e,t){Gm(this,{type:jm,iterator:xm(Wm(e).entries),kind:t})}),"Iterator",(function(){var e=Jm(this),t=e.kind,i=e.iterator.next(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.value]),i}),!0),vf=function(e){this.entries=[],this.url=null,void 0!==e&&(wm(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rf(e,0)?uf(e,1):e:Pm(e)))};vf.prototype={type:Hm,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,n,r,o,s,a,c=Vm(e);if(c)for(i=(t=xm(e,c)).next;!(n=fm(i,t)).done;){if(o=(r=xm(Om(n.value))).next,(s=fm(o,r)).done||(a=fm(o,r)).done||!fm(o,r).done)throw ef("Expected sequence with length 2");sf(this.entries,{key:Pm(s.value),value:Pm(a.value)})}else for(var l in e)km(e,l)&&sf(this.entries,{key:l,value:Pm(e[l])})},parseQuery:function(e){if(e)for(var t,i,n=df(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=df(t,"="),sf(this.entries,{key:ff(cf(i)),value:ff(of(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],sf(i,Sf(e.key)+"="+Sf(e.value));return of(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var yf=function(){Cm(this,Af);var e=Gm(this,new vf(arguments.length>0?arguments[0]:void 0));Tm||(this.length=e.entries.length)},Af=yf.prototype;if(vm(Af,{append:function(e,t){Um(arguments.length,2);var i=Wm(this);sf(i.entries,{key:Pm(e),value:Pm(t)}),Tm||this.length++,i.updateURL()},delete:function(e){Um(arguments.length,1);for(var t=Wm(this),i=t.entries,n=Pm(e),r=0;r<i.length;)i[r].key===n?lf(i,r,1):r++;Tm||(this.length=i.length),t.updateURL()},get:function(e){Um(arguments.length,1);for(var t=Wm(this).entries,i=Pm(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){Um(arguments.length,1);for(var t=Wm(this).entries,i=Pm(e),n=[],r=0;r<t.length;r++)t[r].key===i&&sf(n,t[r].value);return n},has:function(e){Um(arguments.length,1);for(var t=Wm(this).entries,i=Pm(e),n=0;n<t.length;)if(t[n++].key===i)return!0;return!1},set:function(e,t){Um(arguments.length,1);for(var i,n=Wm(this),r=n.entries,o=!1,s=Pm(e),a=Pm(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?lf(r,c--,1):(o=!0,i.value=a));o||sf(r,{key:s,value:a}),Tm||(this.length=r.length),n.updateURL()},sort:function(){var e=Wm(this);Fm(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,i=Wm(this).entries,n=Nm(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new If(this,"keys")},values:function(){return new If(this,"values")},entries:function(){return new If(this,"entries")}},{enumerable:!0}),Sm(Af,Bm,Af.entries,{name:"entries"}),Sm(Af,"toString",(function(){return Wm(this).serialize()}),{enumerable:!0}),Tm&&Im(Af,"size",{get:function(){return Wm(this).entries.length},configurable:!0,enumerable:!0}),ym(yf,Hm),_m({global:!0,constructor:!0,forced:!Em},{URLSearchParams:yf}),!Em&&bm(Qm)){var Rf=gm($m.has),Cf=gm($m.set),bf=function(e){if(wm(e)){var t,i=e.body;if(Dm(i)===Hm)return t=e.headers?new Qm(e.headers):new Qm,Rf(t,"content-type")||Cf(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Mm(e,{body:Lm(0,Pm(i)),headers:Lm(0,t)})}return e};if(bm(zm)&&_m({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return zm(e,arguments.length>1?bf(arguments[1]):{})}}),bm(qm)){var kf=function(e){return Cm(this,Xm),new qm(e,arguments.length>1?bf(arguments[1]):{})};Xm.constructor=kf,kf.prototype=Xm,_m({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:kf})}}var Nf={URLSearchParams:yf,getState:Wm},Df="\t\n\v\f\r \u2028\u2029\ufeff",Of=I,wf=fu,Pf=Df,Mf=c("".replace),Lf=RegExp("^["+Pf+"]+"),xf=RegExp("(^|[^"+Pf+"])["+Pf+"]+$"),Vf=function(e){return function(t){var i=wf(Of(t));return 1&e&&(i=Mf(i,Lf,"")),2&e&&(i=Mf(i,xf,"$1")),i}},Uf={start:Vf(1),end:Vf(2),trim:Vf(3)},Ff=Dn.PROPER,Bf=i,Hf=Df,jf=Uf.trim;Vr({target:"String",proto:!0,forced:function(e){return Bf((function(){return!!Hf[e]()||"
"!=="
"[e]()||Ff&&Hf[e].name!==e}))}("trim")},{trim:function(){return jf(this)}});var Gf=Vr,Wf=ke,Jf=c,Kf=G,Yf=Ee,zf=Ge,qf=fu,Qf=Is,Xf=Sr,$f=C.Symbol,Zf=$f&&$f.prototype;if(Wf&&Yf($f)&&(!("description"in Zf)||void 0!==$f().description)){var eg={},tg=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:qf(arguments[0]),t=zf(Zf,this)?new $f(e):void 0===e?$f():$f(e);return""===e&&(eg[t]=!0),t};Xf(tg,$f),tg.prototype=Zf,Zf.constructor=tg;var ig="Symbol(test)"==String($f("test")),ng=Jf(Zf.valueOf),rg=Jf(Zf.toString),og=/^Symbol\((.*)\)[^)]+$/,sg=Jf("".replace),ag=Jf("".slice);Qf(Zf,"description",{configurable:!0,get:function(){var e=ng(this);if(Kf(eg,e))return"";var t=rg(e),i=ig?ag(t,7,-1):sg(t,og,"$1");return""===i?void 0:i}}),Gf({global:!0,constructor:!0,forced:!0},{Symbol:tg})}var cg=Fp.charAt,lg=fu,dg=cn,ug=jo,hg=Go,pg="String Iterator",_g=dg.set,mg=dg.getterFor(pg);ug(String,"String",(function(e){_g(this,{type:pg,string:lg(e),index:0})}),(function(){var e,t=mg(this),i=t.string,n=t.index;return n>=i.length?hg(void 0,!0):(e=cg(i,n),t.index+=e.length,hg(e,!1))}));var fg,gg=ke,Tg=c,Eg=Fe,Sg=i,Ig=oi,vg=sr,yg=dn,Ag=B,Rg=g,Cg=Object.assign,bg=Object.defineProperty,kg=Tg([].concat),Ng=!Cg||Sg((function(){if(gg&&1!==Cg({b:1},Cg(bg({},"a",{enumerable:!0,get:function(){bg(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach((function(e){t[e]=e})),7!=Cg({},e)[i]||Ig(Cg({},t)).join("")!=n}))?function(e,t){for(var i=Ag(e),n=arguments.length,r=1,o=vg.f,s=yg.f;n>r;)for(var a,c=Rg(arguments[r++]),l=o?kg(Ig(c),o(c)):Ig(c),d=l.length,u=0;d>u;)a=l[u++],gg&&!Eg(s,c,a)||(i[a]=c[a]);return i}:Cg,Dg=Ce,Og=ud,wg=va,Pg=Fe,Mg=B,Lg=function(e,t,i,n){try{return n?t(Dg(i)[0],i[1]):t(i)}catch(NU){Og(e,"throw",NU)}},xg=zl,Vg=ta,Ug=Gt,Fg=tm,Bg=ad,Hg=ed,jg=Array,Gg=c,Wg=2147483647,Jg=/[^\0-\u007E]/,Kg=/[.\u3002\uFF0E\uFF61]/g,Yg="Overflow: input needs wider integers to process",zg=RangeError,qg=Gg(Kg.exec),Qg=Math.floor,Xg=String.fromCharCode,$g=Gg("".charCodeAt),Zg=Gg([].join),eT=Gg([].push),tT=Gg("".replace),iT=Gg("".split),nT=Gg("".toLowerCase),rT=function(e){return e+22+75*(e<26)},oT=function(e,t,i){var n=0;for(e=i?Qg(e/700):e>>1,e+=Qg(e/t);e>455;)e=Qg(e/35),n+=36;return Qg(n+36*e/(e+38))},sT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=$g(e,i++);if(r>=55296&&r<=56319&&i<n){var o=$g(e,i++);56320==(64512&o)?eT(t,((1023&r)<<10)+(1023&o)+65536):(eT(t,r),i--)}else eT(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&eT(t,Xg(n));var c=t.length,l=c;for(c&&eT(t,"-");l<r;){var d=Wg;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<d&&(d=n);var u=l+1;if(d-o>Qg((Wg-s)/u))throw zg(Yg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((n=e[i])<o&&++s>Wg)throw zg(Yg);if(n==o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var m=h-_,f=36-_;eT(t,Xg(rT(_+m%f))),h=Qg(m/f),p+=36}eT(t,Xg(rT(h))),a=oT(s,u,l==c),s=0,l++}}s++,o++}return Zg(t,"")},aT=Vr,cT=ke,lT=q_,dT=C,uT=va,hT=c,pT=ir,_T=Is,mT=Ns,fT=G,gT=Ng,TT=function(e){var t=Mg(e),i=Vg(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=wg(r,n>2?arguments[2]:void 0));var s,a,c,l,d,u,h=Hg(t),p=0;if(!h||this===jg&&xg(h))for(s=Ug(t),a=i?new this(s):jg(s);s>p;p++)u=o?r(t[p],p):t[p],Fg(a,p,u);else for(d=(l=Bg(t,h)).next,a=i?new this:[];!(c=Pg(d,l)).done;p++)u=o?Lg(l,r,[c.value,p],!0):c.value,Fg(a,p,u);return a.length=p,a},ET=am,ST=Fp.codeAt,IT=function(e){var t,i,n=[],r=iT(tT(nT(e),Kg,"."),".");for(t=0;t<r.length;t++)i=r[t],eT(n,qg(Jg,i)?"xn--"+sT(i):i);return Zg(n,".")},vT=fu,yT=oo,AT=Ra,RT=Nf,CT=cn,bT=CT.set,kT=CT.getterFor("URL"),NT=RT.URLSearchParams,DT=RT.getState,OT=dT.URL,wT=dT.TypeError,PT=dT.parseInt,MT=Math.floor,LT=Math.pow,xT=hT("".charAt),VT=hT(/./.exec),UT=hT([].join),FT=hT(1..toString),BT=hT([].pop),HT=hT([].push),jT=hT("".replace),GT=hT([].shift),WT=hT("".split),JT=hT("".slice),KT=hT("".toLowerCase),YT=hT([].unshift),zT="Invalid scheme",qT="Invalid host",QT="Invalid port",XT=/[a-z]/i,$T=/[\d+-.a-z]/i,ZT=/\d/,eE=/^0x/i,tE=/^[0-7]+$/,iE=/^\d+$/,nE=/^[\da-f]+$/i,rE=/[\0\t\n\r #%/:<>?@[\\\]^|]/,oE=/[\0\t\n\r #/:<>?@[\\\]^|]/,sE=/^[\u0000-\u0020]+/,aE=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,cE=/[\t\n\r]/g,lE=function(e){var t,i,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)YT(t,e%256),e=MT(e/256);return UT(t,".")}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=FT(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},dE={},uE=gT({},dE,{" ":1,'"':1,"<":1,">":1,"`":1}),hE=gT({},uE,{"#":1,"?":1,"{":1,"}":1}),pE=gT({},hE,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),_E=function(e,t){var i=ST(e,0);return i>32&&i<127&&!fT(t,e)?e:encodeURIComponent(e)},mE={ftp:21,file:null,http:80,https:443,ws:80,wss:443},fE=function(e,t){var i;return 2==e.length&&VT(XT,xT(e,0))&&(":"==(i=xT(e,1))||!t&&"|"==i)},gE=function(e){var t;return e.length>1&&fE(JT(e,0,2))&&(2==e.length||"/"===(t=xT(e,2))||"\\"===t||"?"===t||"#"===t)},TE=function(e){return"."===e||"%2e"===KT(e)},EE={},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},NE={},DE={},OE={},wE={},PE={},ME={},LE={},xE={},VE={},UE={},FE={},BE=function(e,t,i){var n,r,o,s=vT(e);if(t){if(r=this.parse(s))throw wT(r);this.searchParams=null}else{if(void 0!==i&&(n=new BE(i,!0)),r=this.parse(s,null,n))throw wT(r);(o=DT(new NT)).bindURL(this),this.searchParams=o}};BE.prototype={type:"URL",parse:function(e,t,i){var n,r,o,s,a,c=this,l=t||EE,d=0,u="",h=!1,p=!1,_=!1;for(e=vT(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=jT(e,sE,""),e=jT(e,aE,"$1")),e=jT(e,cE,""),n=TT(e);d<=n.length;){switch(r=n[d],l){case EE:if(!r||!VT(XT,r)){if(t)return zT;l=IE;continue}u+=KT(r),l=SE;break;case SE:if(r&&(VT($T,r)||"+"==r||"-"==r||"."==r))u+=KT(r);else{if(":"!=r){if(t)return zT;u="",l=IE,d=0;continue}if(t&&(c.isSpecial()!=fT(mE,u)||"file"==u&&(c.includesCredentials()||null!==c.port)||"file"==c.scheme&&!c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&mE[c.scheme]==c.port&&(c.port=null));u="","file"==c.scheme?l=wE:c.isSpecial()&&i&&i.scheme==c.scheme?l=vE:c.isSpecial()?l=CE:"/"==n[d+1]?(l=yE,d++):(c.cannotBeABaseURL=!0,HT(c.path,""),l=VE)}break;case IE:if(!i||i.cannotBeABaseURL&&"#"!=r)return zT;if(i.cannotBeABaseURL&&"#"==r){c.scheme=i.scheme,c.path=ET(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,l=FE;break}l="file"==i.scheme?wE:AE;continue;case vE:if("/"!=r||"/"!=n[d+1]){l=AE;continue}l=bE,d++;break;case yE:if("/"==r){l=kE;break}l=xE;continue;case AE:if(c.scheme=i.scheme,r==fg)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query;else if("/"==r||"\\"==r&&c.isSpecial())l=RE;else if("?"==r)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.path.length--,l=xE;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}break;case RE:if(!c.isSpecial()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=xE;continue}l=kE}else l=bE;break;case CE:if(l=bE,"/"!=r||"/"!=xT(u,d+1))continue;d++;break;case bE:if("/"!=r&&"\\"!=r){l=kE;continue}break;case kE:if("@"==r){h&&(u="%40"+u),h=!0,o=TT(u);for(var m=0;m<o.length;m++){var f=o[m];if(":"!=f||_){var g=_E(f,pE);_?c.password+=g:c.username+=g}else _=!0}u=""}else if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=TT(u).length+1,u="",l=NE}else u+=r;break;case NE:case DE:if(t&&"file"==c.scheme){l=ME;continue}if(":"!=r||p){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return qT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=LE,t)return;continue}"["==r?p=!0:"]"==r&&(p=!1),u+=r}else{if(""==u)return qT;if(s=c.parseHost(u))return s;if(u="",l=OE,t==DE)return}break;case OE:if(!VT(ZT,r)){if(r==fg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()||t){if(""!=u){var T=PT(u,10);if(T>65535)return QT;c.port=c.isSpecial()&&T===mE[c.scheme]?null:T,u=""}if(t)return;l=LE;continue}return QT}u+=r;break;case wE:if(c.scheme="file","/"==r||"\\"==r)l=PE;else{if(!i||"file"!=i.scheme){l=xE;continue}if(r==fg)c.host=i.host,c.path=ET(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=ET(i.path),c.query="",l=UE;else{if("#"!=r){gE(UT(ET(n,d),""))||(c.host=i.host,c.path=ET(i.path),c.shortenPath()),l=xE;continue}c.host=i.host,c.path=ET(i.path),c.query=i.query,c.fragment="",l=FE}}break;case PE:if("/"==r||"\\"==r){l=ME;break}i&&"file"==i.scheme&&!gE(UT(ET(n,d),""))&&(fE(i.path[0],!0)?HT(c.path,i.path[0]):c.host=i.host),l=xE;continue;case ME:if(r==fg||"/"==r||"\\"==r||"?"==r||"#"==r){if(!t&&fE(u))l=xE;else if(""==u){if(c.host="",t)return;l=LE}else{if(s=c.parseHost(u))return s;if("localhost"==c.host&&(c.host=""),t)return;u="",l=LE}continue}u+=r;break;case LE:if(c.isSpecial()){if(l=xE,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=fg&&(l=xE,"/"!=r))continue}else c.fragment="",l=FE;else c.query="",l=UE;break;case xE:if(r==fg||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=KT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,"")):TE(u)?"/"==r||"\\"==r&&c.isSpecial()||HT(c.path,""):("file"==c.scheme&&!c.path.length&&fE(u)&&(c.host&&(c.host=""),u=xT(u,0)+":"),HT(c.path,u)),u="","file"==c.scheme&&(r==fg||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)GT(c.path);"?"==r?(c.query="",l=UE):"#"==r&&(c.fragment="",l=FE)}else u+=_E(r,hE);break;case VE:"?"==r?(c.query="",l=UE):"#"==r?(c.fragment="",l=FE):r!=fg&&(c.path[0]+=_E(r,dE));break;case UE:t||"#"!=r?r!=fg&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":_E(r,dE)):(c.fragment="",l=FE);break;case FE:r!=fg&&(c.fragment+=_E(r,uE))}d++}},parseHost:function(e){var t,i,n;if("["==xT(e,0)){if("]"!=xT(e,e.length-1))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return xT(e,u)};if(":"==h()){if(":"!=xT(e,1))return;u+=2,d=++l}for(;h();){if(8==l)return;if(":"!=h()){for(t=i=0;i<4&&VT(nE,h());)t=16*t+PT(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++}if(!VT(ZT,h()))return;for(;VT(ZT,h());){if(o=PT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[l]=256*c[l]+r,2!=++n&&4!=n||l++}if(4!=n)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(JT(e,1,-1)),!t)return qT;this.host=t}else if(this.isSpecial()){if(e=IT(e),VT(rE,e))return qT;if(t=function(e){var t,i,n,r,o,s,a,c=WT(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(o=10,r.length>1&&"0"==xT(r,0)&&(o=VT(eE,r)?16:8,r=JT(r,8==o?1:2)),""===r)s=0;else{if(!VT(10==o?iE:8==o?tE:nE,r))return e;s=PT(r,o)}HT(i,s)}for(n=0;n<t;n++)if(s=i[n],n==t-1){if(s>=LT(256,5-t))return null}else if(s>255)return null;for(a=BT(i),n=0;n<i.length;n++)a+=i[n]*LT(256,3-n);return a}(e),null===t)return qT;this.host=t}else{if(VT(oE,e))return qT;for(t="",i=TT(e),n=0;n<i.length;n++)t+=_E(i[n],dE);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"==this.scheme},includesCredentials:function(){return""!=this.username||""!=this.password},isSpecial:function(){return fT(mE,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"==this.scheme&&1==t&&fE(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==r?(l+="//",e.includesCredentials()&&(l+=i+(n?":"+n:"")+"@"),l+=lE(r),null!==o&&(l+=":"+o)):"file"==t&&(l+="//"),l+=e.cannotBeABaseURL?s[0]:s.length?"/"+UT(s,"/"):"",null!==a&&(l+="?"+a),null!==c&&(l+="#"+c),l},setHref:function(e){var t=this.parse(e);if(t)throw wT(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"==e)try{return new HE(e.path[0]).origin}catch(NU){return"null"}return"file"!=e&&this.isSpecial()?e+"://"+lE(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(vT(e)+":",EE)},getUsername:function(){return this.username},setUsername:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=_E(t[i],pE)}},getPassword:function(){return this.password},setPassword:function(e){var t=TT(vT(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=_E(t[i],pE)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?lE(e):lE(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,NE)},getHostname:function(){var e=this.host;return null===e?"":lE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,DE)},getPort:function(){var e=this.port;return null===e?"":vT(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""==(e=vT(e))?this.port=null:this.parse(e,OE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+UT(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,LE))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""==(e=vT(e))?this.query=null:("?"==xT(e,0)&&(e=JT(e,1)),this.query="",this.parse(e,UE)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!=(e=vT(e))?("#"==xT(e,0)&&(e=JT(e,1)),this.fragment="",this.parse(e,FE)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var HE=function(e){var t=mT(this,jE),i=AT(arguments.length,1)>1?arguments[1]:void 0,n=bT(t,new BE(e,!1,i));cT||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},jE=HE.prototype,GE=function(e,t){return{get:function(){return kT(this)[e]()},set:t&&function(e){return kT(this)[t](e)},configurable:!0,enumerable:!0}};if(cT&&(_T(jE,"href",GE("serialize","setHref")),_T(jE,"origin",GE("getOrigin")),_T(jE,"protocol",GE("getProtocol","setProtocol")),_T(jE,"username",GE("getUsername","setUsername")),_T(jE,"password",GE("getPassword","setPassword")),_T(jE,"host",GE("getHost","setHost")),_T(jE,"hostname",GE("getHostname","setHostname")),_T(jE,"port",GE("getPort","setPort")),_T(jE,"pathname",GE("getPathname","setPathname")),_T(jE,"search",GE("getSearch","setSearch")),_T(jE,"searchParams",GE("getSearchParams")),_T(jE,"hash",GE("getHash","setHash"))),pT(jE,"toJSON",(function(){return kT(this).serialize()}),{enumerable:!0}),pT(jE,"toString",(function(){return kT(this).serialize()}),{enumerable:!0}),OT){var WE=OT.createObjectURL,JE=OT.revokeObjectURL;WE&&pT(HE,"createObjectURL",uT(WE,OT)),JE&&pT(HE,"revokeObjectURL",uT(JE,OT))}yT(HE,"URL"),aT({global:!0,constructor:!0,forced:!lT,sham:!cT},{URL:HE});var KE=Vr,YE=kc,zE=i,qE=je,QE=Ee,XE=da,$E=iu,ZE=ir,eS=YE&&YE.prototype;if(KE({target:"Promise",proto:!0,real:!0,forced:!!YE&&zE((function(){eS.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=XE(this,qE("Promise")),i=QE(e);return this.then(i?function(i){return $E(t,e()).then((function(){return i}))}:e,i?function(i){return $E(t,e()).then((function(){throw i}))}:e)}}),QE(YE)){var tS=qE("Promise").prototype.finally;eS.finally!==tS&&ZE(eS,"finally",tS,{unsafe:!0})}var iS="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,nS=Mt,rS=Ht,oS=RangeError,sS=function(e){if(void 0===e)return 0;var t=nS(e),i=rS(t);if(t!==i)throw oS("Wrong length or index");return i},aS=Array,cS=Math.abs,lS=Math.pow,dS=Math.floor,uS=Math.log,hS=Math.LN2,pS={pack:function(e,t,i){var n,r,o,s=aS(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?lS(2,-24)-lS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=cS(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=dS(uS(e)/hS),e*(o=lS(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*lS(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*lS(2,t),n+=l):(r=e*lS(2,l-1)*lS(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<<t|r,a+=t;a>0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<<r)-1,s=o>>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=lS(2,t),d-=s}return(l?-1:1)*i*lS(2,d-t)}},_S=B,mS=Ut,fS=Gt,gS=function(e){for(var t=_S(this),i=fS(t),n=arguments.length,r=mS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:mS(o,i);s>r;)t[r++]=e;return t},TS=C,ES=c,SS=ke,IS=iS,vS=Dn,yS=Yi,AS=Is,RS=X_,CS=i,bS=Ns,kS=Mt,NS=Ht,DS=sS,OS=pS,wS=Kr,PS=vo,MS=nr.f,LS=gS,xS=am,VS=oo,US=cn,FS=vS.PROPER,BS=vS.CONFIGURABLE,HS="ArrayBuffer",jS="DataView",GS="prototype",WS="Wrong index",JS=US.getterFor(HS),KS=US.getterFor(jS),YS=US.set,zS=TS[HS],qS=zS,QS=qS&&qS[GS],XS=TS[jS],$S=XS&&XS[GS],ZS=Object.prototype,eI=TS.Array,tI=TS.RangeError,iI=ES(LS),nI=ES([].reverse),rI=OS.pack,oI=OS.unpack,sI=function(e){return[255&e]},aI=function(e){return[255&e,e>>8&255]},cI=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},lI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},dI=function(e){return rI(e,23,4)},uI=function(e){return rI(e,52,8)},hI=function(e,t,i){AS(e[GS],t,{configurable:!0,get:function(){return i(this)[t]}})},pI=function(e,t,i,n){var r=DS(i),o=KS(e);if(r+t>o.byteLength)throw tI(WS);var s=o.bytes,a=r+o.byteOffset,c=xS(s,a,a+t);return n?c:nI(c)},_I=function(e,t,i,n,r,o){var s=DS(i),a=KS(e);if(s+t>a.byteLength)throw tI(WS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(IS){var mI=FS&&zS.name!==HS;if(CS((function(){zS(1)}))&&CS((function(){new zS(-1)}))&&!CS((function(){return new zS,new zS(1.5),new zS(NaN),1!=zS.length||mI&&!BS})))mI&&BS&&yS(zS,"name",HS);else{(qS=function(e){return bS(this,QS),new zS(DS(e))})[GS]=QS;for(var fI,gI=MS(zS),TI=0;gI.length>TI;)(fI=gI[TI++])in qS||yS(qS,fI,zS[fI]);QS.constructor=qS}PS&&wS($S)!==ZS&&PS($S,ZS);var EI=new XS(new qS(2)),SI=ES($S.setInt8);EI.setInt8(0,2147483648),EI.setInt8(1,2147483649),!EI.getInt8(0)&&EI.getInt8(1)||RS($S,{setInt8:function(e,t){SI(this,e,t<<24>>24)},setUint8:function(e,t){SI(this,e,t<<24>>24)}},{unsafe:!0})}else QS=(qS=function(e){bS(this,QS);var t=DS(e);YS(this,{type:HS,bytes:iI(eI(t),0),byteLength:t}),SS||(this.byteLength=t,this.detached=!1)})[GS],$S=(XS=function(e,t,i){bS(this,$S),bS(e,QS);var n=JS(e),r=n.byteLength,o=kS(t);if(o<0||o>r)throw tI("Wrong offset");if(o+(i=void 0===i?r-o:NS(i))>r)throw tI("Wrong length");YS(this,{type:jS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),SS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[GS],SS&&(hI(qS,"byteLength",JS),hI(XS,"buffer",KS),hI(XS,"byteLength",KS),hI(XS,"byteOffset",KS)),RS($S,{getInt8:function(e){return pI(this,1,e)[0]<<24>>24},getUint8:function(e){return pI(this,1,e)[0]},getInt16:function(e){var t=pI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=pI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return lI(pI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return lI(pI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return oI(pI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return oI(pI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){_I(this,1,e,sI,t)},setUint8:function(e,t){_I(this,1,e,sI,t)},setInt16:function(e,t){_I(this,2,e,aI,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){_I(this,2,e,aI,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){_I(this,4,e,cI,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){_I(this,4,e,cI,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){_I(this,4,e,dI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){_I(this,8,e,uI,t,arguments.length>2?arguments[2]:void 0)}});VS(qS,HS),VS(XS,jS);var II={ArrayBuffer:qS,DataView:XS},vI=Cs,yI="ArrayBuffer",AI=II[yI];Vr({global:!0,constructor:!0,forced:C[yI]!==AI},{ArrayBuffer:AI}),vI(yI);var RI=Vr,CI=Ta,bI=i,kI=Ce,NI=Ut,DI=Ht,OI=da,wI=II.ArrayBuffer,PI=II.DataView,MI=PI.prototype,LI=CI(wI.prototype.slice),xI=CI(MI.getUint8),VI=CI(MI.setUint8);RI({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:bI((function(){return!new wI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(LI&&void 0===t)return LI(kI(this),e);for(var i=kI(this).byteLength,n=NI(e,i),r=NI(void 0===t?i:t,i),o=new(OI(this,wI))(DI(r-n)),s=new PI(this),a=new PI(o),c=0;n<r;)VI(a,c++,xI(s,n++));return o}});var UI,FI,BI,HI={},jI={get exports(){return HI},set exports(e){HI=e}},GI=iS,WI=ke,JI=C,KI=Ee,YI=ve,zI=G,qI=Vs,QI=Qe,XI=Yi,$I=ir,ZI=Is,ev=Ge,tv=Kr,iv=vo,nv=me,rv=z,ov=cn.enforce,sv=cn.get,av=JI.Int8Array,cv=av&&av.prototype,lv=JI.Uint8ClampedArray,dv=lv&&lv.prototype,uv=av&&tv(av),hv=cv&&tv(cv),pv=Object.prototype,_v=JI.TypeError,mv=nv("toStringTag"),fv=rv("TYPED_ARRAY_TAG"),gv="TypedArrayConstructor",Tv=GI&&!!iv&&"Opera"!==qI(JI.opera),Ev=!1,Sv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},Iv={BigInt64Array:8,BigUint64Array:8},vv=function(e){var t=tv(e);if(YI(t)){var i=sv(t);return i&&zI(i,gv)?i[gv]:vv(t)}},yv=function(e){if(!YI(e))return!1;var t=qI(e);return zI(Sv,t)||zI(Iv,t)};for(UI in Sv)(BI=(FI=JI[UI])&&FI.prototype)?ov(BI)[gv]=FI:Tv=!1;for(UI in Iv)(BI=(FI=JI[UI])&&FI.prototype)&&(ov(BI)[gv]=FI);if((!Tv||!KI(uv)||uv===Function.prototype)&&(uv=function(){throw _v("Incorrect invocation")},Tv))for(UI in Sv)JI[UI]&&iv(JI[UI],uv);if((!Tv||!hv||hv===pv)&&(hv=uv.prototype,Tv))for(UI in Sv)JI[UI]&&iv(JI[UI].prototype,hv);if(Tv&&tv(dv)!==hv&&iv(dv,hv),WI&&!zI(hv,mv))for(UI in Ev=!0,ZI(hv,mv,{configurable:!0,get:function(){return YI(this)?this[fv]:void 0}}),Sv)JI[UI]&&XI(JI[UI],fv,UI);var Av={NATIVE_ARRAY_BUFFER_VIEWS:Tv,TYPED_ARRAY_TAG:Ev&&fv,aTypedArray:function(e){if(yv(e))return e;throw _v("Target is not a typed array")},aTypedArrayConstructor:function(e){if(KI(e)&&(!iv||ev(uv,e)))return e;throw _v(QI(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,n){if(WI){if(i)for(var r in Sv){var o=JI[r];if(o&&zI(o.prototype,e))try{delete o.prototype[e]}catch(NU){try{o.prototype[e]=t}catch(s){}}}hv[e]&&!i||$I(hv,e,i?t:Tv&&cv[e]||t,n)}},exportTypedArrayStaticMethod:function(e,t,i){var n,r;if(WI){if(iv){if(i)for(n in Sv)if((r=JI[n])&&zI(r,e))try{delete r[e]}catch(NU){}if(uv[e]&&!i)return;try{return $I(uv,e,i?t:Tv&&uv[e]||t)}catch(NU){}}for(n in Sv)!(r=JI[n])||r[e]&&!i||$I(r,e,t)}},getTypedArrayConstructor:vv,isView:function(e){if(!YI(e))return!1;var t=qI(e);return"DataView"===t||zI(Sv,t)||zI(Iv,t)},isTypedArray:yv,TypedArray:uv,TypedArrayPrototype:hv},Rv=C,Cv=i,bv=Dd,kv=Av.NATIVE_ARRAY_BUFFER_VIEWS,Nv=Rv.ArrayBuffer,Dv=Rv.Int8Array,Ov=!kv||!Cv((function(){Dv(1)}))||!Cv((function(){new Dv(-1)}))||!bv((function(e){new Dv,new Dv(null),new Dv(1.5),new Dv(e)}),!0)||Cv((function(){return 1!==new Dv(new Nv(2),1,void 0).length})),wv=ve,Pv=Math.floor,Mv=Number.isInteger||function(e){return!wv(e)&&isFinite(e)&&Pv(e)===e},Lv=Mt,xv=RangeError,Vv=function(e){var t=Lv(e);if(t<0)throw xv("The argument can't be less than 0");return t},Uv=RangeError,Fv=function(e,t){var i=Vv(e);if(i%t)throw Uv("Wrong offset");return i},Bv=Vs,Hv=mt,jv=TypeError,Gv=function(e){var t=Hv(e,"number");if("number"==typeof t)throw jv("Can't convert number to bigint");return BigInt(t)},Wv=va,Jv=Fe,Kv=oa,Yv=B,zv=Gt,qv=ad,Qv=ed,Xv=zl,$v=function(e){var t=Bv(e);return"BigInt64Array"==t||"BigUint64Array"==t},Zv=Av.aTypedArrayConstructor,ey=Gv,ty=Vr,iy=C,ny=Fe,ry=ke,oy=Ov,sy=Av,ay=II,cy=Ns,ly=Wi,dy=Yi,uy=Mv,hy=Ht,py=sS,_y=Fv,my=Tt,fy=G,gy=Vs,Ty=ve,Ey=ze,Sy=Di,Iy=Ge,vy=vo,yy=nr.f,Ay=function(e){var t,i,n,r,o,s,a,c,l=Kv(this),d=Yv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,_=Qv(d);if(_&&!Xv(_))for(c=(a=qv(d,_)).next,d=[];!(s=Jv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Wv(h,arguments[2])),i=zv(d),n=new(Zv(l))(i),r=$v(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?ey(o):+o;return n},Ry=rp.forEach,Cy=Cs,by=Is,ky=De,Ny=ln,Dy=lu,Oy=cn.get,wy=cn.set,Py=cn.enforce,My=ky.f,Ly=Ny.f,xy=Math.round,Vy=iy.RangeError,Uy=ay.ArrayBuffer,Fy=Uy.prototype,By=ay.DataView,Hy=sy.NATIVE_ARRAY_BUFFER_VIEWS,jy=sy.TYPED_ARRAY_TAG,Gy=sy.TypedArray,Wy=sy.TypedArrayPrototype,Jy=sy.aTypedArrayConstructor,Ky=sy.isTypedArray,Yy="BYTES_PER_ELEMENT",zy="Wrong length",qy=function(e,t){Jy(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r},Qy=function(e,t){by(e,t,{configurable:!0,get:function(){return Oy(this)[t]}})},Xy=function(e){var t;return Iy(Fy,e)||"ArrayBuffer"==(t=gy(e))||"SharedArrayBuffer"==t},$y=function(e,t){return Ky(e)&&!Ey(t)&&t in e&&uy(+t)&&t>=0},Zy=function(e,t){return t=my(t),$y(e,t)?ly(2,e[t]):Ly(e,t)},eA=function(e,t,i){return t=my(t),!($y(e,t)&&Ty(i)&&fy(i,"value"))||fy(i,"get")||fy(i,"set")||i.configurable||fy(i,"writable")&&!i.writable||fy(i,"enumerable")&&!i.enumerable?My(e,t,i):(e[t]=i.value,e)};ry?(Hy||(Ny.f=Zy,ky.f=eA,Qy(Wy,"buffer"),Qy(Wy,"byteOffset"),Qy(Wy,"byteLength"),Qy(Wy,"length")),ty({target:"Object",stat:!0,forced:!Hy},{getOwnPropertyDescriptor:Zy,defineProperty:eA}),jI.exports=function(e,t,i){var n=e.match(/\d+/)[0]/8,r=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=iy[r],c=a,l=c&&c.prototype,d={},u=function(e,t){My(e,t,{get:function(){return function(e,t){var i=Oy(e);return i.view[o](t*n+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,r){var o=Oy(e);i&&(r=(r=xy(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0)}(this,t,e)},enumerable:!0})};Hy?oy&&(c=t((function(e,t,i,r){return cy(e,l),Dy(Ty(t)?Xy(t)?void 0!==r?new a(t,_y(i,n),r):void 0!==i?new a(t,_y(i,n)):new a(t):Ky(t)?qy(c,t):ny(Ay,c,t):new a(py(t)),e,c)})),vy&&vy(c,Gy),Ry(yy(a),(function(e){e in c||dy(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,r){cy(e,l);var o,s,a,d=0,h=0;if(Ty(t)){if(!Xy(t))return Ky(t)?qy(c,t):ny(Ay,c,t);o=t,h=_y(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw Vy(zy);if((s=p-h)<0)throw Vy(zy)}else if((s=hy(r)*n)+h>p)throw Vy(zy);a=s/n}else a=py(t),o=new Uy(s=a*n);for(wy(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new By(o)});d<a;)u(e,d++)})),vy&&vy(c,Gy),l=c.prototype=Sy(Wy)),l.constructor!==c&&dy(l,"constructor",c),Py(l).TypedArrayConstructor=c,jy&&dy(l,jy,r);var h=c!=a;d[r]=c,ty({global:!0,constructor:!0,forced:h,sham:!Hy},d),Yy in c||dy(c,Yy,n),Yy in l||dy(l,Yy,n),Cy(r)}):jI.exports=function(){},HI("Float32",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var tA=gS,iA=Gv,nA=Vs,rA=Fe,oA=i,sA=Av.aTypedArray,aA=Av.exportTypedArrayMethod,cA=c("".slice);aA("fill",(function(e){var t=arguments.length;sA(this);var i="Big"===cA(nA(this),0,3)?iA(e):+e;return rA(tA,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),oA((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var lA=C,dA=Fe,uA=Av,hA=Gt,pA=Fv,_A=B,mA=i,fA=lA.RangeError,gA=lA.Int8Array,TA=gA&&gA.prototype,EA=TA&&TA.set,SA=uA.aTypedArray,IA=uA.exportTypedArrayMethod,vA=!mA((function(){var e=new Uint8ClampedArray(2);return dA(EA,e,{length:1,0:3},1),3!==e[1]})),yA=vA&&uA.NATIVE_ARRAY_BUFFER_VIEWS&&mA((function(){var e=new gA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));IA("set",(function(e){SA(this);var t=pA(arguments.length>1?arguments[1]:void 0,1),i=_A(e);if(vA)return dA(EA,this,i,t);var n=this.length,r=hA(i),o=0;if(r+t>n)throw fA("Wrong length");for(;o<r;)this[t+o]=i[o++]}),!vA||yA);var AA=q.match(/firefox\/(\d+)/i),RA=!!AA&&+AA[1],CA=/MSIE|Trident/.test(q),bA=q.match(/AppleWebKit\/(\d+)\./),kA=!!bA&&+bA[1],NA=Ta,DA=i,OA=et,wA=pm,PA=RA,MA=CA,LA=ie,xA=kA,VA=Av.aTypedArray,UA=Av.exportTypedArrayMethod,FA=C.Uint16Array,BA=FA&&NA(FA.prototype.sort),HA=!(!BA||DA((function(){BA(new FA(2),null)}))&&DA((function(){BA(new FA(2),{})}))),jA=!!BA&&!DA((function(){if(LA)return LA<74;if(PA)return PA<67;if(MA)return!0;if(xA)return xA<602;var e,t,i=new FA(516),n=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,n[e]=e-2*t+3;for(BA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==n[e])return!0}));UA("sort",(function(e){return void 0!==e&&OA(e),jA?BA(this,e):wA(VA(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))}),!jA||HA);var GA=Qe,WA=TypeError,JA=Vr,KA=c,YA=et,zA=B,qA=Gt,QA=function(e,t){if(!delete e[t])throw WA("Cannot delete property "+GA(t)+" of "+GA(e))},XA=fu,$A=i,ZA=pm,eR=sp,tR=RA,iR=CA,nR=ie,rR=kA,oR=[],sR=KA(oR.sort),aR=KA(oR.push),cR=$A((function(){oR.sort(void 0)})),lR=$A((function(){oR.sort(null)})),dR=eR("sort"),uR=!$A((function(){if(nR)return nR<70;if(!(tR&&tR>3)){if(iR)return!0;if(rR)return rR<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)oR.push({k:t+n,v:i})}for(oR.sort((function(e,t){return t.v-e.v})),n=0;n<oR.length;n++)t=oR[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));JA({target:"Array",proto:!0,forced:cR||!lR||!dR||!uR},{sort:function(e){void 0!==e&&YA(e);var t=zA(this);if(uR)return void 0===e?sR(t):sR(t,e);var i,n,r=[],o=qA(t);for(n=0;n<o;n++)n in t&&aR(r,t[n]);for(ZA(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:XA(t)>XA(i)?1:-1}}(e)),i=qA(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)QA(t,n++);return t}}),HI("Uint8",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var hR=Vr,pR=Wh,_R=c([].reverse),mR=[1,2];hR({target:"Array",proto:!0,forced:String(mR)===String(mR.reverse())},{reverse:function(){return pR(this)&&(this.length=this.length),_R(this)}});var fR=Vr,gR=Fe,TR=c,ER=I,SR=Ee,IR=T,vR=pu,yR=fu,AR=nt,RR=Au,CR=qp,bR=me("replace"),kR=TypeError,NR=TR("".indexOf);TR("".replace);var DR=TR("".slice),OR=Math.max,wR=function(e,t,i){return i>e.length?-1:""===t?i:NR(e,t,i)};fR({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=ER(this),u=0,h=0,p="";if(!IR(e)){if(vR(e)&&(i=yR(ER(RR(e))),!~NR(i,"g")))throw kR("`.replaceAll` does not allow non-global regexes");if(n=AR(e,bR))return gR(n,e,d,t)}for(r=yR(d),o=yR(e),(s=SR(t))||(t=yR(t)),a=o.length,c=OR(1,a),u=wR(r,o,0);-1!==u;)l=s?yR(t(o,u,r)):CR(o,r,u,[],void 0,t),p+=DR(r,h,u)+l,h=u+a,u=wR(r,o,u+c);return h<r.length&&(p+=DR(r,h)),p}});let PR=!0,MR=!0;function LR(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function xR(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function VR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(PR=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function UR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(MR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function FR(){if("object"==typeof window){if(PR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function BR(e,t){MR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function HR(e){return"[object Object]"===Object.prototype.toString.call(e)}function jR(e){return HR(e)?Object.keys(e).reduce((function(t,i){const n=HR(e[i]),r=n?jR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function GR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?GR(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{GR(e,e.get(t),i)}))})))}function WR(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&GR(e,i,r)}))})),r}const JR=FR;function KR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),JR("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return JR("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function YR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function zR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else xR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function QR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function XR(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>WR(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>WR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function $R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function ZR(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return $R(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function eC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function tC(e,t){xR(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var iC=Object.freeze({__proto__:null,shimMediaStream:YR,shimOnTrack:zR,shimGetSendersWithDtmf:qR,shimGetStats:QR,shimSenderReceiverGetStats:XR,shimAddTrackRemoveTrackWithNative:$R,shimAddTrackRemoveTrack:ZR,shimPeerConnection:eC,fixNegotiationNeeded:tC,shimGetUserMedia:KR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then((t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function nC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){BR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function rC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function oC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(oN){if("TypeError"!==oN.name)throw oN;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function sC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function aC(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),xR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function cC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){BR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function lC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function dC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function uC(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function hC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function pC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var _C=Object.freeze({__proto__:null,shimOnTrack:rC,shimPeerConnection:oC,shimSenderGetStats:sC,shimReceiverGetStats:aC,shimRemoveStream:cC,shimRTCDataChannel:lC,shimAddTransceiver:dC,shimGetParameters:uC,shimCreateOffer:hC,shimCreateAnswer:pC,shimGetUserMedia:nC,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function mC(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...i){return i&&i.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function fC(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function gC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function TC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(EC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function EC(e){return e&&void 0!==e.video?Object.assign({},e,{video:jR(e.video)}):e}function SC(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(BR("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function IC(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function vC(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function yC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var AC=Object.freeze({__proto__:null,shimLocalStreamsAPI:mC,shimRemoteStreamsAPI:fC,shimCallbacksAPI:gC,shimGetUserMedia:TC,shimConstraints:EC,shimRTCIceServerUrls:SC,shimTrackEventTransceiver:IC,shimCreateOfferLegacy:vC,shimAudioContext:yC}),RC={},CC={get exports(){return RC},set exports(e){RC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<n.length;r++)i=n[r].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const r=n[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const n=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=o.length?t.parseFmtp(o[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(CC);var bC=RC,kC=e({__proto__:null,default:bC},[RC]);function NC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=bC.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,xR(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function DC(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xR(e,"icecandidate",(e=>{if(e.candidate){const t=bC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function OC(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=bC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=bC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=bC.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>r}),this._sctp=o}return i.apply(this,arguments)}}function wC(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},xR(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function PC(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function MC(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 LC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xC(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var VC=Object.freeze({__proto__:null,shimRTCIceCandidate:NC,shimRTCIceCandidateRelayProtocol:DC,shimMaxMessageSize:OC,shimSendThrowTypeError:wC,shimConnectionState:PC,removeExtmapAllowMixed:MC,shimAddIceCandidateNullOrEmpty:LC,shimParameterlessSetLocalDescription:xC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=FR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=LR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=LR(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=LR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:VC,extractVersion:LR,disableLog:VR,disableWarnings:UR,sdp:kC};switch(n.browser){case"chrome":if(!iC||!eC||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=iC,LC(e,n),xC(e),KR(e,n),YR(e),eC(e,n),zR(e),ZR(e,n),qR(e),QR(e),XR(e),tC(e,n),NC(e),DC(e),PC(e),OC(e,n),wC(e),MC(e,n);break;case"firefox":if(!_C||!oC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=_C,LC(e,n),xC(e),nC(e,n),oC(e,n),rC(e),cC(e),sC(e),aC(e),lC(e),dC(e),uC(e),hC(e),pC(e),NC(e),PC(e),OC(e,n),wC(e);break;case"safari":if(!AC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=AC,LC(e,n),xC(e),SC(e),vC(e),gC(e),mC(e),fC(e),IC(e),TC(e),yC(e),NC(e),DC(e),OC(e,n),wC(e),MC(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var UC,FC=Object.create,BC=Object.defineProperty,HC=Object.defineProperties,jC=Object.getOwnPropertyDescriptor,GC=Object.getOwnPropertyDescriptors,WC=Object.getOwnPropertyNames,JC=Object.getOwnPropertySymbols,KC=Object.getPrototypeOf,YC=Object.prototype.hasOwnProperty,zC=Object.prototype.propertyIsEnumerable,qC=Reflect.get,QC=Math.pow,XC=(e,t,i)=>t in e?BC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,$C=(e,t)=>{for(var i in t||(t={}))YC.call(t,i)&&XC(e,i,t[i]);if(JC)for(var i of JC(t))zC.call(t,i)&&XC(e,i,t[i]);return e},ZC=(e,t)=>HC(e,GC(t)),eb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tb=(e,t)=>{for(var i in t)BC(e,i,{get:t[i],enumerable:!0})},ib=(e,t,i)=>(i=null!=e?FC(KC(e)):{},((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of WC(t))!YC.call(e,r)&&r!==i&&BC(e,r,{get:()=>t[r],enumerable:!(n=jC(t,r))||n.enumerable});return e})(!t&&e&&e.__esModule?i:BC(i,"default",{value:e,enumerable:!0}),e)),nb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?jC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&BC(t,i,o),o},rb=(e,t,i)=>(XC(e,"symbol"!=typeof t?t+"":t,i),i),ob=(e,t,i)=>qC(KC(e),i,t),sb=(e,t,i)=>new Promise(((n,r)=>{var o=e=>{try{a(i.next(e))}catch(t){r(t)}},s=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),ab=eb(((e,t)=>{var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,r,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},c.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,o),!0;case 6:return d.fn.call(d.context,t,i,r,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,r);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||r&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),cb=eb(((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d 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":"")}},{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:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\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:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),lb=eb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))})(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=cb(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,s,r)}})),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}})),db=eb(((e,t)=>{var i=cb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?n.push(i[t.name][s]):n.push(i[t.names[o]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,r=t.innerOrder||a,c=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),ub=eb((e=>{var t=lb(),i=db();e.write=i,e.parse=t.parse,e.parseFmtpConfig=t.parseFmtpConfig,e.parseParams=t.parseParams,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),hb=ib(ab()),pb=((UC=pb||{})[UC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",UC[UC.INVALID_OPERATION=4097]="INVALID_OPERATION",UC[UC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",UC[UC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",UC[UC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",UC[UC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",UC[UC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",UC[UC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",UC[UC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",UC[UC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",UC[UC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",UC[UC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",UC[UC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",UC[UC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",UC[UC.CLIENT_BANNED=16448]="CLIENT_BANNED",UC[UC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",UC[UC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",UC[UC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",UC[UC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",UC[UC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",UC[UC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",UC[UC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",UC[UC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",UC[UC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",UC[UC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",UC[UC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",UC[UC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",UC[UC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",UC[UC.UNKNOWN=65535]="UNKNOWN",UC),_b=pb,mb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:n=_b.UNKNOWN,extraCode:r=0,constraint:o}=e,s="<".concat(function(e){for(let t in _b)if(_b[t]===e)return t;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),rb(this,"code"),rb(this,"extraCode"),rb(this,"message"),rb(this,"originMessage"),rb(this,"name"),rb(this,"constraint"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},fb=mb,gb=((new Date).getTime(),0),Tb=function(){return(new Date).getTime()+gb},Eb=function(){let e=new Date;return e.setTime(Tb()),e.toLocaleString()},Sb={};tb(Sb,{bytes2ms:()=>JD,copyProperties:()=>WD,deepClone:()=>RO,deepMerge:()=>AO,env:()=>Ib,fibonacci:()=>$D,formatedTime:()=>kO,getConstructorName:()=>hO,getContainerFromElement:()=>CO,getEnv:()=>VD,getInternalVersion:()=>gO,getLoggerUrl:()=>FD,getMuteStateFromFlag:()=>SO,getNetworkQuality:()=>IO,getNetworkType:()=>jD,getOSType:()=>HD,getReconnectionTimeout:()=>ZD,getStringByteLength:()=>OO,getSysInfo:()=>GD,getTerminalType:()=>BD,getTurnServer:()=>vO,getValueType:()=>eO,glog:()=>qD,ipv4ToUint32:()=>yO,isArray:()=>aO,isAudioWorkletSupported:()=>pO,isBoolean:()=>oO,isConstructor:()=>uO,isEmpty:()=>EO,isFunction:()=>tO,isLangChinese:()=>QD,isMediaStreamTrack:()=>cO,isNumber:()=>rO,isObject:()=>sO,isOverseaSdkAppId:()=>UD,isPlainObject:()=>XD,isPortrait:()=>PO,isPromise:()=>dO,isRemoteTrack:()=>lO,isString:()=>nO,isUndefined:()=>iO,logVisibilityState:()=>wO,ms2bytes:()=>YD,ms2samples:()=>zD,performanceNow:()=>mO,promiseAny:()=>_O,samples2ms:()=>KD,stringify:()=>NO,stringifyIncludeValue:()=>DO});var Ib={};tb(Ib,{ANDROID_VERSION:()=>Mb,CHROME_MAJOR_VERSION:()=>Lk,CHROME_VERSION:()=>xk,EDGE_VERSION:()=>Hb,EDG_MAJOR_VERSION:()=>Wb,EDG_VERSION:()=>Gb,FIREFOX_MAJOR_VERSION:()=>Fb,FIREFOX_VERSION:()=>Ub,HUAWEI_VERSION:()=>Ak,IE_VERSION:()=>tk,IOS_MAIN_VERSION:()=>jk,IOS_VERSION:()=>Hk,IPADQQB_VERSION:()=>hk,IS_ANDROID:()=>Pb,IS_ANDROID_WEBVIEW:()=>Bk,IS_ANY_SAFARI:()=>Uk,IS_CHROME:()=>Pk,IS_CHROME_OS:()=>fk,IS_CHROMIUM_BASE:()=>wk,IS_EDG:()=>jb,IS_EDGE:()=>Bb,IS_ELECTRON:()=>Ek,IS_FIREFOX:()=>Vb,IS_HEADLESS_CHROME:()=>Mk,IS_HUAWEI:()=>yk,IS_HUAWEIBROWSER:()=>vk,IS_IE:()=>ek,IS_IE8:()=>Zb,IS_IOS:()=>wb,IS_IOS_13_OR_14:()=>Jk,IS_IOS_15_1:()=>Wk,IS_IPAD:()=>kb,IS_IPADQQB:()=>uk,IS_IPAD_PRO:()=>Nb,IS_IPHONE:()=>Db,IS_IPOD:()=>Ob,IS_LINUX:()=>mk,IS_LOCAL:()=>Kk,IS_MAC:()=>_k,IS_MACQQB:()=>lk,IS_MIBROWSER:()=>Sk,IS_MQQB:()=>ok,IS_NATIVE_ANDROID:()=>xb,IS_OLD_ANDROID:()=>Lb,IS_OPPOBROWSER:()=>bk,IS_SAFARI:()=>Vk,IS_SAFARI_15_1:()=>Gk,IS_SAMSUNGBROWSER:()=>Rk,IS_SOGOU:()=>Yb,IS_SOGOUM:()=>Jb,IS_TBS:()=>qb,IS_UCBROWSER:()=>Tk,IS_VIVOBROWSER:()=>Nk,IS_WECHAT:()=>ik,IS_WIN:()=>pk,IS_WQQB:()=>ak,IS_WX:()=>gk,IS_X5MQQB:()=>rk,IS_XWEB:()=>Xb,MACQQB_VERSION:()=>dk,MI_VERSION:()=>Ik,MQQB_VERSION:()=>sk,OPPO_VERSION:()=>kk,SAFARI_VERSION:()=>Fk,SAMSUNG_VERSION:()=>Ck,SOGOUM_VERSION:()=>Kb,SOGOU_VERSION:()=>zb,TBS_VERSION:()=>Qb,USER_AGENT:()=>vb,VIVO_VERSION:()=>Dk,WECHAT_VERSION:()=>nk,WQQB_VERSION:()=>ck,XWEB_VERSION:()=>$b,browserInfo:()=>zk,getBrowserInfo:()=>qk,getChromeMajorVersion:()=>Ok,getOSName:()=>Zk,getOSString:()=>eN,getUserAgentData:()=>Xk,isLocalStorageEnabled:()=>Yk});var vb="undefined"==typeof navigator?"":navigator.userAgent,yb=e=>new RegExp(e,"i").test(vb),Ab=e=>{if(yb(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=vb.match(t);if(i&&i[1])return i[1]}return""},Rb=e=>{if(yb(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=vb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},Cb=/AppleWebKit\/([\d.]+)/i.exec(vb),bb=Cb?parseFloat(Cb[1]):NaN,kb=yb("iPad"),Nb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&yb("Macintosh"),Db=yb("iPhone")&&!kb,Ob=yb("iPod"),wb=Db||kb||Ob||Nb,Pb=yb("Android"),Mb=function(){if(Pb){let e=vb.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){let t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),Lb=Pb&&yb("webkit")&&Mb<2.3,xb=Pb&&Mb<5&&bb<537,Vb=yb("Firefox"),Ub=Ab("Firefox"),Fb=Rb("Firefox"),Bb=yb("Edge"),Hb=Ab("Edge"),jb=yb("Edg"),Gb=Ab("Edg"),Wb=Rb("Edg"),Jb=yb("SogouMobileBrowser"),Kb=Ab("SogouMobileBrowser"),Yb=yb("MetaSr\\s"),zb=Ab("MetaSr\\s"),qb=yb("TBS"),Qb=Ab("TBS"),Xb=yb("XWEB"),$b=Ab("XWEB"),Zb=yb("MSIE\\s8\\.0"),ek=yb("MSIE\\/\\d+"),tk=function(){if(ek){let e=/MSIE\s(\d+)\.\d/.exec(vb),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(vb)&&/rv:11.0/.test(vb)&&(t=11),t}return NaN}(),ik=yb("(micromessenger|webbrowser)"),nk=Ab("MicroMessenger"),rk=!qb&&yb("MQQBrowser")&&yb("COVC"),ok=!qb&&yb("MQQBrowser")&&!yb("COVC"),sk=ok||rk?Ab("MQQBrowser"):"",ak=!qb&&yb(" QQBrowser"),ck=Ab(" QQBrowser"),lk=!qb&&yb("QQBrowserLite"),dk=Ab("QQBrowserLite"),uk=!qb&&yb("MQBHD"),hk=Ab("MQBHD"),pk=yb("Windows"),_k=!wb&&yb("MAC OS X"),mk=!Pb&&yb("Linux"),fk=yb("CrOS"),gk=yb("MicroMessenger"),Tk=yb("UCBrowser"),Ek=yb("Electron"),Sk=yb("MiuiBrowser"),Ik=Ab("MiuiBrowser"),vk=yb("HuaweiBrowser"),yk=yb("Huawei"),Ak=Ab("HuaweiBrowser"),Rk=yb("SamsungBrowser"),Ck=Ab("SamsungBrowser"),bk=yb("HeyTapBrowser"),kk=Ab("HeyTapBrowser"),Nk=yb("VivoBrowser"),Dk=Ab("VivoBrowser"),Ok=()=>Rb("Chrome"),wk=yb("Chrome"),Pk=!Bb&&!Yb&&!Jb&&!qb&&!Xb&&!jb&&!ak&&!Sk&&!vk&&!Rk&&!bk&&!Nk&&wk,Mk=yb("HeadlessChrome"),Lk=Ok(),xk=Ab("Chrome"),Vk=!wk&&!ok&&!rk&&!lk&&!uk&&yb("Safari"),Uk=Vk||wb,Fk=Ab("Version"),Bk=/Android.*(wv|.0.0.0)/.test(vb),Hk=(()=>{if(Nb)return Fk;if(wb){let e=vb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),jk=Number(Hk.split(".")[0]),Gk="15.1"===Fk,Wk="15.1"===Hk,Jk=(()=>{let e=Number(Hk.split(".")[0]);return 14===e||13===e})(),Kk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),Yk=(()=>{let e;return()=>{if(iO(e))try{e=!!window.localStorage}catch(qM){e=!1}return e}})(),zk=qk();function qk(){let e=new Map([[Vb,["Firefox",Ub]],[jb,["Edg",Gb]],[Pk,["Chrome",xk]],[Vk,["Safari",Fk]],[qb,["TBS",Qb]],[Xb,["XWEB",$b]],[ik&&Db,["WeChat",nk]],[ak,["QQ(Win)",ck]],[ok,["QQ(Mobile)",sk]],[rk,["QQ(Mobile X5)",sk]],[lk,["QQ(Mac)",dk]],[uk,["QQ(iPad)",hk]],[Sk,["MI",Ik]],[vk,["HW",Ak]],[Rk,["Samsung",Ck]],[bk,["OPPO",kk]],[Nk,["VIVO",Dk]],[Bb,["EDGE",Hb]],[Jb,["SogouMobile",Kb]],[Yb,["Sogou",zb]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Qk=null;function Xk(){return sb(this,null,(function*(){if(Qk)return Qk;if(!navigator.userAgentData||!tO(navigator.userAgentData.getHighEntropyValues))return null;try{return Qk=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(zM){return null}}))}var $k=new Map([[Pb,"Android"],[wb,"iOS"],[pk,"Windows"],[_k,"MacOS"],[mk,"Linux"],[fk,"ChromeOS"]]),Zk=function(){return $k.get(!0)?$k.get(!0):Qk?Qk.platform:"unknown"},eN=()=>{let e=Zk();return e+="/".concat(zk.name,"/").concat(Vk?zk.version:zk.version.split(".")[0]),null!=Qk&&Qk.platformVersion&&(e+="/".concat(Qk.platformVersion)),null!=Qk&&Qk.architecture&&(e+="/".concat(Qk.architecture)),e},tN={};tb(tN,{AUDIO_MUTE_BIT:()=>HN,AUDIO_STAT_BIT:()=>BN,AUX_STAT_BIT:()=>FN,AUX_STREAM_MSID:()=>WN,BACKEND_ENV:()=>LN,BASE_DOC_URL:()=>gN,BASE_HOST:()=>pN,CAPABILITIES_KEYS:()=>LD,CLASS_NAME:()=>vD,CLOUD_CONSOLE_URL:()=>fN,DATA_FREEZE_TIMING:()=>mD,DOC_URL:()=>TN,DTLS_STATE_UNKNOWN:()=>eD,ENV_NAME:()=>yN,EXCHANGE_SDP_TIMEOUT:()=>dD,INTERVAL:()=>PD,IS_WORKER:()=>cN,IS_WORKLET:()=>lN,KIBANA_EVENT:()=>aD,LOCAL_STREAM_PUBLISH_STATE:()=>_D,LOGGER_CMD_TYPE:()=>vN,LOGGER_DOMAIN:()=>EN,LOGGER_DOMAIN_OVERSEA:()=>SN,LOG_LEVEL:()=>AN,LOG_LEVEL_NAME:()=>bD,MAIN_STREAM_MSID:()=>GN,MICROPHONE_COMMUNICATIONS:()=>CD,MICROPHONE_DEFAULT:()=>AD,NAME:()=>PN,NETWORK_TYPE:()=>bN,NOT_SUPPORTED_H264:()=>pD,PAUSED_RETRY_COUNT:()=>yD,PEERCONNECTION_CONNECTING_TIMEOUT:()=>ED,PEER_CONNECTION_STATE:()=>tD,PEER_LEAVE_REASON:()=>kD,RAF:()=>wD,RECOVER_CAPTURE_INTERVAL:()=>DD,REMOTE_STREAM_TYPE_AUX:()=>KN,REMOTE_STREAM_TYPE_MAIN:()=>JN,RENDER_FREEZE_TIMING:()=>fD,RIC:()=>OD,SCHEDULE_DOMAIN:()=>SD,SCHEDULE_TIMEOUT:()=>ID,SDP_SEMANTICS_PLAN_B:()=>hD,SDP_SEMANTICS_UNIFIED_PLAN:()=>uD,SECOND_HOST:()=>_N,SIGNAL_PING_PONG_INTERVAL:()=>CN,SIGNAL_PING_TIMEOUT:()=>RN,SIGNAL_RECONNECTION_COUNT:()=>sD,SMALL_STAT_BIT:()=>UN,SPEAKER_DEFAULT:()=>RD,STORAGE_EXPIRES_TIME:()=>kN,STREAM_TYPE_BIG:()=>gD,STREAM_TYPE_SMALL:()=>TD,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ND,SYNC_USER_LIST_INTERVAL:()=>cD,Scene:()=>xN,Switch:()=>NN,THIRD_HOST:()=>mN,TIMEOUT:()=>MD,TRANSPORT_DIRECTION:()=>MN,TRTC_ERROR_ASSISTANCE:()=>IN,TRTC_QUALITY_BAD:()=>XN,TRTC_QUALITY_DISCONNECTED:()=>ZN,TRTC_QUALITY_EXCELLENT:()=>zN,TRTC_QUALITY_GOOD:()=>qN,TRTC_QUALITY_POOR:()=>QN,TRTC_QUALITY_UNKNOWN:()=>YN,TRTC_QUALITY_VERY_BAD:()=>$N,UPDATE_OFFER_TIMEOUT:()=>lD,VIDEO_MUTE_BIT:()=>jN,VIDEO_STAT_BIT:()=>VN,audioProfileMap:()=>DN,getRetryCount:()=>rD,getScriptDir:()=>dN,innerVersion:()=>iN,loggerProxy:()=>uN,screenProfileMap:()=>wN,setLoggerProxy:()=>hN,setRetryCount:()=>nD,setVersion:()=>rN,version:()=>nN,videoProfileMap:()=>ON});var iN="4.15.00.1600",nN="5.0.0";function rN(e){nN=e;let[t,i,n]=e.split(".").map((e=>parseInt(e,10)));iN="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,n),".").concat(i.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var oN,sN,aN,cN="undefined"!=typeof importScripts,lN="undefined"!=typeof registerProcessor,dN=()=>{let e=cN?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},uN="",hN=e=>uN=e,pN="web.sdk.qcloud.com",_N="web.sdk.tencent.cn",mN="web.sdk.cloud.tencent.cn",fN="https://console.cloud.tencent.com/trtc",gN="https://".concat(pN,"/trtc/webrtc/v5/doc"),TN="".concat(gN,"/zh-cn/"),EN="https://yun.tim.qq.com",SN="https://apisgp.my-imcloud.com",IN="trtc_error_assistance",vN={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},yN={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},AN=((aN=AN||{})[aN.TRACE=0]="TRACE",aN[aN.DEBUG=1]="DEBUG",aN[aN.INFO=2]="INFO",aN[aN.WARN=3]="WARN",aN[aN.ERROR=4]="ERROR",aN[aN.NONE=5]="NONE",aN),RN=18e3,CN=2e3,bN={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},kN=6048e5,NN=((sN=NN||{}).USEAINS="useAINS",sN.ENABLEDEBUG="enableDebug",sN.USEV2="useV2",sN.USEWT="useWt",sN),DN={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},ON={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},wN={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},PN={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},MN={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},LN={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xN=((oN=xN||{}).LIVE="live",oN.RTC="rtc",oN),VN=1,UN=2,FN=4,BN=8,HN=64,jN=16,GN="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",WN="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",JN=PN.MAIN,KN=PN.AUXILIARY,YN=0,zN=1,qN=2,QN=3,XN=4,$N=5,ZN=6,eD="unknown",tD={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},iD=1/0;function nD(e){iD=e}function rD(){return iD}var oD,sD=30,aD={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},cD=1e4,lD=1e4,dD=1e4,uD="unified-plan",hD="plan-b",pD=1028,_D=((oD=_D||{})[oD.UNPUBLISH=-1]="UNPUBLISH",oD[oD.PUBLISHING=0]="PUBLISHING",oD[oD.PUBLISHED=1]="PUBLISHED",oD),mD=500,fD=1e3,gD=PN.BIG,TD=PN.SMALL,ED=1e4,SD={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},ID=2e3,vD={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},yD=5,AD="default",RD=AD,CD="communications",bD=Object.keys(AN),kD=["normal leave","timeout leave","kick","role change"],ND=10,DD=2e3,OD="ric",wD="raf",PD="interval",MD="timeout",LD=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],xD=1e8,VD=function(){return new URLSearchParams(location.search).get("trtc_env")||""},UD=e=>Number(e)<14e8,FD=function(e,t){let i;i=uN||(UD(e)?SN:EN);let n=Math.floor(Math.random()*QC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function BD(){return Pb?4:Db?2:kb?3:_k?12:pk?5:mk?13:1}function HD(){return Pb?"Android":Db?"iPhone":kb?"iPad":_k?"Mac":pk?"Windows":mk?"Linux":"unknown"}function jD(){let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();"slow-2"===r&&(r="2g");let o=i||"unknown";if(n)switch(n){case"cellular":case"wimax":o=r||"unknown";break;case"wifi":o="wifi";break;case"ethernet":o="wired";break;default:o="unknown"}return o}var GD=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:BD(),uint32_device_type:0,str_os_verion:HD(),uint32_link_type:1,str_client_version:iN,uint32_net_type:bN[jD()],ua:navigator.userAgent,version:""}}}};function WD(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,n)}return e}function JD(e){return KD(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function KD(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function YD(e){return 4*zD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function zD(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var qD="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},QD=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},XD=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 $D(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:$D(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function ZD(e){return e>8?3e4:1e3*$D(e)}function eO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var tO=e=>"function"==typeof e,iO=e=>void 0===e,nO=e=>"string"==typeof e,rO=e=>"number"==typeof e,oO=e=>"boolean"==typeof e,sO=e=>"object"===eO(e),aO=e=>"array"===eO(e),cO=e=>eO(e)==="MediaStreamTrack".toLowerCase(),lO=e=>e.isRemote,dO=e=>"promise"===eO(e),uO=e=>tO(e)&&e.prototype.constructor===e,hO=e=>uO(e)?e.prototype.constructor.name:"",pO="undefined"!=typeof AudioWorkletNode;function _O(e){return new Promise(((t,i)=>{let n=[];e.forEach((r=>{r.then(t).catch((t=>{n.push(t),n.length===e.length&&i(n)}))}))}))}function mO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var fO=e=>+e<10?"0".concat(e):e,gO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),n=fO(i[1])+fO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(n)},TO=Object.prototype.hasOwnProperty;function EO(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(XD(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(TO.call(e,t))return!1;return!0}return!1}function SO(e,t){return{userId:t,hasAudio:!!(e&BN),hasVideo:!!(e&VN),hasAuxiliary:!!(e&FN),hasSmall:!!(e&UN),audioMuted:!!(e&HN),videoMuted:!!(e&jN),audioAvailable:!(!(e&BN)||e&HN),videoAvailable:!(!(e&VN)||e&jN)}}function IO(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}function vO(e){let t={urls:"turn:".concat(e.url)};return!iO(e.username)&&!iO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",iO(e.credentialType)||(t.credentialType=e.credentialType)),t}function yO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!nO(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 AO=function(e,t,i,n){if(!sO(e)||!sO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(r=s[a],!(iO(t[r])||i&&i.includes(r)))if(sO(e[r])&&sO(t[r]))o+=AO(e[r],t[r],i,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=RO(t[r]),o+=1)}return o};function RO(e){if(aO(e)){let t=[];return e.forEach(((e,i)=>{t[i]=RO(e)})),t}if(sO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=RO(e[i])})),t}return e}var CO=e=>nO(e)?document.getElementById(e):e,bO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),kO=()=>bO.format(new Date);function NO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(aO(e))return"[".concat(e.map((e=>NO(e,{keysToInclude:i,keysToExclude:n}))).join(","),"]");if(!XD(e)||!aO(i)&&!aO(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach((s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=XD(e[s])||aO(e[s])?JSON.parse(NO(e[s],{keysToExclude:n,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(oD){return"{}"}}function DO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((n=>{t===e[n]&&i.push(n)})),NO(e,{keysToInclude:i})}function OO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var wO=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&jO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{jO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),PO=()=>{var e,t,i;return!(null==(i=null==(t=null==(e=window.screen)?void 0:e.orientation)?void 0:t.type)||!i.includes("portrait"))};function MO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=r||5e3,o.open(n||"POST",t,!0),o.send(i)}))}var LO,xO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,_=0,m=(e,i)=>sb(this,null,(function*(){let l=a||this;try{let i=yield t.apply(l,c);h>0&&s&&s.call(this,h),h=0,e(i)}catch(f){let t=()=>{clearTimeout(p),h=0,_=2,i(f)},s=()=>{2!==_&&h<(tO(d)?d():d)?(h++,_=1,tO(r)&&r.call(this,h,t),p=window.setTimeout((()=>{p=-1,m(e,i)}),tO(u)?u(h):u)):(t(),tO(o)&&o.call(this,f))};tO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(m)}},VO=class{constructor(e){rb(this,"userId"),rb(this,"remoteUserId"),rb(this,"id"),rb(this,"sdkAppId"),rb(this,"type"),rb(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!oO(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):"","]")),jO.log(e,t,iO(this.userId)||EO(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)}},UO=new(ib(ab(),1).default),FO=((LO=FO||{}).ROOM_DESTROY="1",LO.JOIN_START="21",LO.JOIN_SCHEDULE_SUCCESS="22",LO.JOIN_SIGNAL_CONNECTION_START="23",LO.JOIN_SIGNAL_CONNECTION_END="24",LO.JOIN_SEND_CMD="25",LO.JOIN_RECEIVED_CMD_RES="26",LO.JOIN_SUCCESS="27",LO.JOIN_FAILED="28",LO.LEAVE_START="51",LO.LEAVE_SEND_CMD="52",LO.LEAVE_SUCCESS="53",LO.PUBLISH_START="61",LO.SEND_FIRST_VIDEO_FRAME="62",LO.PUBLISH_FAILED="63",LO.SUBSCRIBE_START="81",LO.SUBSCRIBE_SUCCESS="82",LO.SUBSCRIBE_FAILED="84",LO.UNSUBSCRIBE_SUCCESS="83",LO.LOCAL_TRACK_CAPTURE_START="101",LO.LOCAL_TRACK_CAPTURE_SUCCESS="102",LO.LOCAL_TRACK_CAPTURE_FAILED="103",LO.LOCAL_TRACK_PUBLISHED="104",LO.LOCAL_TRACK_UNPUBLISHED="105",LO.LOCAL_TRACK_REPLACED="106",LO.SWITCH_DEVICE_SUCCESS="107",LO.TRACK_MUTED="108",LO.TRACK_UNMUTED="109",LO.REMOTE_TRACK_SUBSCRIBED="110",LO.REMOTE_TRACK_UNSUBSCRIBED="111",LO.PLAY_TRACK_START="151",LO.PLAYER_STATE_CHANGED="152",LO.VIDEO_LOADED_DATA="153",LO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",LO.WORKLET_LOADED_SUCCESS="155",LO.WORKLET_LOADED_FAILED="156",LO.SIGNAL_CONNECTION_STATE_CHANGED="201",LO.PEER_CONNECTION_STATE_CHANGED="202",LO.SINGLE_CONNECTION_STAT="203",LO.HEARTBEAT_REPORT="251",LO.RECEIVED_PUBLISHED_USER_LIST="252",LO.REMOTE_PUBLISH_STATE_CHANGED="253",LO.AUDIO_LEVEL_INTERVAL="260",LO.NETWORK_QUALITY="261",LO.API_SUCCESS_RATE="262",LO),BO=FO,HO=!(wb||Pb||Mk),jO=new class{constructor(){rb(this,"_isEnableUploadLog",!0),rb(this,"_localJoinedUser",new Map),rb(this,"_queue",[]),rb(this,"_timeoutId",-1),rb(this,"_logLevel",1),rb(this,"_logLevelToUpload",2),!cN&&!lN&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){UO.on(BO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&AN[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),UO.on(BO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),UO.once(BO.JOIN_FAILED,(()=>{this.startUpload()})),UO.on(BO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]})}));else if(nO(i.userId)&&rO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return sb(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:n,logs:r}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Eb(),sdkAppId:String(n),userId:i,version:nN,log:r.map((e=>e.log)).join("\n")}),n),r.forEach((e=>e.uploaded=!0))}}catch(sN){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return xO({retryFunction:()=>MO({url:FD(t,vN.LOG),body:e,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:e=>{let{retry:t}=e;t()}})()}getPrefix(e){let t=new Date;t.setTime(Tb());let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),"[".concat(t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(i,"] <").concat(AN[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){iO(AN[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(nO(e))return e;try{return JSON.stringify(e)}catch(oN){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:n,sdkAppId:r,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=AN[e])?void 0:o.toLowerCase())||"info";HO?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 VO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;AN[t]&&(this._logLevelToUpload=t)}},GO=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)}))},WO=new class{constructor(){rb(this,"_prefix","TRTC"),rb(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){Yk()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=JSON.parse(localStorage.getItem(e));if(t&&t.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(Yk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(qM){jO.warn(qM)}}getItem(e){if(!Yk())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(oN){jO.warn(oN)}}setItem(e,t){if(Yk())try{let i={expiresIn:Date.now()+kN,value:t};this._queue.set(this.getRealKey(e),i)}catch(oD){jO.warn(oD)}}deleteItem(e){if(!Yk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(oN){return jO.warn(oN),!1}}clear(){if(Yk())try{localStorage.clear()}catch(qM){jO.warn(qM)}}},JO={};tb(JO,{HTTPS_API:()=>uw,IS_GET_CAPABILITIES_SUPPORTED:()=>kw,IS_GET_SETTINGS_SUPPORTED:()=>bw,IS_SEI_SUPPORTED:()=>Nw,IS_SPC_SUPPORTED:()=>yw,basis:()=>Mw,checkSystemRequirementsInternal:()=>cw,decodeSupportStatus:()=>aw,encodeSupportStatus:()=>sw,getBrowserInfo:()=>ZO,getDisplayResolution:()=>pw,isAddTransceiverSupported:()=>vw,isBrowserSupported:()=>ew,isGetReceiversSupported:()=>Ew,isGetSendersSupported:()=>Sw,isGetTransceiversSupported:()=>Iw,isGetUserMediaSupported:()=>_w,isMediaDevicesSupported:()=>iw,isMediaSessionSupported:()=>ww,isMediaStreamTrackProcessorSupported:()=>ow,isReplaceTrackSupported:()=>Rw,isScreenCaptureApiAvailable:()=>dw,isSelectedCandidatePair:()=>hw,isSetParametersSupported:()=>Cw,isSmallStreamAPISupported:()=>fw,isSmallStreamSupported:()=>gw,isStopTransceiverSupported:()=>Aw,isTRTCSupported:()=>lw,isUnifiedPlanDefault:()=>Tw,isUsedInHttpProtocol:()=>rw,isWebAudioSupported:()=>mw,isWebCodecSupported:()=>Ow,isWebCodecsSupported:()=>tw,isWebRTCSupported:()=>Dw,isWebTransportSupported:()=>Pw});var KO={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},YO={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(eO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(eO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:n}=e;return"failed to subscribe ".concat(i," ").concat(n," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:n,maxSizeInSecond:r}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(r," bytes"):n," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},zO=(e,t)=>t?"".concat(gN,"/").concat(e,"/").concat(t):"".concat(gN,"/").concat(e,"/index.html"),qO=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage.getItem(IN);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n}}return{}};function QO(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o="",s="",a="";tO(YO[t])?o=YO[t](i):nO(YO[t])&&(o=YO[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=qO();n?a="".concat(n.className,".html#").concat(n.fnName):l&&l[t]&&(tO(l[t])?a=l[t](i):nO(l[t])&&(a=l[t]));let d=o;return QD()&&(c&&c[t]&&(tO(c[t])?s=c[t](i):nO(c[t])&&(s=c[t])),s&&(d=r?"".concat(s,"\n请查看文档: ").concat(zO("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),r&&(d+=" \nRefer to: ".concat(zO("en",a),"\n")),d}var XO={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},$O=new Map([[Vb,["Firefox",Ub]],[jb,["Edg",Gb]],[Pk,["Chrome",xk]],[Vk,["Safari",Fk]],[qb,["TBS",Qb]],[Xb,["XWEB",$b]],[ik&&Db,["WeChat",nk]],[ak,["QQ(Win)",ck]],[ok,["QQ(Mobile)",sk]],[rk,["QQ(Mobile X5)",sk]],[lk,["QQ(Mac)",dk]],[uk,["QQ(iPad)",hk]],[Sk,["MI",Ik]],[vk,["HW",Ak]],[Rk,["Samsung",Ck]],[bk,["OPPO",kk]],[Nk,["VIVO",Dk]],[Bb,["EDGE",Hb]],[Jb,["SogouMobile",Kb]],[Yb,["Sogou",zb]]]);function ZO(){let e=$O.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var ew=function(){return!(Tk||Bb||jb&&Wb<80||Vb&&Fb<56)},tw=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},iw=function(){if(!navigator.mediaDevices)return rw()||jO.error(YO.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},nw=!1;function rw(){return"http:"===location.protocol&&!Kk&&(nw||jO.error(QO({key:KO.NOT_SUPPORTED_HTTP})),nw=!0,!0)}var ow=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},sw=function(){return sb(this,null,(function*(){if(XO.detail.isH264EncodeSupported||XO.detail.isVp8EncodeSupported)return{isH264EncodeSupported:XO.detail.isH264EncodeSupported,isVp8EncodeSupported:XO.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection,r=document.createElement(PN.CANVAS);r.getContext("2d");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),XO.detail.isH264EncodeSupported=t,XO.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:XO.detail.isH264EncodeSupported,isVp8EncodeSupported:XO.detail.isVp8EncodeSupported}}catch(oD){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},aw=function(){return sb(this,null,(function*(){if(XO.detail.isH264DecodeSupported&&XO.detail.isVp8DecodeSupported)return{isH264DecodeSupported:XO.detail.isH264DecodeSupported,isVp8DecodeSupported:XO.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection;return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(oD){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},cw=function(){return sb(this,null,(function*(){if(XO.result)return XO;let e=ew(),t=Dw(),i=tw(),n=iw(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield sw(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield aw();return XO.result=e&&t&&n&&(r||o)&&(s||a),XO.detail.isBrowserSupported=e,XO.detail.isWebRTCSupported=t,XO.detail.isWebCodecsSupported=i,XO.detail.isMediaDevicesSupported=n,XO.detail.isScreenShareSupported=dw(),XO.detail.isSmallStreamSupported=gw(),XO.detail.isH264EncodeSupported=r,XO.detail.isVp8EncodeSupported=o,XO.detail.isH264DecodeSupported=s,XO.detail.isVp8DecodeSupported=a,XO.result||jO.error("".concat(navigator.userAgent," ").concat(DO(XO.detail,!1))),XO}))},lw=function(){return XO.result},dw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},uw=(e,t,i)=>{"http:"===location.protocol&&!Kk&&(e[t]=()=>{throw new fb({code:_b.INVALID_OPERATION,message:YO.NOT_SUPPORTED_HTTP})})},hw=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(oO(e.selected)&&!e.selected)};function pw(){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 _w(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function mw(){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 fw(){return"captureStream"in HTMLCanvasElement.prototype}function gw(){return!(ik||wb||Lk&&Lk<63)&&!(!ew()||!fw())}var Tw=function(){if(iO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:uD}),e.addTransceiver(PN.AUDIO),t=!0}catch(oN){}return null==e||e.close(),t};function Ew(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Sw(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Iw(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function vw(){return 11!==jk&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var yw=!(!vw()||wk&&Lk<74);function Aw(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Rw(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Cw(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Sw()}var bw=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,kw=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Nw="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Ok()>=86,Dw=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function Ow(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return iO(window.AudioDecoder)||(e.AudioDecoder=!0),iO(window.AudioEncoder)||(e.AudioEncoder=!0),iO(window.VideoDecoder)||(e.VideoDecoder=!0),iO(window.VideoEncoder)||(e.VideoEncoder=!0),iO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function ww(){return"mediaSession"in navigator&&!iO(navigator.mediaSession.setActionHandler)}function Pw(){return!iO(window.WebTransport)}function Mw(){let e={browser:"".concat(zk.name,"/").concat(zk.version),os:Zk(),displayResolution:pw(),isScreenShareSupported:dw(),isWebRTCSupported:Dw(),isGetUserMediaSupported:_w(),isWebAudioSupported:mw(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:Ow(),isMediaSessionSupported:ww(),isWebTransportSupported:Pw()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var Lw=ib(ab(),1),xw=Symbol("instance"),Vw=Symbol("cacheResult"),Uw=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,Gw.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Fw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Bw=new Map;function Hw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Bw.get(n)||[];Bw.has(n)||Bw.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=Ww.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return n[Vw];n.state instanceof Uw&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;if(Array.isArray(e)?0==e.length?n.state instanceof Uw&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Fw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not in from config"))):e!==n.state&&(l=new Fw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=n.state,u=new Uw(d,t,s);Gw.call(n,u);let h=e=>{var r;return n[Vw]=e,u.aborted||(Gw.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Vw])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(Gw.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new Fw(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(_){p(_)}}}}var jw="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 Gw(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Ww.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Ww=class extends Lw.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Ww.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[xw];n?this.name=n.name+"-"+n.count++:i[xw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Bw.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);Bw.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=Ww.instances.get(e),t||Ww.instances.set(e,t=new Ww(e,void 0,Object.create(Ww.prototype)))):(t=Ww.instances2.get(e),t||Ww.instances2.set(e,t=new Ww(e.constructor.name,void 0,Object.create(Ww.prototype)))),t}static getState(e){var t;return null===(t=Ww.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};jw(Ww.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Gw.call(this,e)}};Ww.STATECHANGED="stateChanged",Ww.UPDATEAFSM="updateAFSM",Ww.INIT="[*]",Ww.ON="on",Ww.OFF="off",Ww.instances=new Map,Ww.instances2=new WeakMap;var Jw=(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)},Kw=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},Yw=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),zw=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MD,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=$C(e===PD?{delay:2e3,count:0,backgroundTask:!0}:e===OD?{delay:1e4,count:0}:e===wD?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),sO(t)&&(i=$C($C({},i),t)),tO(e)&&(t=e,e=MD);let n=$C({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")])));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=mO(),n=()=>{if(t=mO()-i,t>=e.delay&&(i=mO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=Jw(n,{timeout:e.delay})};return e.ricID=Jw(n,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=mO(),n=()=>document.hidden&&e.backgroundTask?(t=mO()-i,i=mO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=mO()-i,t>=e.delay&&(i=mO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=mO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&Yw(n),r&&Kw(r),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};zw.taskMap=new Map,zw.currentTaskID=1;var qw=zw;PN.SEI_MESSAGE;var Qw={LOADED_DATA:PN.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"},Xw=new class{constructor(){rb(this,"_roomIdMap",new Map),rb(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:nN,env:yN.QCLOUD,browserVersion:zk.name+zk.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r))}logSuccessEvent(e){Kk||!jO.isAbleToUpload||this._configs.env===yN.QCLOUD&&this.uploadEventToKibana(ZC($C({},e),{result:"success"}))}logFailedEvent(e){if(Kk||!jO.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:"failed",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||_b.UNKNOWN};this._configs.env===yN.QCLOUD&&this.uploadEventToKibana(ZC($C({},o),{error:n}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:n}=e,r={timestamp:Eb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:nN,log:t};n&&(r.errorInfo=n.message),this.sendRequest(FD(this._configs.sdkAppId,vN.LOG),r)}sendRequest(e,t){jO.isAbleToUpload?MO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},$w="trtc_autoplay",Zw="".concat($w,"_mask"),eP="".concat($w,"_wrapper"),tP="".concat($w,"_header"),iP="".concat($w,"_content"),nP="".concat($w,"_action_wrapper"),rP="".concat($w,"_question"),oP="".concat($w,"_collapse"),sP="".concat($w,"_action_confirm"),aP="".concat($w,"_detail"),cP="#2473E8",lP="dialog",dP="".concat(lP,"-show"),uP="".concat(lP,"-1"),hP="".concat(lP,"-2"),pP=!1,_P=()=>!!document.querySelector(".".concat(eP)),mP="".concat(gN,"/").concat(QD()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),fP="<br><a href='".concat(mP,"' target='_blank'>").concat(QD()?"其他方案?":"Any other solution?","</a>"),gP="".concat(QD()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(fP):"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(fP)),TP=class{constructor(){if(rb(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),rb(this,"_dialogNode",null),rb(this,"_bodyPosition",""),rb(this,"_showDetail",!1),rb(this,"_isCollapseClicked",!1),rb(this,"_isQuestionClicked",!1),QD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!pP){let e=document.createElement("style");e.innerHTML=".".concat(Zw,"{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(Zw," div:not(.").concat(nP,"){display:block !important;}.").concat(eP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(eP," a{color:").concat(cP,";}.").concat(tP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(iP,"{margin:8px 0;}.").concat(nP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(oP,"{margin-right:auto;cursor:pointer}.").concat(rP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(sP,"{margin-left:8px;color:#fff;background:").concat(cP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(sP,":hover{opacity:0.9;}.").concat(oP,",.").concat(sP,",.").concat(iP,",.").concat(rP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(eP,"{width:80vw;}}"),document.head.appendChild(e),pP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(Zw,"\"><div class='").concat(eP,"'><div class='").concat(tP,"'>").concat(location.host,"</div><div class='").concat(iP,"'>").concat(this.content,"</div><div class='").concat(aP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(gP,"</div><div class='").concat(nP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=sP,t.innerText=QD()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=rP,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=oP,n.innerText="".concat(QD()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(".".concat(nP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r}addDiaLog(){_P()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(eP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",jO.info("show autoplay dialog"),Xw.uploadEvent({log:dP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){jO.warn("confirm clicked, try resume stream"),UO.emit(BO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(aP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||Xw.uploadEvent({log:uP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(mP,"_blank"),this._isQuestionClicked||Xw.uploadEvent({log:hP}),this._isQuestionClicked=!0}},EP={};tb(EP,{create:()=>IP,remove:()=>vP});var SP=new WeakMap;function IP(e,t){SP.has(e)||SP.set(e,[]);let i=SP.get(e),n={add:(e,r)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n}function vP(e){let t=SP.get(e);t&&(t.forEach((e=>e())),SP.delete(e))}var yP=class extends Ww{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,rb(this,"id"),rb(this,"element",null),rb(this,"container",null),rb(this,"mediaStream",new MediaStream),rb(this,"track"),rb(this,"url"),rb(this,"attr"),rb(this,"muted"),rb(this,"_log"),rb(this,"_pausedRetryCount"),rb(this,"_isElementPlayingFired",!1),rb(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=yD,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Qw.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element))){let t=new MediaStream;t.addTrack(e),this.element.srcObject=t}}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))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return sb(this,null,(function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(oN){let t=QO({key:KO.PLAY_FAILED,data:{media:this.kind,error:oN}});if(this.track&&!this.track.muted&&this._log.warn(oN),t.includes("NotAllowedError"))throw new fb({code:_b.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(PN.ENDED),this._interval>0&&qw.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Wk?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,t){this.element&&(this.element.style.width="".concat(e,"px"),this.element.style.height="".concat(t,"px"))}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return IP(this.element,this.element).add(PN.PLAYING,e).add(PN.ENDED,e).add(PN.PAUSE,e).add(PN.ERROR,e).add(PN.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==EP||EP.create(this.track,this.track).add(PN.ENDED,e).add(PN.MUTE,e).add(PN.UNMUTE,e),this.track.readyState===PN.ENDED&&this.handleTrackEvent({type:PN.ENDED}),this.track.muted&&this.handleTrackEvent({type:PN.MUTE})}}bindAutoPlayEvent(){UO.on(BO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&vP(this.track)}unbindEvents(){this.element&&vP(this.element),this.unbindTrackEvents(),UO.off(BO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case PN.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(PN.PLAYING),this._interval&&(qw.clearTask(this._interval),this._interval=-1);break;case PN.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(PN.ENDED);break;case PN.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(PN.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=Ok();this._pausedRetryCount>0&&(this.kind===PN.VIDEO&&!_P()||this.kind===PN.AUDIO&&(rO(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),wb&&(this._interval=qw.run(MD,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case PN.ERROR:if(this.element&&this.element.error){let{code:e,message:t}=this.element.error;this._log.error("".concat(this.kind," player error observed. code: ").concat(e," message: ").concat(t," userAgent: ").concat(navigator.userAgent)),Xw.uploadEvent({log:"stat-".concat(this.kind,"-").concat(aD.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case PN.LOADEDDATA:this.kind===PN.VIDEO&&this.emit(Qw.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case PN.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(PN.ENDED);break;case PN.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(PN.MUTE);break;case PN.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(PN.UNMUTE)}}handlePlaying(e){this.emit(Qw.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Qw.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Qw.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};nb([Hw([],"PLAYING",{sync:!0})],yP.prototype,"handlePlaying",1),nb([Hw("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],yP.prototype,"handlePaused",1),nb([Hw([],"STOPPED",{sync:!0})],yP.prototype,"handleStopped",1);var AP=class extends yP{constructor(e){super(e,PN.VIDEO),rb(this,"viewMirror",!1),rb(this,"objectFit"),iO(e.viewMirror)||(this.viewMirror=e.viewMirror),iO(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(PN.VIDEO);if(this.track){let e=new MediaStream;e.addTrack(this.track),t.srcObject=e}t.muted=!0;let i="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");this.viewMirror&&(i+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents()}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(PN.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(PN.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.viewMirror&&this.element){let e=this.element.style.transform;t===PN.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):t===PN.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}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)}setViewMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit="".concat(e)),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){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}},RP=!1,CP=class{constructor(e){rb(this,"context_"),rb(this,"blob_"),this.context_=e.context,this.blob_=new Blob(['class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);'],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return sb(this,null,(function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),jO.info("worklet addModule success"),UO.emit(BO.WORKLET_LOADED_SUCCESS),RP=!0}catch(qM){jO.info("worklet addModule catch error. ".concat(qM.message)),UO.emit(BO.WORKLET_LOADED_FAILED)}}))}get initWorkletSuccess(){return RP}};"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var bP,kP,NP=0,DP=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new window.AudioContext($C({sampleRate:48e3},t)),n=++NP,r=()=>{"suspended"===i.state?(i.resume(),document.addEventListener("click",r)):"interrupted"===i.state?i.resume():document.removeEventListener("click",r)};return document.addEventListener("click",r),i.onstatechange=()=>{jO.info("".concat(e,"-").concat(n," context state: ").concat(i.state)),r()},i},OP=0,wP=class{constructor(e){rb(this,"_volume"),rb(this,"_log"),rb(this,"_track"),rb(this,"_stream"),rb(this,"_audioCtx"),rb(this,"_destination"),rb(this,"_streamSource"),rb(this,"_scriptProcessorNode"),rb(this,"_audioWorkletNode"),rb(this,"_interval");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,bP||(bP=DP("volume-meter")),this._audioCtx=bP,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,UO.on(BO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),pO?(UO.on(BO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),UO.on(BO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),OP+=1}preload(){kP?kP.initWorkletSuccess&&this.initAudioWorklet():kP=new CP({context:bP})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(qM){Xw.logFailedEvent({userId:this._log.userId,eventType:aD.LOAD_WORKLET,error:qM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let n=0;n<t.length;++n)i+=t[n]*t[n];this._volume=Math.sqrt(i/t.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(qM){this._log.error("volumeMeter init script processor error: ".concat(qM))}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,UO.off(BO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),UO.off(BO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),UO.off(BO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),OP>0&&(OP-=1),0===OP&&(null==bP||bP.close(),bP=null,kP=null)}resume(){null==bP||bP.resume()}setTrack(e){if(this._audioCtx&&this._audioWorkletNode){if(!e)return this._streamSource.disconnect();this._track=e,this._streamSource.disconnect(),this._streamSource=this._audioCtx.createMediaStreamSource(new MediaStream([e])),this._streamSource.connect(this._audioWorkletNode)}}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})}},PP=null,MP=0,LP=class extends yP{constructor(e){super(e,PN.AUDIO),rb(this,"_volumeMeter"),rb(this,"_gainedTrack",null),rb(this,"_gainNode",null),rb(this,"_destination",null),rb(this,"_mediaStreamSource",null),rb(this,"_sourceElement",null),rb(this,"_outputDeviceId"),rb(this,"_volume",1),rb(this,"_loop",!1),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter?this._volumeMeter.setTrack(e):e&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new wP({track:this._gainedTrack||e,log:this._log})}initializeElement(){if(("15.2"===Hk||"15.3"===Hk||"15.4"===Hk)&&this.muted)return void this._log.info("audioElement is muted.");let e=document.createElement(PN.AUDIO);this.track&&(e.srcObject=new MediaStream([this._gainedTrack||this.track])),e.muted=this.muted,e.setAttribute("id","audio_".concat(this.id)),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,this.bindElementEvents()}play(){return sb(this,null,(function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield ob(LP.prototype,this,"play").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),this.destroyGain(),super.stop()}resume(){return sb(this,null,(function*(){yield ob(LP.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return sb(this,null,(function*(){this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield this.element.setSinkId(e))}))}setVolume(e){this._volume=e,this._gainNode?this._gainNode.gain.value=e:e>1?this.createGain(e):this.element&&(this.element.volume=e)}createGain(e){if(!this.track)return;PP||(PP=DP("player")),this._log.info("create gainNode ".concat(e));let t=PP.createMediaStreamSource(new MediaStream([this.track])),i=PP.createGain(),n=PP.createMediaStreamDestination();t.connect(i),i.connect(n),i.gain.value=e,this._gainNode=i,this._destination=n,this._mediaStreamSource=t,this._gainedTrack=n.stream.getAudioTracks()[0],MP+=1,this.element&&(vP(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play()}destroyGain(){var e,t,i;!this._gainNode||(this._log.info("destroy gainNode"),null==(e=this._gainNode)||e.disconnect(),null==(t=this._destination)||t.disconnect(),null==(i=this._mediaStreamSource)||i.disconnect(),this._gainNode=null,this._destination=null,this._mediaStreamSource=null,this._sourceElement&&(this._sourceElement.srcObject=null,this._sourceElement=null),this._gainedTrack=null,0===(MP-=1)&&PP&&(this._log.info("destroy gain audioContext"),PP.close(),PP=null))}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return(null==(e=this._volumeMeter)?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return null==(e=this._volumeMeter)?void 0:e.getInternalAudioLevel()}},xP=class extends Ww{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,isInitPlayer:o=!0}=e;var s;super(),rb(this,"id",GO()),rb(this,"userId",""),rb(this,"isRemote"),rb(this,"mediaType"),rb(this,"room"),rb(this,"user"),rb(this,"_log"),rb(this,"_inputTrack"),rb(this,"_outputTrack"),rb(this,"isPlayCalled"),rb(this,"container",null),rb(this,"player"),rb(this,"subVideoPlayerMap"),rb(this,"muted",!1),rb(this,"playerMuted",!1),rb(this,"abortCtrl"),rb(this,"audioOutputDeviceId"),rb(this,"playbackVolume",1),rb(this,"objectFit","cover"),rb(this,"mirror",!1),rb(this,"isScreen",!1),rb(this,"manager"),iO(t)||(this.userId=t),this.mediaType=n,this._log=jO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=r||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}),o&&this.initPlayer()}get log(){return this._log||jO}get kind(){return 1===this.mediaType?PN.AUDIO:PN.VIDEO}get strMediaType(){return 4===this.mediaType?PN.VIDEO:2===this.mediaType?PN.SCREEN:PN.AUDIO}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}play(e,t){return sb(this,null,(function*(){let i=aO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!iO(t.muted)&&this.setPlayerMute(t.muted),t&&!iO(t.objectFit)&&(this.objectFit=t.objectFit),this.setMirror(null==t?void 0:t.mirror),void(this.kind===PN.VIDEO&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),aO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!iO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===PN.VIDEO)&&this.setPlayerMute(!0),t&&!iO(t.objectFit)&&(this.objectFit=t.objectFit),this.setMirror(null==t?void 0:t.mirror),this.kind===PN.VIDEO&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),UO.emit(BO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this._outputTrack),yield this.player.play(),aO(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==PN.VIDEO||iO(e)&&this.isRemote)return;this.mirror=iO(e)?"view":e;let i=this.player;if(t&&(i=t),oO(this.mirror))return i.setViewMirror(this.mirror),void(this.room&&(this.room.videoManager.mirror=!1));switch(this.mirror){case"view":this.room&&(this.room.videoManager.mirror=!1),i.setViewMirror(!0);break;case"publish":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!0);break;case"both":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return sb(this,null,(function*(){if(!this._outputTrack||this.kind===PN.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var n;e.find((e=>i===e))||(t.stop(),t.setContainer(null),null==(n=this.subVideoPlayerMap)||n.delete(i))}));for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(iO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new AP({id:this.userId||this.id,track:this.outMediaTrack,container:r,muted:this.playerMuted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)this.setMirror(null==t?void 0:t.mirror,e),yield e.play()}))}initPlayer(){this.log.info("create player"),this.kind===PN.AUDIO?this.player=new LP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new AP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,log:this.log}),this.player.on(Qw.LOADED_DATA,(()=>{UO.emit(BO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(Qw.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(Qw.PLAYER_STATE_CHANGED,(e=>{UO.emit(BO.PLAYER_STATE_CHANGED,$C({track:this},e)),this.emit("player-state-changed",e)}))}setAudioOutput(e){return sb(this,null,(function*(){var t;this.audioOutputDeviceId=e,yield null==(t=this.player)?void 0:t.setSinkId(e)}))}setAudioVolume(e){var t;this.playbackVolume=e,this.log.info("setAudioVolume to ".concat(e)),null==(t=this.player)||t.setVolume(e)}getAudioLevel(){var e;return(null==(e=this.player)?void 0:e.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.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop(),e.setContainer(null)})),this.container=null)}resume(){return sb(this,null,(function*(){var e;!this.isPlayCalled||(yield null==(e=this.player)?void 0:e.resume())}))}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){return this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),UO.emit(e?BO.TRACK_MUTED:BO.TRACK_UNMUTED,{track:this}),!0}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}setInputMediaStreamTrack(e){let t=this._inputTrack;if(e!==t)return this._inputTrack=e,e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||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,e.enabled=!this.muted,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.outMediaTrack),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 TP;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};nb([Hw([],Ww.INIT,{sync:!0})],xP.prototype,"close",1);var VP=Object.prototype.hasOwnProperty;var UP=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(XD(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(VP.call(e,t))return!1;return!0}return!1},FP=ib(ab(),1),BP=e=>t=>t.deviceId===e,HP=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";rb(this,"kind"),rb(this,"type"),rb(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter((e=>e.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase())));1===this.devices.length&&WP(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(BP(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");jO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(BP(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");jO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},jP=class extends FP.EventEmitter{constructor(){super(),rb(this,"audioInputs",new HP(PN.AUDIO)),rb(this,"videoInputs",new HP(PN.VIDEO)),rb(this,"audioOutputs",new HP(PN.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||qw.run(PD,(()=>{this.update()}),{delay:1e4}))}init(){JP().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield JP(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},GP=lN||cN?null:new jP;function WP(e){return e.deviceId===e.groupId&&""===e.groupId}function JP(){return sb(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(rw()||!iw())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{WP(e)&&(e.kind===PN.AUDIO_INPUT?i.audio=!0:e.kind===PN.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e=yield navigator.mediaDevices.getUserMedia(i);t=yield navigator.mediaDevices.enumerateDevices(),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&&qP.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function KP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return GP.update(e?1:0).then((e=>e.audioInputs.devices))}function YP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return GP.update(e?2:0).then((e=>e.videoInputs.devices))}function zP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return sb(this,null,(function*(){return GP.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var qP=new Set;function QP(e,t){return sb(this,null,(function*(){let i=(yield KP()).find((e=>e.deviceId===AD));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var XP=xO({retryFunction:function(e){return sb(this,null,(function*(){let t=function(e){return{audio:ZP(e),video:eM(e)}}(e);jO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],n=[],r=["label","deviceId"];t.audio&&(i=yield KP(),jO.info("microphones: ".concat(NO(i,{keysToInclude:r})))),t.video&&(n=yield YP(),jO.info("cameras: ".concat(NO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return kw&&e.getTracks().forEach((e=>{jO.info("".concat(e.kind," capabilities: ").concat(NO(e.getCapabilities(),{keysToInclude:LD})))})),e}catch(o){if("NotFoundError"===o.name){if(e.video&&n&&0===n.length)throw new fb({code:_b.DEVICE_NOT_FOUND,message:QO({key:KO.CAMERA_NOT_FOUND})});if(e.audio&&i&&0===i.length)throw new fb({code:_b.DEVICE_NOT_FOUND,message:QO({key:KO.MICROPHONE_NOT_FOUND})})}throw new fb({code:_b.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)):2===s?r[0].useDeviceIdOnly=!0:3===s&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&$P(r[0].microphoneId,!1),r[0].cameraId&&$P(r[0].cameraId,!0)},onRetrying:e=>{jO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{Xw.logFailedEvent({eventType:aD.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{Xw.logSuccessEvent({eventType:aD.GET_USER_MEDIA_RETRY}),Xw.uploadEvent({log:"stat-".concat(aD.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function $P(e,t){return sb(this,null,(function*(){let i=(t?yield YP():yield KP()).find((t=>t.deviceId===e));i&&tO(i.getCapabilities)&&jO.warn(NO(i.getCapabilities(),{keysToInclude:LD}))}))}function ZP(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!UP(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(rO(e.channelCount)&&(t.channelCount=e.channelCount),oO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),oO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),oO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!UP(t)||t)}function eM(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&&!UP(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Vb&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Vb&&(i.height.max=e.height)),Vb&&_k&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!UP(i)||i)}var tM=XP;function iM(e){return rM(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return yield e.apply(this,n),t.apply(this,n)}))}))}function nM(e){return rM(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return sb(this,null,(function*(){return e.call(this,t.apply(this,n))}))}))}function rM(e){return function(t,i,n){return n.value=e(n.value,i),n}}var oM=new WeakMap,sM=new WeakMap;function aM(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(oM.has(this)){let o=oM.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i})}else oM.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=oM.get(this);e&&(e.shift(),e[0]&&r($C({},e[0])))}))},i}}function cM(e){return function(t,i,n){let r=n.value,o=t=>rO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally((()=>{if(sM.has(n)&&sM.get(n).has(o(i))){let e=sM.get(n).get(o(i));e&&(e.shift(),e[0]&&s($C({},e[0])))}}))};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(sM.has(this))if(sM.get(this).has(o(t))){let n=sM.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i})}}else sM.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});else{let n=new Map;n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),sM.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i})}}))},n}}var lM=class extends xP{constructor(e){super({mediaType:e,isInitPlayer:!(arguments.length>1&&void 0!==arguments[1])||arguments[1]}),rb(this,"isRemote",!1),rb(this,"deviceId"),rb(this,"groupId",""),rb(this,"label",""),rb(this,"_isRecapturing",!1),rb(this,"_lastRecaptureTime",0),rb(this,"_onMuteTimeoutId",-1),rb(this,"profile"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return"publish"===this.state}installTrackEvent(e){IP(e,e).add(PN.MUTE,this.onTrackMuted).add(PN.UNMUTE,this.onTrackUnmuted).add(PN.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===PN.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){vP(e)}setStateToCapture(){}capture(e){return sb(this,null,(function*(){var t;try{let i;UO.emit(BO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield tM(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),UO.emit(BO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),i}catch(sN){throw UO.emit(BO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:sN}),this.log.error("getUserMedia error observed ".concat(sN)),sN}}))}setInputMediaStreamTrack(e){this.state===Ww.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}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),UO.emit(BO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return sb(this,null,(function*(){if(this.mediaTrack&&bw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return sb(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==PN.AUDIO||t!==AD||(yield QP(n,r)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),JP().then((t=>{let i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}))}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===PN.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(PN.AUDIO_INPUT);return!!qP.has(i)}(this.mediaTrack)||this.kind===PN.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;let t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let i="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(PN.VIDEO_INPUT);return!!qP.has(i)}(this.mediaTrack)||this._isRecapturing||e&&_k&&Vk)}onTrackMuted(){if(wO(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<DD)return void setTimeout((()=>this.onTrackMuted()),DD);this._onMuteTimeoutId=setTimeout((()=>sb(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return sb(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<DD)return void setTimeout((()=>this.onTrackEnded()),DD);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return sb(this,null,(function*(){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?yield KP():yield YP()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})})).catch((e=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(e.message)),this.emit("5",e)}))}))}getRecoverCaptureDeviceId(){return sb(this,null,(function*(){let e=this instanceof 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 n=e?(yield YP()).find((e=>!dM.has(e.deviceId))):(yield KP()).find((e=>!dM.has(e.deviceId)));n&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(n.deviceId)),t=n.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};nb([Hw(Ww.INIT,"capture",{ignoreError:!0,sync:!0})],lM.prototype,"setStateToCapture",1),nb([aM()],lM.prototype,"capture",1),nb([Hw("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),UO.emit(BO.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===_b.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],lM.prototype,"publish",1),nb([rM((e=>function(){return sb(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),2===this.mediaType&&(this.mediaType=4)}))})),Hw([],"capture",{sync:!0})],lM.prototype,"unpublish",1);var dM=new Map;UO.on(BO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&dM.delete(e.track.deviceId)}));var uM=class extends lM{constructor(e){super(1),rb(this,"mediaType",1),rb(this,"volume",0),rb(this,"captureVolume",1),rb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),rb(this,"playerMuted",!0),this.manager=e}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:n=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:n,customSource:i})}switchDevice(e){return sb(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==AD)return;if(yield QP(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)),UO.emit(BO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(oD){throw this.log.error("switch microphone failed ".concat(oD)),this.deviceId&&this.recapture(this.deviceId),oD}}}))}listenDeviceChange(){GP&&!GP.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&GP.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield KP();t[0]?this.recapture(t[0].deviceId):GP.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return sb(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!iO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!iO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!iO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}setCaptureVolume(e){var t;let i=e/100;i!==this.captureVolume&&(null==(t=this.manager)||t.setCaptureVolume(i),this.captureVolume=i)}unpublish(){var e;return null==(e=this.manager)||e.removeAudioTrack(this),super.unpublish()}close(){GP.off("audioInputAdded",this.handleMicrophoneAdded,this),GP.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}},hM=class extends lM{constructor(e){super(4),rb(this,"mediaType",4),rb(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),rb(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),rb(this,"small"),rb(this,"isNeedToSetBandwidth"),this.manager=e;let t=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(ZC($C({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t)}get facingMode(){if(bw&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:n=!1,customSource:r}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,customSource:r})}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}setProfile(e){!e||(e.width*e.height<=19200&&Pb&&wk&&(this.log.warn("resolution is ".concat(e.width,"*").concat(e.height,", fallback to 240*180")),e.width>e.height?(e.width=240,e.height=180):(e.width=180,e.height=240),e.bitrate=Math.max(e.bitrate,150)),e.bitrate&&(this.isNeedToSetBandwidth=e.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(e):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(ZC($C({},this.profile),{width:1920,height:1080}))))}applyProfile(){var e;if(!this.mediaTrack)return;let t=this.settings;return t.height!==this.profile.height||t.width!==this.profile.width||t.frameRate!==this.profile.frameRate?null==(e=this.mediaTrack)?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then((()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:PN.VIDEO,videoType:PN.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return bw&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:PO()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return sb(this,null,(function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),UO.emit(BO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(oD){throw this.log.error("switch camera failed ".concat(oD)),this.deviceId&&this.recapture(this.deviceId),oD}}))}listenDeviceChange(){GP&&!GP.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&GP.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return sb(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield YP();t[0]?this.recapture(t[0].deviceId):GP.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return sb(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){GP.off("videoInputAdded",this.handleCameraAdded,this),GP.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}};var pM=function(e){return sb(this,null,(function*(){let t=null,i=function(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Vk?{max:e.width}:{ideal:e.width,max:e.width},height:Vk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3}}return t}(e);jO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===n.getAudioTracks().length&&(Pk&&Lk<74||Vk||Vb)&&jO.warn("Your browser not support capture system audio"),e.frameRate&&n.getVideoTracks()[0]&&n.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height}).catch((e=>{jO.warn("screen applyConstraints failed: ".concat(e))})),e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return iO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);jO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0])}return n}))},_M=class extends hM{constructor(e){super(e),rb(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),rb(this,"objectFit","contain"),rb(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return sb(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:n,echoCancellation:r,noiseSuppression:o,audioTrack:s,videoTrack:a}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield pM({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:n,echoCancellation:r,noiseSuppression:o}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof fb?e:new fb({code:_b.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return sb(this,null,(function*(){throw new Error("Method not implemented.")}))}},mM=class extends uM{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},fM=class extends uM{constructor(e){super(e),rb(this,"_inputs",new Map),rb(this,"_destination"),rb(this,"audioContext",DP("audio-mixer")),this._log.id="m-".concat(this._log.id),"running"!==this.audioContext.state&&this._log.warn("audio mixer context state: ".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1}addTrack(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._inputTrack=e;let i=this.audioContext.createMediaStreamSource(new MediaStream([t?e.clone():e]));this._inputs.set(e,{sourceNode:i,clone:t}),i.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture())}setTrackCaptureVolume(e,t){if(!this._inputs.has(e)||!this._destination)return;let i=this._inputs.get(e),{sourceNode:n}=i;i.gainNode||(this._log.info("create GainNode"),i.gainNode=this.audioContext.createGain()),i.gainNode.gain.value=t,n.disconnect(),n.connect(i.gainNode).connect(this._destination)}publish(e,t){return this.room=e,t}unpublish(){delete this.room}replaceTrack(e,t){var i;if(!this.hasMix)return;let n=1;if(t){let r=this._inputs.get(t);r&&(r.sourceNode.disconnect(),r.gainNode&&(n=r.gainNode.gain.value,null==(i=r.gainNode)||i.disconnect()),this._inputs.delete(t),this.addTrack(e.outMediaTrack,r.clone),1!==n&&this.setTrackCaptureVolume(e.outMediaTrack,n))}}removeTrack(e){let t=this._inputs.get(e);!t||(t.sourceNode.disconnect(),this._inputs.delete(e),this._inputTrack===e&&delete this._inputTrack,0===this._inputs.size&&(delete this._outputTrack,this.unpublish(),this.close()))}close(){this.stop(),this.audioContext.close()}get hasMix(){return!!this._outputTrack}set channelCount(e){this._destination.channelCount=e}};nb([Hw("capture","publish",{ignoreError:!0})],fM.prototype,"publish",1),nb([Hw([],"capture",{sync:!0})],fM.prototype,"unpublish",1);var gM=class extends lM{constructor(e,t){super(1),rb(this,"musicId"),rb(this,"mediaType",1),rb(this,"volume",0),rb(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),rb(this,"playerMuted",!1),rb(this,"audio"),rb(this,"_audioContext"),rb(this,"_destination"),rb(this,"_source",null),this.manager=e,this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.audio=document.createElement("audio"),this.audio.src=t.url,this.audio.crossOrigin="anonymous",oO(t.loop)&&this.loop(t.loop),rO(t.volume)&&this.setVolume(t.volume),t.id&&(this.musicId=t.id),this._source=this._audioContext.createMediaElementSource(this.audio),this._source.connect(this._destination),this.setInputMediaStreamTrack(this._destination.stream.getAudioTracks()[0]),this.installPlayerEvent()}play(){return sb(this,null,(function*(){try{yield this.audio.play(),yield ob(gM.prototype,this,"play").call(this,null,{muted:!1}),this._log.info("music ".concat(this.musicId," play success"))}catch(oN){this._log.error("music ".concat(this.musicId," play error"),oN)}}))}installPlayerEvent(){this.audio.addEventListener("error",this.handleAudioError.bind(this))}uninstallPlayerEvent(){this.audio.removeEventListener("error",this.handleAudioError.bind(this))}handleAudioError(e){this._log.warn("local music ".concat(this.musicId," audio error"),e)}initAudioContext(){this._audioContext=DP("music"),"running"!==this._audioContext.state&&this._log.warn("local music ".concat(this.musicId," context state: ").concat(this._audioContext.state))}destroy(){var e,t;null==(e=this._source)||e.disconnect(),null==(t=this._destination)||t.disconnect(),this.uninstallPlayerEvent(),this.player.stop(),this._audioContext.close().then((()=>{this._source=null,this._destination=null,this._audioContext=null}))}getStream(){var e;return(null==(e=this._destination)?void 0:e.stream)||null}seek(e){e<0&&e>this.duration()?this._log.warn("Time beyond song duration."):this.audio.currentTime=e}getPosition(){return this.audio.currentTime||0}setVolume(e){e>1&&e<0?this.log.warn("volume is out of range"):this.audio.volume=e}getVolume(){return this.audio.volume||0}setPlayBackRate(e){e>8&&e<0?this.log.warn("rate is out of range"):this.audio.playbackRate=e}getPlayBackRate(){return this.audio.playbackRate||0}duration(){return this.audio.duration||0}loop(e){return this.audio&&oO(e)&&(this.audio.loop=e),this.audio.loop||!1}setOperation(e){"pause"===e&&this.audio.pause(),"resume"===e&&(this.audio.pause(),this.audio.play()),"stop"===e&&(this.audio.pause(),this.seek(0))}listenDeviceChange(){}},TM="input",EM="output",SM={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var IM=e=>(e=Number(e))>0&&e<14e8;function vM(e){return sb(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e="https://".concat(function(e){let t;return t=IM(e)?SM.MAIN_OVERSEA:SM.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(n,"×tamp=").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}var yM=ib(ab(),1);function AM(e,t){t=t||{};let i,n=e.numberOfChannels,{sampleRate:r}=e,o=t.float32?3:1,s=3===o?32:16;return i=2===n?function(e,t){let i=e.length+t.length,n=new Float32Array(i),r=0,o=0;for(;r<i;)n[r++]=e[o],n[r++]=t[o],o++;return n}(e.getChannelData(0),e.getChannelData(1)):e.getChannelData(0),function(e,t,i,n,r){let o=r/8,s=n*o,a=new ArrayBuffer(44+e.length*o),c=new DataView(a);return RM(c,0,"RIFF"),c.setUint32(4,36+e.length*o,!0),RM(c,8,"WAVE"),RM(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,t,!0),c.setUint16(22,n,!0),c.setUint32(24,i,!0),c.setUint32(28,i*s,!0),c.setUint16(32,s,!0),c.setUint16(34,r,!0),RM(c,36,"data"),c.setUint32(40,e.length*o,!0),1===t?function(e,t,i){for(let n=0;n<i.length;n++,t+=2){let r=Math.max(-1,Math.min(1,i[n]));e.setInt16(t,r<0?32768*r:32767*r,!0)}}(c,44,e):function(e,t,i){for(let n=0;n<i.length;n++,t+=4)e.setFloat32(t,i[n],!0)}(c,44,e),a}(i,o,r,n,s)}function RM(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}var CM,bM=class{constructor(e){rb(this,"audioContext_"),rb(this,"inputPCM_",new Float32Array),rb(this,"outputPCM_",new Float32Array),this.audioContext_=e}onDump(e,t){if(t===TM){let t=this.inputPCM_.length,i=new Float32Array(t+e[0].length);i.set(this.inputPCM_),i.set(e[0],t),this.inputPCM_=i}if(t===EM){let t=this.outputPCM_.length,i=new Float32Array(t+e[0].length);i.set(this.outputPCM_),i.set(e[0],t),this.outputPCM_=i}}getBlob(e){let t=e===TM?this.inputPCM_:this.outputPCM_,i=this.audioContext_.createBuffer(2,t.length,48e3);i.copyToChannel(t,0,0),i.copyToChannel(t,1,0);let n=AM(i);return i=null,new window.Blob([new DataView(n)],{type:"audio/wav"})}reset(){this.inputPCM_=new Float32Array,this.outputPCM_=new Float32Array}destroy(){this.reset()}},kM=class{constructor(e){let{sdkAppId:t,userId:i,audioContext:n,sign:r,status:o,worklet:s,timestamp:a,logger:c}=e;rb(this,"audioContext_"),rb(this,"destination_"),rb(this,"gainNode_"),rb(this,"log_"),rb(this,"workletNode_"),rb(this,"isDumping_",!1),rb(this,"dump_"),rb(this,"audioTrack_"),rb(this,"source_"),rb(this,"denoiserTrack_"),rb(this,"enableDenoise_",!0),rb(this,"emitter_",new yM.default),this.audioContext_=n,this.destination_=this.audioContext_.createMediaStreamDestination(),this.gainNode_=this.audioContext_.createGain(),this.gainNode_.gain.value=1.1,this.log_=c,this.workletNode_=s,this.workletNode_.connect(this.gainNode_).connect(this.destination_),this.workletNode_.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:i,timestamp:a,sign:r,status:o}}),this.workletNode_.port.onmessage=e=>{let{type:t,data:i}=e.data;if("ondump"===t&&this.isDumping_){let{inputPCM:e,outputPCM:t}=i;this.dump_.onDump(e,TM),this.dump_.onDump(t,EM)}"dumped"===t&&this.dumped()},this.dump_=new bM(this.audioContext_)}dumped(){this.isDumping_=!1;let e=this.dump_.getBlob(TM),t=this.dump_.getBlob(EM);this.emitter_.emit("ondumpend",{blob:e,name:TM}),this.emitter_.emit("ondumpend",{blob:t,name:EM}),this.dumpedWAV(e,TM),this.dumpedWAV(t,EM),this.dump_.reset()}dumpedWAV(e,t){let i=window.URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download="".concat(t,"-").concat(Date.now(),".wav"),n.click(),window.URL.revokeObjectURL(i),n.href=""}process(e){return sb(this,null,(function*(){if(this.audioTrack_=e,!this.audioTrack_)throw new Error("RTCAIDenoiser: cannot process without audioTrack.");let t=new MediaStream;t.addTrack(this.audioTrack_),this.source_=this.audioContext_.createMediaStreamSource(t),yield this.source_.connect(this.workletNode_),yield this.enableTrackANS(this.audioTrack_,!1);let i=this.destination_.stream;return this.denoiserTrack_=i.getAudioTracks()[0],this.log_.info("RTCAIDenoiser: denoiser process track ID: ".concat(e.id," success.")),this.denoiserTrack_}))}updateTrack(e){return sb(this,null,(function*(){var t;let i=new MediaStream;yield i.addTrack(e);let n=this.audioContext_.createMediaStreamSource(i);this.source_.disconnect(),n.connect(this.workletNode_),null==(t=this.audioTrack_)||t.stop(),this.audioTrack_=e,this.source_=n,this.log_.info("RTCAIDenoiser: updateTrack success.")}))}disable(){return sb(this,null,(function*(){var e;return this.enableDenoise_=!1,null==(e=this.workletNode_)||e.port.postMessage({type:"disable"}),this.audioTrack_&&(yield this.enableTrackANS(this.audioTrack_,!0)),this.log_.info("RTCAIDenoiser: disable ai denoiser."),this.enableDenoise_}))}enable(){return sb(this,null,(function*(){var e;return this.enableDenoise_=!0,null==(e=this.workletNode_)||e.port.postMessage({type:"enable"}),this.audioTrack_&&(yield this.enableTrackANS(this.audioTrack_,!1)),this.log_.info("RTCAIDenoiser: enable ai denoiser."),this.enableDenoise_}))}enableTrackANS(e,t){let i=e.getConstraints();return i.noiseSuppression=t,e.applyConstraints(i).catch((e=>this.log_.warn("".concat(t?"enable":"disable"," ANS failed "),e)))}startDump(){return this.isDumping_?(this.log_.info("RTCAIDenoiser: data is currently being dumped."),!1):(this.workletNode_.port.postMessage({type:"startDump"}),this.dump_?this.dump_.reset():this.dump_=new bM(this.audioContext_),this.isDumping_=!0,this.log_.info("RTCAIDenoiser: start dump data."),!0)}stopDump(){!this.isDumping_||(this.workletNode_.port.postMessage({type:"stopDump"}),this.isDumping_=!1,this.log_.info("RTCAIDenoiser: stop dump data."))}getAudioTrack(){return this.audioTrack_}getDenoiserTrack(){return this.destination_.stream.getAudioTracks()[0]}get enabled(){return this.enableDenoise_}destroy(){var e,t,i,n,r,o;this.log_.info("RTCAIDenoiser: destroy processor."),null==(e=this.audioTrack_)||e.stop(),null==(t=this.workletNode_)||t.port.postMessage({type:"destroy"}),this.workletNode_.port.onmessage=null,null==(i=this.source_)||i.disconnect(),null==(n=this.destination_)||n.disconnect(),null==(r=this.workletNode_)||r.disconnect(),null==(o=this.dump_)||o.destroy(),this.emitter_.removeAllListeners()}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}},NM=class{constructor(e){let{assetsPath:t,log:i,audioContext:n}=e;this.isLoaded_=!1,this.audioContext_=n,this.log_=i,this.assetsPath_=t}createProcessor(e){return sb(this,null,(function*(){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield vM(ZC($C({},e),{timestamp:t}));if(!i)throw this.log_.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new Error(o);try{yield this.load()}catch(c){throw new Error("Init wasm failed, please check your assetsPath.")}let s=yield this.initWorklet(),a=new kM(ZC($C({},e),{audioContext:this.audioContext_,timestamp:t,sign:n,status:r,worklet:s,logger:this.log_}));return this.log_.info("RTCAIDenoiser: ".concat(e.userId," create denoiser processor success.")),a}))}load(){return sb(this,null,(function*(){if(!this.isLoaded_)try{yield this.audioContext_.audioWorklet.addModule("".concat(this.assetsPath_,"/denoiser-wasm.js")),this.isLoaded_=!0}catch(qM){throw this.log_.error("Init assets from ".concat(this.assetsPath_," failed! Reason: ").concat(qM)),qM}}))}initWorklet(){return sb(this,null,(function*(){try{return new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}catch(qM){return yield this.load(),new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}}))}destroy(){var e;null==(e=this.audioContext_)||e.close()}isSupported(){return"AudioWorklet"in window&&"WebAssembly"in window}};var DM=class{constructor(e){let{room:t}=e;rb(this,"_localAudioTrack",null),rb(this,"_localScreenAudioTrack",null),rb(this,"localMixAudioTrack"),rb(this,"isDenoiserInit",!1),rb(this,"isDenoiserEnabled",!1),rb(this,"isDenoiserProcessed",!1),rb(this,"mixedMusicMap",new Map),rb(this,"cacheMusicMap",new Map),rb(this,"_log"),rb(this,"denoiserTrack",null),rb(this,"denoiser",null),rb(this,"denoiserProcessor"),rb(this,"initProcessorOptions"),rb(this,"denoiserContext"),this._log=jO.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId})}get mixedAudioTrack(){var e,t,i,n,r,o;if(bw&&(this._localAudioTrack||this.localMixAudioTrack)){let s=null==(t=null==(e=this._localAudioTrack)?void 0:e.mediaTrack)?void 0:t.getSettings(),a=null==(n=null==(i=this._localAudioTrack)?void 0:i.outMediaTrack)?void 0:n.getSettings(),c=null==(o=null==(r=this.localMixAudioTrack)?void 0:r.outMediaTrack)?void 0:o.getSettings();this._log.info("local audio track input sampleRate: ".concat(null==s?void 0:s.sampleRate," output sampleRate: ").concat(null==a?void 0:a.sampleRate," audio mixer sampleRate: ").concat(null==c?void 0:c.sampleRate))}return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null}dump(e){var t,i,n,r,o,s;if(!this._localAudioTrack)return;let a=[],c=[];null!=(t=this._localAudioTrack)&&t.mediaTrack&&(a.push(null==(i=this._localAudioTrack)?void 0:i.mediaTrack),c.push("mic")),null!=(n=this._localAudioTrack)&&n.outMediaTrack&&(a.push(null==(r=this._localAudioTrack)?void 0:r.outMediaTrack),c.push("mic-processed")),null!=(o=this.localMixAudioTrack)&&o.outMediaTrack&&(a.push(this.localMixAudioTrack.outMediaTrack),c.push("mix")),this._log.info("dump audio track ".concat(c,", duration: ").concat(e));let l=new AbortController,d=[],u=setTimeout((()=>{this._log.info('dump audio track complete please input "download()" to download.'),l.abort("timeout")}),1e3*e),h=()=>{for(let e=0;e<c.length;e++){let t=URL.createObjectURL(new Blob(d[e])),i=document.createElement("a");i.href=t,i.download="".concat(c[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(u),l.abort("download")},p=function(e,t){return sb(this,null,(function*(){CM||(CM=e.audioWorklet.addModule(URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return 1;}});"],{type:"application/javascript"})))),yield CM;let i=new AudioWorkletNode(e,"dumper",{numberOfInputs:t.length,numberOfOutputs:0}),n=t.map((t=>e.createMediaStreamSource(new MediaStream([t.clone()]))));return t.forEach(((e,t)=>{n[t].connect(i,0,t)})),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){n.forEach((e=>e.disconnect())),i.port.close()}})}))}((null==(s=this.localMixAudioTrack)?void 0:s.audioContext)||DP("dump"),a).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>d[t]=d[t]?d[t].concat(e[0]):[e[0]]))}}),l).catch((e=>h))));return{then:p.then.bind(p),download:h}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){var t,i,n;if(e instanceof mM)return this._localScreenAudioTrack=e,e.setOutputMediaStreamTrack(e.mediaTrack);let r=e.outMediaTrack||void 0;return e instanceof gM?(e.setOutputMediaStreamTrack(e.mediaTrack),void(null==(t=this.localMixAudioTrack)||t.replaceTrack(e,r))):e instanceof uM?(this._localAudioTrack=e,void(this.isDenoiserProcessed?(null==(i=this.denoiserProcessor)||i.updateTrack(e.mediaTrack),e.setOutputMediaStreamTrack(this.denoiserTrack)):(e.setOutputMediaStreamTrack(e.mediaTrack),null==(n=this.localMixAudioTrack)||n.replaceTrack(e,r)))):e instanceof PM?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){if(e instanceof uM)return this.removeAudioTrack(e)}addMusicSource(e){return sb(this,null,(function*(){this._log.info("add music source, id: ".concat(e.id," url: ").concat(e.url));let t,{id:i,url:n,loop:r,volume:o}=e;if(!this.mixedMusicMap.has(i))return this.cacheMusicMap.has(i)?(t=this.cacheMusicMap.get(i),t.audio.currentTime=0):t=new gM(this,e),t.play(),this._log.info("start mix audio ".concat(i," success.")),this.mixedMusicMap.set(i,t),this.cacheMusicMap.set(i,t),t}))}updateMusicSource(e){return sb(this,null,(function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;if(this._log.info("update music source, ".concat(JSON.stringify(e))),this.mixedMusicMap.has(t)){let e=this.mixedMusicMap.get(t);iO(i)||e.setVolume(i),iO(n)||e.loop(n),iO(r)||e.setOperation(r),iO(o)||e.seek(o)}}))}addAudioTrack(e){return sb(this,null,(function*(){var t;if(this.localMixAudioTrack||(this.localMixAudioTrack=new fM(this)),this._log.info("start add audioTrack, userId: ".concat(e.userId)),e===this._localAudioTrack){if(bw){let i=null==(t=e.mediaTrack)?void 0:t.getSettings();this.localMixAudioTrack.channelCount=(null==i?void 0:i.channelCount)||1}this.mixedMusicMap.forEach((e=>{var t;null==(t=this.localMixAudioTrack)||t.addTrack(e.outMediaTrack)}))}this.localMixAudioTrack.addTrack(e.outMediaTrack,Hk.startsWith("14.5")),this._localAudioTrack&&1!==this._localAudioTrack.captureVolume&&this.setCaptureVolume(this._localAudioTrack.captureVolume)}))}removeAudioTrack(e){e===this._localAudioTrack&&(this.localMixAudioTrack&&this.mixedMusicMap.forEach((e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack)})),this._localAudioTrack=null),this.localMixAudioTrack&&(this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.localMixAudioTrack.hasMix||delete this.localMixAudioTrack)}removeMusicSource(e){let{id:t}=e;if(this.mixedMusicMap.has(t)){this._log.info("remove music source, music id: ".concat(t));let e=this.mixedMusicMap.get(t);e.stop(),this.mixedMusicMap.delete(t),this.localMixAudioTrack&&this.localMixAudioTrack.removeTrack(e.outMediaTrack)}"*"===t&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{this.removeMusicSource({id:t})}))}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach((e=>e.stop()))}initDenoiser(e){return sb(this,null,(function*(){let{assetsPath:t,sdkAppId:i,userId:n,userSig:r}=e;try{(!this.denoiserContext||"closed"===this.denoiserContext.state)&&(this.denoiserContext=DP("denoiser")),this.denoiser||(this.denoiser=new NM({assetsPath:t,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:i,userId:n,userSig:r})),this.isDenoiserInit=!0,this.initProcessorOptions=e}catch(aN){throw aN}}))}enableDenoiser(e){return sb(this,null,(function*(){var e,t,i,n;if(this.isDenoiserEnabled=!0,this.hasAudioTrack)if(this.isDenoiserProcessed)null==(n=this.denoiserProcessor)||n.enable();else{let n=null==(e=this._localAudioTrack)?void 0:e.mediaTrack;if(!n)return;this.denoiserProcessor||(yield this.initDenoiser(this.initProcessorOptions)),this.denoiserTrack=yield this.denoiserProcessor.process(n),this.isDenoiserProcessed=!0,null==(t=this._localAudioTrack)||t.setOutputMediaStreamTrack(this.denoiserTrack),null==(i=this.localMixAudioTrack)||i.replaceTrack(this._localAudioTrack,n)}}))}disableDenoiser(){return sb(this,null,(function*(){var e;this.isDenoiserEnabled&&(null==(e=this.denoiserProcessor)||e.disable(),this.isDenoiserEnabled=!1)}))}setCaptureVolume(e){var t;this.localMixAudioTrack&&this._localAudioTrack&&this._localAudioTrack.outMediaTrack&&(null==(t=this.localMixAudioTrack)||t.setTrackCaptureVolume(this._localAudioTrack.outMediaTrack,e))}destroyDenoiserProcessor(){var e;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,null==(e=this.denoiserTrack)||e.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext)}destroy(){var e;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),null==(e=this.denoiser)||e.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack)}},OM=class extends xP{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,rb(this,"tinyId"),rb(this,"isRemote",!0),this.tinyId=t.tinyId}setMute(e){return 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===OM.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)}},wM=OM;rb(wM,"STATE_SUBSCRIBE","subscribe"),nb([Hw(Ww.INIT,wM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),UO.emit(BO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],wM.prototype,"subscribe",1),nb([Hw(wM.STATE_SUBSCRIBE,Ww.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),UO.emit(BO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],wM.prototype,"unsubscribe",1);var PM=class extends wM{constructor(e,t){super(e,t,1),rb(this,"volume",0),rb(this,"mediaType",1),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},MM=class extends wM{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),rb(this,"mediaType",4),rb(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}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}},LM=class extends MM{constructor(e,t){super(e,t,2),rb(this,"mediaType",2),rb(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function xM(){}var VM=e=>e(),UM=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,FM=1,BM=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new JM(e,this,this.streamId++);return KM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},HM=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=xM,this.error=xM,this.next=xM,this.dispose=xM,this.subscribe=xM,this.doDefer()}subscribe(e){return e instanceof BM?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(VM),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}},jM=class extends HM{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 GM(e,t,i){if(UM()){let n=Object.defineProperties(Object.setPrototypeOf(e,BM.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}});KM.create(n);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof BM&&KM.addSource(n,t)}return n}return e}function WM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var JM=class extends jM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{KM.defer(this.source,this.id)}))}next(e){KM.next(this.source,this.id,e),this.sink.next(e)}complete(){KM.complete(this.source,this.id),this.sink.complete()}error(e){KM.complete(this.source,this.id,e),this.sink.error(e)}},KM={addSource(e,t){WM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){WM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:n}=e;WM("subscribe",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){WM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){WM("defer",{id:e.id,streamId:t})},pipe(e){WM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){WM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=FM++),WM("create",{name:e.toString(),id:e.id})}},YM=class extends HM{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 zM,qM,QM=(zM=class extends jM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},qM="map",function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>{if(e instanceof BM){let i=GM((n=>{let r=new zM(n,...t);r.sourceId=i.id,r.subscribe(e)}),qM,arguments);return i.source=e,KM.pipe(i),i}return i=>e(new zM(i,...t))}});!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];i.reduce(((e,t)=>t(e)),e)}(function(e){return GM((t=>{let i=0,n=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(n)})),"interval"}),"interval",arguments)}(250),QM((()=>performance.now())),function(){return e=>{let t=new YM(e);if(e instanceof BM){let i=GM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,KM.pipe(i),i}return GM(t.add.bind(t),"share",arguments)}}());var XM=new Map;function $M(e,t){let i=ZC($C({},t),{timestamp:Tb()});XM.has(e)?XM.get(e).push(i):XM.set(e,[i])}UO.on(BO.JOIN_SUCCESS,(e=>{let{room:t}=e;$M(t.userId,{eventId:32788,eventDesc:"join room"})})),UO.on(BO.LEAVE_START,(e=>{let{room:t}=e;$M(t.userId,{eventId:32789,eventDesc:"leave room"})})),UO.on(BO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),$M(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),UO.on(BO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),$M(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),UO.on(BO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===PN.AUDIO?$M(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):$M(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),UO.on(BO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===PN.AUDIO?$M(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):$M(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),UO.on(BO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&$M(t.room.userId,{eventId:32777,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&$M(t.room.userId,{eventId:32776,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&$M(t.room.userId,{eventId:32803,eventDesc:"".concat(PN.SUBSCRIBE," ").concat(PN.SMALL_VIDEO),remoteUserId:t.userId}))})),UO.on(BO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&$M(t.room.userId,{eventId:32779,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&$M(t.room.userId,{eventId:32778,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&$M(t.room.userId,{eventId:32804,eventDesc:"".concat(PN.UNSUBSCRIBE," ").concat(PN.SMALL_VIDEO),remoteUserId:t.userId}))})),UO.on(BO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&$M(t.room.userId,{eventId:t.kind===PN.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===PN.VIDEO?"camera":"microphone")})})),UO.on(BO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&$M(t.room.userId,{eventId:t.kind===PN.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),UO.on(BO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===r?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===r?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&$M(n.userId,{eventId:t,eventDesc:i})})),UO.on(BO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===r?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&$M(n.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var ZM=ib(ab(),1),eL=class extends ZM.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,rb(this,"userMap",new Map),rb(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n="peer leave [".concat(e,"]");iO(t)||(n+=":".concat(kD[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:r.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:n,userId:r,tinyId:o}=e,s=SO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:SO(0,r),muteState:s,flag:n})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var tL,iL=!0,nL={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"},rL={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},oL=((tL=oL||{})[tL.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",tL[tL.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",tL[tL.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",tL[tL.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",tL[tL.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",tL[tL.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",tL[tL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",tL[tL.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",tL[tL.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",tL[tL.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",tL[tL.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",tL[tL.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",tL[tL.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",tL[tL.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",tL[tL.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",tL[tL.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",tL[tL.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",tL[tL.INVALID_OPERATION=5100]="INVALID_OPERATION",tL[tL.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",tL[tL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",tL[tL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",tL[tL.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",tL[tL.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",tL[tL.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",tL[tL.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",tL[tL.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",tL[tL.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",tL[tL.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",tL[tL.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",tL[tL.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",tL[tL.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",tL[tL.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",tL[tL.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",tL[tL.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",tL[tL.DEVICE_ERROR=5300]="DEVICE_ERROR",tL[tL.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",tL[tL.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",tL[tL.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",tL[tL.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",tL[tL.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",tL[tL.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",tL[tL.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",tL[tL.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",tL[tL.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",tL[tL.SERVER_ERROR=5400]="SERVER_ERROR",tL[tL.NEED_TO_BUY=5401]="NEED_TO_BUY",tL[tL.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",tL[tL.OPERATION_FAILED=5500]="OPERATION_FAILED",tL[tL.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",tL[tL.REJOIN_FAILED=5502]="REJOIN_FAILED",tL[tL.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",tL[tL.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",tL[tL.OPERATION_ABORT=5998]="OPERATION_ABORT",tL[tL.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",tL);var sL=ZC($C({},YO),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(eO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(eO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=aL(t),error:n}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function aL(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var cL=class extends Error{constructor(e){let{code:t,extraCode:i,message:n="",messageParams:r,fnName:o="",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s="",a=oL[i];try{t=sL[a]}catch(o){t=sL.UNKNOWN_ERROR}return tO(t)?s=t(n):nO(t)&&(s=t),r&&(s+=" doc:"),s}({code:i||t,params:$C({fnName:o,error:s},r)}),super(c),rb(this,"name","RtcError"),rb(this,"code"),rb(this,"extraCode"),rb(this,"functionName"),rb(this,"message"),rb(this,"handler"),rb(this,"originError"),this.name=oL[t],this.code=t,this.extraCode=i,this.functionName=o,this.originError=s,this.message=c,5302===this.extraCode&&(null==(a=this.originError)?void 0:a.message.includes("system"))&&(this.handler=()=>{let e=document.createElement("a");pk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):_k&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let n=e;if(e instanceof fb){let{stack:r}=e,o={code:rL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case _b.INVALID_PARAMETER:o.code=rL.INVALID_PARAMETER;break;case _b.INVALID_OPERATION:o.code=rL.INVALID_OPERATION;break;case _b.NOT_SUPPORTED:case _b.NOT_SUPPORTED_H264:o.code=rL.ENV_NOT_SUPPORTED,e.getCode()===_b.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(YO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case _b.DEVICE_NOT_FOUND:case _b.DEVICE_AUTO_RECOVER_FAILED:o.code=rL.DEVICE_ERROR;break;case _b.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case _b.SERVER_TIMEOUT:case _b.SWITCH_ROLE_FAILED:o.code=rL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case _b.API_CALL_ABORTED:o.code=rL.OPERATION_ABORT;break;case _b.INITIALIZE_FAILED:o.code=5300,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 _b.UNKNOWN:break;default:o.code=rL.OPERATION_FAILED}n=new cL(o),r&&(n.stack+=r.substr(r.indexOf("\n")))}else{if(e instanceof cL)return e;n=new cL({code:rL.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};var lL=cL,dL={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}}},uL={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}}},hL={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(nO(e)){let n=document.getElementById(e);if(!n)throw new lL({code:rL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(n instanceof HTMLElement))throw new lL({code:rL.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:eO(n)}})}}},pL={name:"userId",required:!0,type:"string"},_L={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function mL(e,t){if(!e)throw new lL({code:rL.INVALID_OPERATION,extraCode:5101,fnName:t})}function fL(e,t,i){if(!e)throw new lL({code:rL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var gL={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 lL({code:rL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(nO(e.roomId))throw new lL({code:rL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new lL({code:rL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new lL({code:rL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new lL({code:rL.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:hL,publish:{type:"boolean"},option:dL},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&rw())throw new lL({code:rL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},hL),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:dL}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:_L},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&rw())throw new lL({code:rL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:_L}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:hL,publish:{type:"boolean"},option:uL},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&rw())throw new lL({code:rL.ENV_NOT_SUPPORTED,extraCode:5201});if(!dw())throw new lL({code:rL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:hL,publish:{type:"boolean"},option:uL}},muteRemoteAudio:[pL,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[pL,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:hL,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){mL(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(fL(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new lL({code:rL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ZC($C({},hL),{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){mL(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(fL(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new lL({code:rL.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&&iO(e.streamType))throw new lL({code:rL.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){mL(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!Nw)throw new lL({code:rL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new lL({code:rL.INVALID_OPERATION,messageParams:{key:KO.SEI_DISABLED}});if(e.byteLength>1e3)throw new lL({code:rL.INVALID_PARAMETER,messageParams:{key:KO.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new lL({code:rL.INVALID_PARAMETER,messageParams:{key:KO.SEI_EMPTY}});if(mL(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new lL({code:rL.INVALID_PARAMETER,messageParams:{key:KO.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},TL={TRTC:gL},EL=class extends Error{};function SL(e,t){let i=RO(e);for(let n=0;n<t.length;n++)AO(i[n],t[n]);return i}function IL(e){this._resolve=Promise.resolve(e)}function vL(e){this._reject=Promise.reject(e)}var yL=class{constructor(e,t){this.instance=e,this.group=t,rb(this,"started",!1),rb(this,"ops",[]),rb(this,"startSame",(()=>!0)),rb(this,"mergeUpdate",SL);let i=yL.instances.get(e);i?i.set(t,this):yL.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=yL.instances.get(e);return i&&i.get(t)||new yL(e,t)}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new EL("start failed")),null==(n=this.currentOp)||n.action(),t},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:IL,reject:vL};try{switch(this.state){case 1:if(0===e)throw new EL("already started");break;case 4:if(2===e)throw new EL("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(n,r)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new EL("already start");break;case 3:switch(e.type){case 2:throw new EL("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new EL("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new EL("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 EL("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new EL("start not allowed after update");case 0:throw new EL("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new EL("keep start")),new EL("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}},AL=yL;rb(AL,"instances",new WeakMap);var RL=new WeakMap,CL=(e,t)=>{if(t instanceof EL){let{stack:i}=t;t=new lL({code:rL.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function bL(e,t){return rM(((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];let a=AL.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(CL.bind(null,n))}))}function kL(e,t){let{merge:i,debounce:n}=t||{};return rM(((t,r)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=AL.get(this,"string"==typeof e?e:e.call(this,...s));if(i&&(c.mergeUpdate=i.bind(this)),n&&n.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=n;return new Promise(((n,o)=>{var a,l;let d=null==(a=RL.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(CL.bind(null,r)).then(n,o)}),e);RL.has(this)?null==(l=RL.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):RL.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]))}))}return c.action(2,t.bind(this),s).catch(CL.bind(null,r))}))}function NL(e){return rM(((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return AL.get(this,"string"==typeof e?e:e.call(this,...r)).action(3,t.bind(this),r).catch(CL.bind(null,i))}))}var DL={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function OL(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function wL(e){return e===nL.QOS_PREFERENCE_CLEAR?"detail":e===nL.QOS_PREFERENCE_SMOOTH?"motion":""}function PL(e,t){return{room:e,innerEmitter:UO,constants:tN,environment:Ib,utils:Sb,eventLogger:Xw,log:e.getLogger(),errorModule:t,clearStarted(t,i){let n=t.getAlias(),r=AL.instances.get(e);if(r)if(i){let e=r.get(n+i);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(n)&&(e.started=!1)}))}}}var ML=new WeakMap;function LL(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return rM(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{VL.call(this,t,r,i,this._name)}catch(sN){return Promise.reject(sN)}return e.apply(this,r)}))}function xL(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return rM(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{VL.call(this,t,r,i,this._name)}catch(sN){throw sN}return e.apply(this,r)}))}function VL(e,t,i,n){if(aO(e))for(let r=0;r<e.length;r++)UL.call(this,{rule:e[r],value:t[r],key:e[r].name,fnName:i,className:n});else UL.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:n})}function UL(e){let{rule:t,value:i,key:n,fnName:r,className:o}=e;function s(e){return{code:rL.INVALID_PARAMETER,extraCode:e,fnName:r,messageParams:{key:n,rule:t,value:i}}}if(iO(i)){if(t.required)throw new lL(s(5001));if(iO(t.defaultValue))return void(tO(t.validate)&&t.validate.call(this,i,n,r,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let n=0;n<t.type.length;n++)null===t.type[n]&&null===i&&(e=!0),tO(t.type[n])&&i instanceof t.type[n]&&(e=!0),nO(t.type[n])&&eO(i)===t.type[n].toLowerCase()&&(e=!0);if(!e)throw new lL({code:rL.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:n,rule:{type:t.type.map((e=>uO(e)?hO(e):nO(e)?e:eO(e)))},value:i}})}else if(!iO(t.type)&&eO(i)!==t.type)throw new lL(s(5002));if(!1===t.allowEmpty){let e=rO(i)&&(0===i||Number.isNaN(i)),t=nO(i)&&""===i.trim();if(e||t)throw new lL(s(5003))}if(t.notLessThanZero&&rO(i)&&i<0)throw new lL(s(5006));if(!iO(t.min)&&rO(i)&&i<t.min)throw new lL(s(5007));if(!iO(t.max)&&rO(i)&&i>t.max)throw new lL(s(5008));if(nO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new lL(s(5004))}else if(tO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new lL(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new lL(s(5005));let{properties:a}=t;XD(a)&&sO(i)&&Object.keys(a).forEach((e=>{UL.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:r,className:o})}));let{arrayItem:c}=t;XD(c)&&aO(i)&&i.forEach(((e,t)=>{UL.call(this,{rule:c,value:e,key:"".concat(n,"[").concat(t,"]"),fnName:r,className:o})})),tO(t.validate)&&t.validate.call(this,i,n,r,o,this)}function FL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=(()=>""),getRemoteId:i=(()=>"")}=e;return rM(((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];function a(e,t,i){if(i&&i.includes(e))return"hided";if(t===o||e in o)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(eO(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(eO(t))}}let c=this._log||jO,l=t.call(this,...o),d=""!==l?"".concat(l,".").concat(n):n;o.length>0?c.info("".concat(d,"() ").concat(JSON.stringify(o,((e,t)=>a(e,t,["userSig","privateMapKey"]))))):c.info("".concat(d,"()"));try{let t=e.apply(this,o),n=mO();return dO(t)?t.then((e=>(c.info("".concat(d,"() success ").concat(i.call(this,...o))),UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:mO()-n}),e))).catch((e=>{throw e=lL.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error("".concat(d,"() failed ").concat(i.call(this,...o)," ").concat(e," params: ").concat(JSON.stringify(o,a))),UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:e}),e})):(UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:mO()-n}),t)}catch(u){throw u=lL.convertFrom.call(this,u,d),c.error("".concat(d,"() failed ").concat(u," params: ").concat(JSON.stringify(o,a))),UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:u}),u}}))}var BL=e=>rM(((t,i)=>function(n,r){return sb(this,null,(function*(){let o=this._plugins.get(n);if(o)return VL.call(this,o.getValidateRule(e),[r],i,"TRTC"),t.call(this,o,r);this._log.warn("plugin ".concat(n," is not found"))}))})),HL=0,jL=class{constructor(e){this.core=e,rb(this,"log"),HL+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(HL)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(HL)),this.core=e}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return jL.startValidateRule;case"update":return jL.updateValidateRule;case"stop":return jL.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.addMusicSource(e)}))}update(e){return sb(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.updateMusicSource(e)}))}stop(e){return sb(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.removeMusicSource(e)}))}},GL=jL;rb(GL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if("*"!==e.url){let t=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],r=t.split(".").pop(),o=n.indexOf(r)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new lL({code:rL.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}}}),rb(GL,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}}}),rb(GL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var WL=0,JL=class{constructor(e){this.core=e,rb(this,"log"),WL+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(WL)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(WL))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{assetsPath:{type:"string",required:!0},sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,n,r){if(!e.room.audioManager.hasAudioTrack)throw new lL({code:rL.INVALID_OPERATION,extraCode:5106,fnName:n})}}}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(e){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return JL.startValidateRule(this.core);case"update":return JL.updateValidateRule;case"stop":return JL.stopValidateRule}}start(e){return sb(this,null,(function*(){let{room:t}=this.core,{assetsPath:i,sdkAppId:n,userId:r,userSig:o}=e;if(i&&!t.audioManager.isDenoiserInit)try{yield t.audioManager.initDenoiser({assetsPath:i,sdkAppId:n,userId:r,userSig:o})}catch(s){if(s.message)throw new lL({code:rL.INVALID_PARAMETER,message:s.message})}yield t.audioManager.enableDenoiser(e),t.sendAbilityStatus({ai_denoise:1})}))}update(e){return sb(this,null,(function*(){}))}stop(e){return sb(this,null,(function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser()}))}},KL=JL;rb(KL,"updateValidateRule",{type:"object"}),rb(KL,"stopValidateRule",{type:"object"});var YL=0,zL=new Set,qL=null;rN("5.3.2-beta.7");var QL=class extends hb.EventEmitter{constructor(e,t){super(),rb(this,"_room"),rb(this,"_eventListened",new Set),rb(this,"_localVideoTrack",null),rb(this,"_localAudioTrack",null),rb(this,"_localScreenTrack",null),rb(this,"_localScreenAudioTrack",null),rb(this,"_localVideoConfig",null),rb(this,"_localScreenConfig",null),rb(this,"_localAudioConfig",null),rb(this,"_remoteVideoConfigMap",new Map),rb(this,"_remoteAudioConfigMap",new Map),rb(this,"_remoteAudioMuteMap",new Map),rb(this,"_mediaTrackMap",new WeakMap),rb(this,"_log",jO.createLogger({id:"t".concat(++YL)})),rb(this,"_plugins",new Map),rb(this,"_networkQuality",null),rb(this,"_speakerId"),this._room=new e($C({logger:this._log,frameWorkType:QL.frameWorkType},t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}});let i={RtcError:lL,ErrorCode:rL,ErrorCodeDictionary:oL};t.plugins&&t.plugins.forEach((e=>{let t=new e(PL(this._room,i));this._plugins.set(t.getName(),t)}));let n=new GL(PL(this._room,i));this._plugins.set(n.getName(),n);let r=new KL(PL(this._room,i));this._plugins.set(r.getName(),r),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(DL.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 lL({code:rL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this.on(DL.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(DL.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];try{return n.apply(e,o)}catch(i){let n=QO({key:KO.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return jO.warn("".concat(n,"\n\n").concat(i.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;iL&&(iL=!1,5!==jO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(gN,"/en/index.html")),console.info("* Changelog: ".concat(gN,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),jO.info("TRTC Web SDK Version:",nN),jO.info("UA:",navigator.userAgent),jO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),Xk().then((e=>{if(e){let t="UAData: ".concat(e.platform,"/").concat(e.platformVersion);e.architecture&&e.bitness&&(t+=" ".concat(e.architecture,"/").concat(e.bitness)),e.mobile&&(t+=" mobile"),e.model&&(t+=" model: ".concat(e.model)),e.fullVersionList&&(t+=" ".concat(e.fullVersionList.filter((e=>"Not/A)Brand"!==e.brand)).map((e=>"".concat(e.brand,"/").concat(e.version))).join(","))),jO.info(t)}})))}();let i=new QL(e,t||{});return zL.add(i),i}_listenEvents(){IP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(DL.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(DL.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(DL.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(DL.ERROR,lL.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(DL.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(DL.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{IP(t,t).add("player-state-changed",(i=>{let n=ZC($C({},i),{userId:e.userId});t.kind===PN.VIDEO&&(n.streamType=OL(t.streamType)),this.emit(t.kind===PN.AUDIO?DL.AUDIO_PLAY_STATE_CHANGED:DL.VIDEO_PLAY_STATE_CHANGED,n)})).add("error",(e=>{e.getCode()===_b.PLAY_NOT_ALLOWED&&this.emit(DL.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{vP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i,r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete("".concat(n,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(n,"_","sub")),r!==s&&this.emit(s?DL.REMOTE_AUDIO_AVAILABLE:DL.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),o!==a&&this.emit(a?DL.REMOTE_VIDEO_AVAILABLE:DL.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?DL.REMOTE_VIDEO_AVAILABLE:DL.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"})})).add("firewall-restriction",(()=>{this.emit(DL.ERROR,new lL({code:rL.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(DL.SEI_MESSAGE,ZC($C({},e),{streamType:OL(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,n,r,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/xD},video:e.msg_up_stream_info.msg_video_status.filter((e=>c[e.uint32_video_stream_type])).map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:c[e.uint32_video_stream_type]})))},remoteStatistics:e.msg_down_stream_info.map((e=>({userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/xD},video:e.msg_video_status.map((e=>({bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:c[e.uint32_video_stream_type]})))})))};this.emit(DL.STATISTICS,l)})),IP(this,GP).add("audioInputAdded",(e=>{this.emit(DL.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(DL.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(DL.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(DL.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>sb(this,null,(function*(){if(this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),qL&&qL.deviceId===RD){let e=(yield zP()).find((e=>e.deviceId===RD));e&&qL.groupId!==e.groupId&&(qL=e,this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>sb(this,null,(function*(){this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield zP())[0];t&&qL&&(qL.deviceId===e.deviceId||qL.deviceId===RD&&qL.groupId!==t.groupId)&&(qL=t,this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}enterRoom(e){return sb(this,null,(function*(){var t,i;let{scene:n="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!nO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,oO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),this._handleReceiveMode(),yield this._room.join(a,n,QL.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return sb(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return sb(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){vP(this),this.removeAllListeners(),this._room.destroy(),zL.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:n,option:r}=t,o=new uM(e._room.audioManager),s={},a={muted:!0};r&&(iO(r.microphoneId)?iO(r.audioTrack)||(s.customSource=r.audioTrack):s.deviceId=r.microphoneId,r&&rO(r.captureVolume)&&o.setCaptureVolume(r.captureVolume),iO(r.profile)||(nO(r.profile)?DN[r.profile]&&o.setProfile(DN[r.profile]):o.setProfile(r.profile)),rO(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),iO(r.echoCancellation)||(o.profile.echoCancellation=r.echoCancellation),iO(r.noiseSuppression)||(o.profile.noiseSuppression=r.noiseSuppression),iO(r.autoGainControl)||(o.profile.autoGainControl=r.autoGainControl)),o.on("5",(t=>{e.emit(DL.ERROR,new lL({code:rL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(DL.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=lL.convertFrom(t.error)),e.emit(DL.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),iO(n)||o.setMute(n),IP(o,o).add("player-state-changed",(t=>{e.emit(DL.AUDIO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),yield e._updateAudioPlayOption({playOption:a,track:o}),e._localAudioTrack=o,e._localAudioConfig=ZC($C({},t),{publish:i})}()}))}updateLocalAudio(e){return sb(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):iO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),iO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),iO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!iO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),iO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),AO(this._localAudioConfig,e)}))}stopLocalAudio(){return sb(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),vP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:n=!0,mute:r,option:o}=t,s=new hM(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:iO(o.useFrontCamera)?iO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?PN.FACING_MODE_USER:PN.FACING_MODE_ENVIRONMENT,iO(o.profile)||(nO(o.profile)?ON[o.profile]&&s.setProfile(ON[o.profile]):s.setProfile(o.profile)),iO(o.fillMode)||(c.objectFit=o.fillMode),iO(o.mirror)||(c.mirror=o.mirror),iO(o.small)||(gw()?nO(o.small)?s.small=ON[o.small]:!0===o.small?s.small=ON["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(DL.ERROR,new lL({code:rL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(DL.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=lL.convertFrom(t.error)),e.emit(DL.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),iO(r)||s.setMute(r),(null==o?void 0:o.qosPreference)&&s.mediaTrack){let e=wL(o.qosPreference);s.mediaTrack.contentHint=e}IP(s,s).add("player-state-changed",(t=>{e.emit(DL.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"main"}))})),n&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),yield e._updateVideoPlayOption({view:i,playOption:c,track:s}),e._localVideoTrack=s,e._localVideoConfig=ZC($C({},t),{view:i,publish:n})}()}))}updateLocalVideo(e){return sb(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r){if(iO(r.profile)||(nO(r.profile)?ON[r.profile]&&this._localVideoTrack.setProfile(ON[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&iO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):iO(r.useFrontCamera)?iO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?PN.FACING_MODE_USER:PN.FACING_MODE_ENVIRONMENT),iO(r.fillMode)||(o.objectFit=r.fillMode),iO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack){let e=wL(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(r.small){let e=!this._localVideoTrack.small;gw()?(!0===r.small?this._localVideoTrack.small=ON["120p"]:nO(r.small)?this._localVideoTrack.small=ON[r.small]:this._localVideoTrack.small=r.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===r.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!iO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),iO(n)||this._localVideoTrack.setMute(n),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),AO(this._localVideoConfig,e)}))}stopLocalVideo(){return sb(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),vP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:n=!0,option:r}=t,o=new _M(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=lL.convertFrom(t.error)),e.emit(DL.PUBLISH_STATE_CHANGED,ZC($C({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null;o.setMediaType(2);let a={},c={};r&&(iO(r.profile)||(nO(r.profile)?wN[r.profile]&&o.setProfile(wN[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),iO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=wL(r.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(PN.ENDED,(()=>{e._stopScreenShare(),e.emit(DL.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new mM(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),IP(o,o).add("player-state-changed",(t=>{e.emit(DL.VIDEO_PLAY_STATE_CHANGED,ZC($C({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=ZC($C({},t),{view:i,publish:n})}()}))}updateScreenShare(e){return sb(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(iO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=wL(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!iO(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),AO(this._localScreenConfig,e)}))}stopScreenShare(){return sb(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return sb(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),r&&(iO(r.fillMode)||(a.objectFit=r.fillMode),iO(r.mirror)||(a.mirror=r.mirror),"main"===n&&!iO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._remoteVideoConfigMap.set(o,e),this._emitTrackEvent(c)}))}updateRemoteVideo(e){return sb(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n),s=this._remoteVideoConfigMap.get(o);if(!s||!this._room.remotePublishedUserMap.has(i))return;let a={};r&&(iO(r.fillMode)||(a.objectFit=r.fillMode),iO(r.mirror)||(a.mirror=r.mirror));let c=null,l=this._room.remotePublishedUserMap.get(i);"main"===n&&(null==l?void 0:l.muteState.hasVideo)&&(c=l.remoteVideoTrack),"sub"===n&&(null==l?void 0:l.muteState.hasAuxiliary)&&(c=l.remoteAuxiliaryTrack),c&&("main"===n&&r&&!iO(r.small)&&this._room.changeType(r.small,c.user),yield this._updateVideoPlayOption({view:t,playOption:a,track:c,prevConfig:s})),AO(s,e)}))}stopRemoteVideo(e){return sb(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;"main"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return sb(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return sb(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return sb(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return sb(this,null,(function*(){return e.stop(t)}))}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,i){return super.on(e,t,i),this._eventListened.add(e),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let t=this._room.remotePublishedUserMap.get(e);if(t)return t.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return sb(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(iO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o})}catch(rU){throw this._remoteAudioConfigMap.delete(t),rU}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return sb(this,null,(function*(){let i=this._room.remotePublishedUserMap.get(e.userId);i&&(i.remoteAudioTrack.stop(),i.muteState.hasAudio&&t&&(yield this._room.unsubscribe(i.remoteAudioTrack)),this._mediaTrackMap.get(i.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(i.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId))}))}_updateVideoPlayOption(e){return sb(this,arguments,(function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(iO(t)&&r&&r.view&&!EO(i)){let e;e=aO(r.view)?r.view:CO(r.view),e&&(yield n.play(e,i))}if(!iO(t)){let e;e=aO(t)?t:CO(t),e?yield n.play(e,i):n.stop()}}()}))}_updateAudioPlayOption(e){return sb(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(aN){}iO(t.muted)||i.setPlayerMute(t.muted),iO(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(DL.TRACK,{userId:t,streamType:OL(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch((()=>{}))}_handleReceiveMode(){this._room.autoReceiveAudio&&IP(this,this).add(DL.REMOTE_AUDIO_AVAILABLE,(e=>sb(this,[e],(function(e){var t=this;let{userId:i}=e;return function*(){t._remoteAudioMuteMap.get("*")||t._remoteAudioMuteMap.get(i)||t._doStartRemoteAudio({userId:i}).catch((()=>{}))}()})))),this._room.autoReceiveVideo&&IP(this,this).add(DL.REMOTE_VIDEO_AVAILABLE,(e=>{let{userId:t,streamType:i}=e,n=this._room.remotePublishedUserMap.get(t);if(n){let e="main"===i?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}))}_exitRoom(){return sb(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{vP(e.remoteAudioTrack),vP(e.remoteVideoTrack),vP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return sb(this,null,(function*(){var e,t,i;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(),null==(t=this._localScreenAudioTrack)||t.stop(),null==(i=this._localScreenAudioTrack)||i.close(),vP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return sb(this,null,(function*(){if(qL&&!WP(qL))this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"active",device:qL});else{let e=yield zP();if(e[0]&&!WP(e[0]))qL=e[0],this.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!qL||WP(qL))&&(this._initActiveSpeaker(),UO.off("102",this._initActiveSpeaker))};UO.on("102",e)}}}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}static setLogLevel(e,t){jO.setLogLevel(e),iO(t)||(t?jO.enableUploadLog():jO.disableUploadLog())}static isSupported(){return cw()}static getCameraList(){return YP(!0)}static getMicrophoneList(){return KP(!0)}static getSpeakerList(){return zP(!0)}static setCurrentSpeaker(e){return sb(this,null,(function*(){(yield zP()).forEach((t=>{t.deviceId===e&&(zL.forEach((i=>{i.setCurrentSpeaker(e),i.emit(DL.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),qL=t)}))}))}},XL=QL;rb(XL,"_loggerManager",jO),rb(XL,"EVENT",DL),rb(XL,"ERROR_CODE",rL),rb(XL,"TYPE",nL),rb(XL,"frameWorkType",30),nb([LL(TL.TRTC.enterRoom),bL("room",((e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId})),rM((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),FL()],XL.prototype,"enterRoom",1),nb([FL()],XL.prototype,"exitRoom",1),nb([LL(TL.TRTC.switchRole),kL("room",{merge:(e,t)=>t}),FL()],XL.prototype,"switchRole",1),nb([FL()],XL.prototype,"destroy",1),nb([LL(TL.TRTC.startLocalAudio),bL("audio",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId)})),FL()],XL.prototype,"startLocalAudio",1),nb([LL(TL.TRTC.updateLocalAudio),kL("audio",{debounce:{delay:200,getKey:()=>"".concat(YL,"-localAudio"),isNeedToDebounce:e=>{var t;return!iO(null==(t=e.option)?void 0:t.captureVolume)}}}),FL()],XL.prototype,"updateLocalAudio",1),nb([NL("audio"),FL()],XL.prototype,"stopLocalAudio",1),nb([LL(TL.TRTC.startLocalVideo),bL("video",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId)})),FL()],XL.prototype,"startLocalVideo",1),nb([LL(TL.TRTC.updateLocalVideo),kL("video"),FL()],XL.prototype,"updateLocalVideo",1),nb([NL("video"),FL()],XL.prototype,"stopLocalVideo",1),nb([LL(TL.TRTC.startScreenShare),bL("screen",(()=>!0)),FL()],XL.prototype,"startScreenShare",1),nb([LL(TL.TRTC.updateScreenShare),kL("screen"),FL()],XL.prototype,"updateScreenShare",1),nb([FL()],XL.prototype,"stopScreenShare",1),nb([LL(TL.TRTC.startRemoteVideo),bL((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),FL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],XL.prototype,"startRemoteVideo",1),nb([LL(TL.TRTC.updateRemoteVideo),kL((e=>"v".concat(e.userId).concat(e.streamType))),FL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],XL.prototype,"updateRemoteVideo",1),nb([LL(TL.TRTC.stopRemoteVideo),rM((e=>function(t){return sb(this,null,(function*(){if("*"===t.userId){let e=[];return this._room.remotePublishedUserMap.forEach((t=>{this._remoteVideoConfigMap.has("".concat(t.userId,"_","main"))&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch((()=>{}))),this._remoteVideoConfigMap.has("".concat(t.userId,"_","sub"))&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch((()=>{})))})),Promise.all(e)}return e.call(this,t)}))})),FL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],XL.prototype,"stopRemoteVideo",1),nb([NL((e=>"v".concat(e.userId).concat(e.streamType)))],XL.prototype,"_stopRemoteVideo",1),nb([LL(...TL.TRTC.muteRemoteAudio),FL({getRemoteId:e=>e})],XL.prototype,"muteRemoteAudio",1),nb([xL(...TL.TRTC.setRemoteAudioVolume),function(e,t){return rM(((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];var s,a;let c=null==(s=ML.get(this))?void 0:s.get(t(...r));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,r)}),e);ML.has(this)?null==(a=ML.get(this))||a.set(t(...r),l):ML.set(this,new Map([[t(...r),l]]))}))}(200,(e=>e)),FL({getRemoteId:e=>e})],XL.prototype,"setRemoteAudioVolume",1),nb([BL("start"),bL(((e,t)=>e.getAlias()+e.getGroup(t))),FL({namePrefix:e=>e.getName()})],XL.prototype,"startPlugin",1),nb([BL("update"),kL(((e,t)=>e.getAlias()+e.getGroup(t))),FL({namePrefix:e=>e.getName()})],XL.prototype,"updatePlugin",1),nb([BL("stop"),NL(((e,t)=>e.getAlias()+e.getGroup(t))),FL({namePrefix:e=>e.getName()})],XL.prototype,"stopPlugin",1),nb([xL(...TL.TRTC.enableAudioVolumeEvaluation)],XL.prototype,"enableAudioVolumeEvaluation",1),nb([FL()],XL.prototype,"setCurrentSpeaker",1),nb([bL((e=>"a".concat(e.userId)),(()=>!0))],XL.prototype,"_startRemoteAudio",1),nb([rM((e=>function(t){return sb(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(ZC($C({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),NL((e=>"a".concat(e.userId)))],XL.prototype,"_stopRemoteAudio",1),nb([NL("room")],XL.prototype,"_exitRoom",1),nb([NL("screen")],XL.prototype,"_stopScreenShare",1),nb([LL(TL.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return rM(((e,r)=>{let o=new Map;return UO.on(BO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],XL.prototype,"sendSEIMessage",1),nb([LL(TL.TRTC.create)],XL,"_create",1);var $L=XL,ZL=class{constructor(){this._set=new Set,UO.on(BO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(n)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(n)}getKey(e,t,i,n){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(n)}isJoined(e){let{userId:t,roomId:i,sdkAppId:n,room:r}=e;return"rtc"!==r.scene&&this._set.has(this.getKey(t,i,n,r.useStringRoomId))}};function ex(){return sb(this,null,(function*(){let e,t;try{let t=yield KP();e=t&&t.length}catch(u){}try{let e=yield YP();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:n,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=JO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:n,h264Decode:o,vp8Encode:r,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Xw.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),Xw.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var tx=ib(ab()),ix="1",nx="5",rx="2",ox="3",sx="4",ax={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},cx=[ax.UPDATE_REMOTE_MUTE_STAT,ax.UPLINK_NETWORK_STATS,ax.USER_LIST_RES,ax.MUTE_RESULT],lx={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"},dx="publish_change",ux="join",hx="leave",px="quality_report",_x="mute_uplink",mx="publish",fx="publish_state_change",gx="unpublish",Tx="subscribe",Ex="unsubscribe",Sx="subscribe_change",Ix="start_publishing",vx="stop_publishing",yx="start_push_user_cdn",Ax="stop_push_user_cdn",Rx="start_mcu_mix",Cx="stop_mcu_mix",bx="get_user_list",kx="change_role",Nx="update_constraint_config",Dx="rebuild_pc",Ox="join/v2",wx="publish/v2",Px="subscribe/v3",Mx="ability_status_report",Lx="reconnect",xx=new WeakMap;function Vx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=xO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,(()=>{var t;null!=(t=xx.get(e))&&t.has(o)?r():s(n)}),s,a)},onRetrying(t,i){var r;tO(n)&&n.call(this,t,i),null!=(r=xx.get(e))&&r.has(o)&&(xx.get(e).get(o).stopRetry=i)},onRetryFailed:r});return s.value=function(){let t=xx.get(e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return t?t.set(o,{args:n}):xx.set(e,new Map([[o,{args:n}]])),a.apply(this,n).finally((()=>{var t;return null==(t=xx.get(e))?void 0:t.delete(o)}))},s}}function Ux(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(r=xx.get(e))&&r.has(t)){let{stopRetry:r,args:s}=xx.get(e).get(t),a=!0;if(n)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),r&&r(),null==(o=xx.get(e))||o.delete(t))}return s.apply(this,c)},o}}var Fx=null,Bx=!0;function Hx(e){oO(e)&&e!==Bx&&(Bx=e,jO.info("setIsNeedToSchedule ".concat(e)))}function jx(e){return sb(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:n,roomId:r,userSig:o,version:s,frameWorkType:a}=e;return function*(){if(!Bx&&Fx)return{isCached:!0,result:Fx};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(n)),c.append("groupId",String(r)),c.append("sdkVersion",s),c.append("userSig",String(o)),a&&c.append("frameWorkType",String(a));let l=mO(),d=yield function(e,t,i){return new Promise(((n,r)=>{let o=null;_O([Yx((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n()}))(Jx(i,PN.MAIN),e,{get timeout(){return 1e3*$D(2+t.count[0])}}),Yx((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n()}))(Jx(i,PN.BACKUP),e,{get timeout(){return 1e3*$D(2+t.count[1])}})]).then((e=>{o=e,n(o)})).catch(r)}))}(c,e,i);d.config&&(d.config.loggerDomain&&hN(d.config.loggerDomain),oO(d.config.scheduleCache)&&Hx(!d.config.scheduleCache)),e.delta=mO()-l;let u=function(e,t,i){let n=performance.getEntriesByType("resource"),r=Jx(e,PN.MAIN),o=Jx(e,PN.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?PN.MAIN:PN.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];Xw.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=ZC($C({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,l);return Fx=d,{isCached:!1,result:d,detailCost:u}}catch(c){let e=aO(c)?c[0]:c,t=rO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),n=new fb({code:_b.SCHEDULE_FAILED,extraCode:t,message:QO({key:KO.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw jO.error(i,t),n}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(SD).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),UO.on("28",(()=>Hx(!0))),UO.on("63",(()=>Hx(!0))),UO.on("84",(()=>Hx(!0))),UO.on("201",(e=>{"RECONNECTING"===e.state&&Hx(!0)})),UO.on("202",(e=>{"RECONNECTING"===e.state&&Hx(!0)}));var Gx={main:"",backup:""};function Wx(e){aO(e)?(Gx.main=e[0],Gx.backup=e[1]):Gx.main=e}function Jx(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:PN.MAIN;return t=UD(e)?i===PN.MAIN?SD.MAIN_OVERSEA:SD.BACKUP_OVERSEA:i===PN.MAIN?SD.MAIN:SD.BACKUP,"https://".concat(Gx[i]||t,"/api/v1/config")}function Kx(e,t,i){return new Promise(((n,r)=>{MO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg})})).catch(r)}))}var Yx=(e,t)=>xO({retryFunction:Kx,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var zx=new Set;var qx=class extends tx.default{constructor(e){var t,i;super(),rb(this,"room"),rb(this,"url"),rb(this,"backupUrl"),rb(this,"race"),rb(this,"_socketInUse"),rb(this,"_socket"),rb(this,"_backupSocket"),rb(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_seq",0),rb(this,"_log"),rb(this,"_lastMessageTime",-1),rb(this,"_connnectStartTime",-1),rb(this,"_stopConnectRetry"),rb(this,"bytesSent",0),rb(this,"bytesReceived",0),rb(this,"keepAlive",!1),this.room=e.room,this.race=!!iO(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-zx.size>0&&this.room.enableSPC&&(this.keepAlive=!0,zx.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=jO.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));return this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return"CONNECTED"===this._currentState}get isConnecting(){return"CONNECTING"===this._currentState}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"]").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive)));let i=e._urlWithParam,n=e._backupUrlWithParam;e._connnectStartTime=mO(),e._socketInUse=yield _O([e.connectWS({url:i,isMain:!0,timeout:t}),e.connectWS({url:n,isMain:!1,timeout:t})]),e.unbindAndCloseSocket(e._socketInUse===e._socket?PN.BACKUP:PN.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:n}=e,r=new WebSocket(t);this.bindSocket(r),n?this._socket=r:this._backupSocket=r;let o=-1;return new Promise(((e,t)=>{r.onclose=t,r.onerror=t,r.onopen=()=>e(r),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(n?PN.MAIN:PN.BACKUP),t(new fb({code:_b.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{r.onclose=null,r.onerror=null,r.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===PN.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(oD){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(oD){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||1e3!==e.code)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?PN.MAIN:PN.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),e.target===this._socketInUse&&(this.unbindAndCloseSocket(PN.MAIN),this.unbindAndCloseSocket(PN.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=OO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(ax),o=Object.keys(ax)[r.indexOf(i)],s=lx[o];switch(cx.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case ax.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&function(e){gb=e-(new Date).getTime();let t=new Date;t.setTime(e),jO.info("baseTime from server: ".concat(t," offset: ").concat(gb))}(n.svrTime),this._log.info("ChannelSetup Success"),UO.emit(BO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",cost:mO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(ix,{signalInfo:this._signalInfo});else{let e=new fb({code:_b.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:QO({key:KO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),UO.emit(BO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",error:e}),this.emit(nx,e)}break;case ax.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return sb(this,null,(function*(){try{Hx(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(oN){}}))}reconnect(){return sb(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:n,relayPort:r}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:Lx,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:i,relayPort:r},responseCommand:lx.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),UO.emit(BO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketReconnect",cost:mO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(oN){this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=OO(n),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(r,l);let e=new fb({code:_b.API_CALL_TIMEOUT,message:QO({key:KO.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t))};this.on(r,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return xO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(n,"]"))},settings:{retries:n,timeout:r},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),zx.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(PN.MAIN),this.unbindAndCloseSocket(PN.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof Uw&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(Ww.STATECHANGED,i))};this.room.on(Ww.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(rx,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e&&this.emit(ox))}};nb([Vx({settings:{retries:1/0,timeout:2e3},onError(e,t){this.room.isDestroyed||t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,this.room.isDestroyed&&t())}})],qx.prototype,"connect",1);var Qx=ib(ab()),Xx=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],n=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let r=6;r<this.dataView.buffer.byteLength;r++){let i=this.dataView.getUint8(r);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),n=new DataView(i);for(let r=0;r<i.byteLength;r++,t++)n.setInt8(r,this.dataView.getInt8(t));return n}},$x=class{constructor(e,t){this._singlePC=e,this._log=t,rb(this,"_seiMessageList",[]),rb(this,"_smallSeiMessageList",[]),rb(this,"_seiPayloadType",243),rb(this,"_seiAbortMap",new Map),rb(this,"_nonSeiAbortMap",new Map),rb(this,"onSEIMessage",null)}isRunning(e){return this._seiAbortMap.has(e)}start(e){let t=e.direction===PN.TRANSCEIVER_DIRECTION_SENDONLY,i=(t?e.sender:e.receiver).createEncodedStreams(),n=i.readable,r=i.writable,o=new TransformStream({transform:t?(t,i)=>this.encodeVideoFrame(t,i,e):(t,i)=>this.decodeVideoFrame(t,i,e)}),s=new AbortController;n.pipeThrough(o).pipeTo(r,s).catch((e=>{this._log.warn(e)})),this._seiAbortMap.set(e,s)}restart(e){this.stop(e),this.start(e)}stop(e){var t;null==(t=this._seiAbortMap.get(e))||t.abort(),this._seiAbortMap.delete(e)}destroy(){this._seiAbortMap.forEach((e=>e.abort())),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach((e=>e.abort())),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach(((e,t)=>{var i,n;if("inactive"!==e.direction&&e.mid)if(t<4)1===t||2===t?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let r=(t-4)%3==1,o=(t-4)%3==2;(null==(n=null==(i=e.receiver)?void 0:i.track)?void 0:n.kind)===PN.VIDEO&&(r||o)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}}))}catch(qM){this._log.warn(qM)}}pipeSenderOrReceiver(e){let t=e.direction===PN.TRANSCEIVER_DIRECTION_SENDONLY?e.sender:e.receiver,{readable:i,writable:n}=t.createEncodedStreams(),r=new AbortController;this._nonSeiAbortMap.set(e,r),i.pipeTo(n,r).catch((()=>{}))}push(e,t){var i,n;t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==(n=null==(i=this._singlePC.getPeerConnection())?void 0:i.getSenders()[2])?void 0:n.track)&&this._smallSeiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0,n=new DataView(e);for(let r=0;r<e.byteLength;r++)switch(n.getUint8(r)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encodeVideoFrame(e,t,i){try{let t=2===Number(i.mid)?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&t.length>0&&!this.isEmptyFrame(e)){let i=9-this.getNaluCount(e.data);if(i<=0)return;let n=t.splice(0,i).reverse().map(this.encodeSEINalu.bind(this)),r=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(r+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<n.length;e++)for(let t=0;t<n[e].dataView.byteLength;t++)s.setInt8(c++,n[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));e.data=o,this._log.debug("".concat(n.length," sei sent"))}}catch(sN){this._log.warn(sN)}t.enqueue(e)}decodeVideoFrame(e,t,i){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],n=new DataView(e.data),r=0,o=-1,s=-1;for(let i=0;i<e.data.byteLength;i++){let a=n.getUint8(i);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=i-r;if(-1===o?o=a:-1===s&&(s=a,t.push(new Xx(new DataView(n.buffer.slice(o,s)))),o=a,s=-1),6!==n.getUint8(i+1)){e.data=new DataView(n.buffer.slice(a)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),tO(this.onSEIMessage)&&t.reverse().forEach((e=>{let t=Number(i.mid);this.onSEIMessage({seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,mid:t,streamType:(t-4)%3==2?"auxiliary":"main"})}))}}catch(sN){this._log.warn(sN)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)r.push(255);r.push(n);let o=new DataView(e);return r.push(...new Uint8Array(o.buffer)),r.push(128),new Xx(new DataView(new Uint8Array(r).buffer),!0)}},Zx=0,eV=!1,tV=new Set,iV=!1,nV=class{constructor(e){rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_isErrorObserved",!1),rb(this,"_waitForPeerConnectionConnectedPromise"),rb(this,"_waitForPeerConnectionConnectedPromiseReject",null),rb(this,"_peerConnection",null),rb(this,"_emitter",new Qx.default),rb(this,"_currentState","DISCONNECTED"),rb(this,"_isReconnecting",!1),rb(this,"_reconnectionCount",0),rb(this,"_reconnectionTimer",-1),rb(this,"_isFirstConnection",!0),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),rb(this,"_localAddress"),rb(this,"_remoteAddress"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=jO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Nw&&(this._sei=new $x(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=mO())}afterConnect(e){return sb(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(mO()-this._prevTime,3e4)})):this._isReconnecting&&UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:mO()-this._prevTime}),this._prevTime=-1}catch(oN){throw this._isFirstConnection?(this._isFirstConnection=!1,UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:oN})):this._isReconnecting&&this._reconnectionCount>=3&&UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:oN}),oN}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&Nw,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),tV.delete(this)}closePeerConnection(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new fb({code:_b.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return eD;let e=null;if(this._isUplink){if(!Sw()||0===this._peerConnection.getSenders().length)return eD;e=this._peerConnection.getSenders()[0].transport}else{if(!Ew()||0===this._peerConnection.getReceivers().length)return eD;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:eD}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(i)),e.target.connectionState===tD.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===tD.FAILED||e.target.connectionState===tD.CLOSED){let n="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),r=new fb({message:n,code:_b.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",r)}(e.target.connectionState===tD.CONNECTED||e.target.connectionState===tD.COMPLETED)&&(this.logSelectedCandidate(),Xw.logSuccessEvent({userId:this._room.userId,eventType:aD.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(Zx=0,eV=!1,iV=!0,tV.add(this)):tV.delete(this),UO.emit(BO.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(hw(t)){let i=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{UO.off(BO.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{r();let e=new fb({code:_b.API_CALL_TIMEOUT,message:"connection timeout"});Zx+=1,(e=>Zx>2&&!eV&&0===tV.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),eV=!0,this._emitter.emit("firewall-restriction")),t(e)}),ED);UO.on(BO.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ox,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=rD()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new fb({code:this._isUplink?_b.UPLINK_RECONNECTION_FAILED:_b.DOWNLINK_RECONNECTION_FAILED,message:QO({key:this._isUplink?KO.UPLINK_RECONNECTION_FAILED:KO.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(ox,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"))}},rV=ib(ub()),oV=function(e){return rV.default.parse(e)},sV=function(e){return rV.default.write(e)};function aV(e){return Object.keys(e).filter((t=>e[t]))}var cV=class extends nV{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,auxiliary:0}),rb(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new PM(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new MM(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new LM(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 SO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===PN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===GN?PN.MAIN:PN.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=PN.AUDIO;i.kind===PN.VIDEO&&(r=n===PN.MAIN?PN.VIDEO:PN.AUXILIARY);let o=this.remoteAudioTrack;r===PN.VIDEO?o=this.remoteVideoTrack:r===PN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let n=[...i];for(let r=0;r<n.length;r++){let[e,i]=n[r];t.splice(e+r,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=oV(e);return t.media.forEach((e=>{e.type===PN.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),sV(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=oV(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),sV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===tD.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===tD.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else this.initialize(),yield this.connect(e)}catch(aN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(aN.message," ").concat(JSON.stringify(this.muteState))),new fb({code:_b.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):aN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(n," stream already unsubscribed"));let e=$C({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let r="subscribe_change";Object.values(e).find((e=>!0===e))||(r="unsubscribe"),t._log.info("".concat("unsubscribe"===r?r:"subscribe"," ").concat(n," [").concat(aV(e),"]")),yield t.sendSubscription(r,e),"unsubscribe"===r&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Ex,r=lx.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Sx,r=lx.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:QO({key:KO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(t),yield e.waitForPeerConnectionConnected()}catch(oD){throw e.closePeerConnection(!0),oD}}()}))}exchangeSDP(e){return sb(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:Tx,commandDesc:"exchange sdp",data:n,responseCommand:lx.SUBSCRIBE_RESULT,timeout:dD});if(!this._peerConnection){let e=new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(r),this._isSDPExchanging=!1}catch(oD){throw this._isSDPExchanging=!1,oD}}))}createOffer(){return sb(this,null,(function*(){let e={voiceActivityDetection:!1};vw()&&this._sdpSemantics===uD?(this._peerConnection.addTransceiver(PN.AUDIO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:MN.RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:MN.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield aw();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=oV(e);return t.media.forEach((e=>{var t,i;if(e.type===PN.VIDEO){let n=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&n.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t)}));let r=e=>{let{payload:t}=e;return!n.has(t)};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!n.has(Number(e)))).join(" ")}})),sV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=oV(e);return t.media.forEach((e=>{e.type===PN.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),sV(t)}(t.sdp),this._sdpSemantics===uD&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return sb(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===pD)throw new fb({code:_b.NOT_SUPPORTED_H264,message:QO({key:KO.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new fb({code:t,message:QO({key:KO.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",ZC($C({},e),{userId:this.userId}))}),this.updateSSRC(r)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{oV(e).media.forEach((e=>{if(e.ssrcs)if(e.type===PN.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(GN)}));t&&(this.ssrc.audio=Number(t.id))}else{let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(GN)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(WN)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(oD){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return sb(this,null,(function*(){if(!(ob(cV.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(oD){let t=ZD(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}},lV=cV;nb([rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],lV.prototype,"subscribe",1),nb([nM(nV.prototype.afterConnect),iM(nV.prototype.beforeConnect)],lV.prototype,"connect",1);var dV=lV,uV={voiceActivityDetection:!1},hV=class extends nV{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Iw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===PN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),vw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==n?void 0:n.outMediaTrack,a=t._audioManager.mixedAudioTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||PN.AUDIO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?PN.VIDEO:s||PN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||PN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||PN.VIDEO,{direction:MN.SENDONLY,streams:[e]}),yield t.connect();else{let e=[];if(a&&(c[0].sender.track||e.push(0),yield c[0].sender.replaceTrack(a),yield t.setBandwidth({bandwidth:(null==i?void 0:i.profile.bitrate)||40,type:PN.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:PN.VIDEO,videoType:o?PN.AUXILIARY:PN.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:PN.VIDEO,videoType:PN.SMALL}),e.push(2))}yield t.setTransceiverDirection(MN.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==n||n.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info("publish by addtrack");let e=null==n?void 0:n.outMediaTrack,o=t._audioManager.mixedAudioTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream;e.addTrack(r),t._peerConnection.addTrack(r,e)}yield t.connect()}()}))}enableSmall(e){return sb(this,null,(function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(MN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(MN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!Iw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent("DISCONNECTED",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:fx,data:t,responseCommand:lx.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:gx,commandDesc:"unpublish",responseCommand:lx.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===_b.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),bw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Nx,data:this._mediaSettings,responseCommand:lx.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?PN.AUXILIARY:PN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),vw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Iw()&&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)}let n=t.kind===PN.VIDEO?t:this._audioManager.mixedAudioTrack;if(n&&this._peerConnection.addTrack(t,new MediaStream([n])),t.kind===PN.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===hD||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=oV(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===PN.VIDEO)return!0;return!1}removeSender(e){let t=null;Iw()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&tO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?PN.AUXILIARY:PN.MAIN," stream")),vw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(MN.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Vb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(MN.INACTIVE,"|").concat(MN.RECVONLY,"|").concat(MN.SENDONLY,")")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes("a=".concat(MN.RECVONLY)))return n=!0,"a=".concat(e);if(e===MN.SENDONLY&&i.includes("a=".concat(MN.INACTIVE)))return n=!0,"a=".concat(MN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return sb(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===PN.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let t=this._peerConnection.getSenders().find((t=>t.track===e.outMediaTrack));t&&(this.removeSender(t),e.kind===PN.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===PN.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=vw()?e.kind===PN.AUDIO?n[0]:n[1]:n.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(r?PN.AUXILIARY:PN.MAIN," stream")),e.kind===PN.AUDIO?yield i.replaceTrack(this._audioManager.mixedAudioTrack):e.kind===PN.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return sb(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(uV);Vb&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===PN.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:dx,data:r,responseCommand:lx.UPDATE_OFFER_RESULT,timeout:lD,commandDesc:"update offer"}),{code:s,message:a}=o.data;0!==s&&this.checkPublishResultCode(s,a),yield this.acceptAnswer(o.data.data),i.sdp&&this.updateSSRC(i.sdp)}catch(sN){throw this._log.error(sN),sN}}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!Cw())return o?n===PN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(vw()){let t=0;n===PN.VIDEO&&(t=r===PN.SMALL?2:r===PN.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===n));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(r||"").concat(n," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return n===PN.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let n="AS";Vb&&(n="TIAS",t*=1e3);let r=0,o=-1;return i===PN.SMALL?r=1:i===PN.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===r?"".concat(e,"b=").concat(n,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return Vb&&(i="TIAS",t*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(i,":").concat(t,"\r\n"))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return sb(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(oN){throw this.closePeerConnection(!0),this.uninstallEvents(),oN}}))}exchangeSDP(){return sb(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(oN){throw oN}}))}createOffer(){return sb(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(uV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(oN){throw oN}}))}doExchangeSDP(){let e={command:mx,responseCommand:lx.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof _M||this.localAuxVideoTrack instanceof _M,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",n=oV(e);return n.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),sV(n)}acceptAnswer(e){return sb(this,null,(function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?PN.AUXILIARY:PN.BIG;s=yield this.setBandwidth({bandwidth:e,type:PN.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:PN.AUDIO,sdp:s}))}if(s=this.removeVideoOrientation(e.sdp),null!=(o=this._publishingLocalVideoTrack)&&o.small){let{smallStreamConfig:e}=this._room;s=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||e.bitrate,type:PN.VIDEO,videoType:PN.SMALL,sdp:s})}let a={type:e.type,sdp:s};yield this._peerConnection.setRemoteDescription(a),this._log.debug("accepted answer: ".concat(s))}catch(rU){throw this._log.error("failed to accept remote answer ".concat(rU)),rU}}))}sendMutedFlag(e){var t,i,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info("send muted state: ".concat(JSON.stringify(r))),this._signalChannel.send(_x,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return sb(this,null,(function*(){if(!(ob(hV.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:gx,responseCommand:lx.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(oD){let t=ZD(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)&&UO.emit(BO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{oV(e).media.forEach(((e,t)=>{if(e.type===PN.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===hD&&e.ssrcGroups)return void e.ssrcGroups.forEach(((e,t)=>{let i=Number(e.ssrcs.split(" ")[0]);0===t?this.ssrc.video=i:1===t&&(this.ssrc.small=i)}));let i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(t){case 1:this.ssrc.video=Number(i.id);break;case 2:this.ssrc.small=Number(i.id);break;case 3:this.ssrc.auxiliary=Number(i.id)}}}))}catch(oD){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:PN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===PN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===PN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===PN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===PN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===pD?(this._log.error(YO.NOT_SUPPORTED_H264ENCODE),new fb({code:_b.NOT_SUPPORTED_H264,message:QO({key:KO.NOT_SUPPORTED_H264ENCODE})})):new fb({code:_b.UNKNOWN,message:QO({key:KO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lx.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},pV=hV;nb([rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],pV.prototype,"publish",1),nb([nM(nV.prototype.afterConnect),iM(nV.prototype.beforeConnect)],pV.prototype,"connect",1);var _V=pV,mV=class{constructor(e,t){this.room=e,rb(this,"_log"),rb(this,"_prevReportTime"),rb(this,"_prevReport",{}),rb(this,"_prevEncoderImplementation"),rb(this,"_prevQualityLimitationReason"),rb(this,"_prevAuxQualityLimitationReason"),rb(this,"_prevDecoderImplementationMap",new Map),rb(this,"totalBytesSent",0),rb(this,"totalBytesReceived",0),rb(this,"_spcStats",null),this._log=t,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevAuxQualityLimitationReason=""}get statInterval(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return sb(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var r;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===PN.VIDEO){let r,o;if(i.ssrc===n.video?(r=PN.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=PN.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=PN.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,iO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),iO(i.nackCount)||(t[r].nackCount=i.nackCount),iO(i.pliCount)||(t[r].pliCount=i.pliCount),iO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),iO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),iO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!iO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!iO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!iO(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?hw(i)&&rO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===PN.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===PN.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(PN.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(PN.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!iO(i.audioLevel)&&(null==(r=e.localMainAudioTrack)?void 0:r.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!iO(i.frameWidth)){let r=PN.SMALL;i.trackIdentifier===e.getVideoTrackId(PN.VIDEO)||i.ssrc===n.video?r=PN.VIDEO:(i.trackIdentifier===e.getVideoTrackId(PN.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=PN.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(r){this._log.warn("failed to getStats on sender connection ".concat(r))}return t}))}getReceiverStats(e){return sb(this,null,(function*(){let t={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===PN.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0}else{if(Vb&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===n.auxiliary&&r.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&hw(i)&&rO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);iO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!iO(i.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&i.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0)})),0===t.audio.audioLevel&&e.muteState.audioAvailable&&(t.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=t.audio.bytesReceived+t.video.bytesReceived+t.auxiliary.bytesReceived)}catch(sN){this._log.warn("failed to getStats on receiver connection ".concat(sN))}return t}))}getStats(e,t){return sb(this,null,(function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&r.push(e))),this._spcStats=r}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e)}return{senderStats:i,receiverStats:n}}))}getDifferenceValue(e,t){if(UP(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!UP(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*xD,uint32_audio_energy:1e6*t.senderStats.audio.totalAudioEnergy,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(e.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*xD);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e)}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r}}let{statInterval:r}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=n.get("".concat(e.userId,"_").concat(JN)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=n.get("".concat(e.userId,"_").concat(KN)),r=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),pk&&115===Ok()&&0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),iO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),iO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),iO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),iO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),iO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),iO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r))}));let a=i.msg_down_stream_info,c=o.msg_down_stream_info;return a.forEach((e=>{let t=c.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(UP(e.msg_audio_status)||UP(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status;i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let o=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/r),i.uint32_audio_total_bitrate=Math.round(8*o/r)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r)}))}}})),i}getStatsReport(e){return sb(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,n);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},fV=ib(ab()),gV=class extends fV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_log"),rb(this,"_uplinkRTT",0),rb(this,"_uplinkLoss",0),rb(this,"_downlinkRTT",0),rb(this,"_downlinkLoss",0),rb(this,"_downlinkPrevStatMap",new Map),rb(this,"_downlinkLossAndRTTMap",new Map),rb(this,"_interval",-1),rb(this,"_uplinkNetworkQuality",0),rb(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=jO.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(lx.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(rx,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return sb(this,null,(function*(){if(0===this._room.remotePublishedUserMap.size)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],t=e.filter((e=>{var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===tD.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r<t.length;r++){let e=t[r].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:n,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=n-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[r].getUserId(),audioDelay:t[r].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[r].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i)}))}getStat(e){return sb(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Ew())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&&rO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===PN.AUDIO||e.mediaType===PN.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(n){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==tD.DISCONNECTED&&e.connectionState!==tD.FAILED&&e.connectionState!==tD.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=qw.run(OD,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];UO.emit(BO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(gV.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&&(qw.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r})}}))}},TV=gV;rb(TV,"EVENT_NETWORK_QUALITY","0");var EV=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._apiSuccessRateMap=new Map,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=jO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&tO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];let o=t.apply(i,n);return dO(o)?o.catch((e=>jO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(oD){jO.error("".concat(t.name,"() error observed ").concat(oD))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=qw.run(OD,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return"".concat(this._keyPrefix,"_").concat(this._room.userId)}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:nN,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:bN[jD()],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,this._apiSuccessRateMap.clear(),Xk().then((e=>{this._basicInfo.string_os_version=eN(),e&&(this._basicInfo.string_device_name=e.model)}))}addEvent(e,t){return this._eventMap.set(e,t),UO.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(BO.JOIN_START,this.handleJoinStart).addEvent(BO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(BO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(BO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(BO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(BO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(BO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(BO.JOIN_FAILED,this.handleJoinFailed).addEvent(BO.LEAVE_START,this.handleLeaveStart).addEvent(BO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(BO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(BO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(BO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(BO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(BO.PUBLISH_START,this.handlePublishStart).addEvent(BO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(BO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(BO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(BO.PLAY_TRACK_START,this.handlePlayStart).addEvent(BO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(BO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:n}=e;!lO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(n===PN.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(BO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(BO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(BO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(BO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(n.userId,"auxiliary")})).addEvent(BO.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(BO.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)=>UO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),qw.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&&(iO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),iO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),iO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof fb?Number(i.getExtraCode()||i.getCode()):_b.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let n="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:ZC($C({},vV),{msg_user_info:new yV({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(n,r)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new yV({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===n?(i.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!lO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!lO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/xD*100)>0&&(this._localStreamStat.totalAudioLevel+=e/xD,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n="".concat(r,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*QC(10,6)))}})),i){let e="".concat(r,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/xD*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/xD,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof fb?i.getExtraCode()||i.getCode():_b.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate(e){let{room:t,apiName:i,error:n,cost:r}=e;if(!this.hitTest(t))return;let o=AV[i],s={uint32_function_request_type:o,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(n){let e=n.extraCode||n.code||_b.UNKNOWN;Xw.logFailedEvent({eventType:i,code:e,userId:this._room.userId,error:n});let t={int32_error_code:e,error_count:1};s.msg_error_code.push(t)}else rO(r)&&(Xw.logSuccessEvent({eventType:i,userId:this._room.userId}),s.uint32_avg_value=r,s.uint32_max_value=r,s.uint32_success_count=1);let a=this._apiSuccessRateMap.get(o);a?(a.uint32_success_count+s.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+s.uint32_avg_value)/(a.uint32_success_count+s.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,s.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+s.uint32_success_count,s.msg_error_code.forEach((e=>{let t=a.msg_error_code.find((t=>t.int32_error_code===e.int32_error_code));t?t.error_count+=1:a.msg_error_code.push(e)}))):this._apiSuccessRateMap.set(o,s)}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&VN))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&BN))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&FN))>=0}hitTest(e){return e===this._room}checkStorage(){return sb(this,null,(function*(){try{let e=WO.getItem(this._storageKey);e&&(yield this.upload(e),WO.deleteItem(this._storageKey))}catch(qM){this._log.warn(qM)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&WO.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,PN.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,PN.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,IV);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>IV&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+IV):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>IV&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+IV):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>IV&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+IV)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new yV({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:yO(this._signalInfo.relayIp),uint32_client_ip:yO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(2147483648*Math.random()),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:yO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){try{this.prepareReport();let e=this.getReportData();this.upload(e),WO.deleteItem(this._storageKey),this.initData()}catch(qM){this._log.warn(qM)}}upload(e){if(Kk&&!Ek||0===e.msg_path_enter_room.uint64_start_time||[pN,_N,mN].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=FD(t,vN.KEY_POINT),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(i,JSON.stringify(e))),n||MO({url:i,body:JSON.stringify(e)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}};nb([Vx({settings:{timeout:500,retries:3}})],EV.prototype,"upload",1);var SV,IV=5e3,vV={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},yV=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},AV=((SV=AV||{})[SV.enterRoom=50001]="enterRoom",SV[SV.exitRoom=50002]="exitRoom",SV[SV.switchRole=50003]="switchRole",SV[SV.destroy=50004]="destroy",SV[SV.startLocalAudio=50005]="startLocalAudio",SV[SV.updateLocalAudio=50006]="updateLocalAudio",SV[SV.stopLocalAudio=50007]="stopLocalAudio",SV[SV.startLocalVideo=50008]="startLocalVideo",SV[SV.updateLocalVideo=50009]="updateLocalVideo",SV[SV.stopLocalVideo=50010]="stopLocalVideo",SV[SV.startScreenShare=50011]="startScreenShare",SV[SV.updateScreenShare=50012]="updateScreenShare",SV[SV.stopScreenShare=50013]="stopScreenShare",SV[SV.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",SV[SV.startRemoteVideo=50015]="startRemoteVideo",SV[SV.updateRemoteVideo=50016]="updateRemoteVideo",SV[SV.stopRemoteVideo=50017]="stopRemoteVideo",SV[SV.muteRemoteAudio=50018]="muteRemoteAudio",SV[SV.setRemoteAudioVolume=50019]="setRemoteAudioVolume",SV[SV.startMixTranscode=50020]="startMixTranscode",SV[SV.stopMixTranscode=50021]="stopMixTranscode",SV[SV.startPublishCDNStream=50022]="startPublishCDNStream",SV[SV.stopPublishCDNStream=50023]="stopPublishCDNStream",SV[SV.PeerConnectionConnect=50024]="PeerConnectionConnect",SV[SV.PeerConnectionReconnect=50025]="PeerConnectionReconnect",SV[SV.WebsocketConnect=50026]="WebsocketConnect",SV[SV.WebsocketReconnect=50027]="WebsocketReconnect",SV[SV.schedule=50028]="schedule",SV[SV.SPCConnect=50029]="SPCConnect",SV[SV.SPCReconnect=50030]="SPCReconnect",SV[SV.videoCtxGl=50031]="videoCtxGl",SV[SV.videoCtxGlRecover=50032]="videoCtxGlRecover",SV[SV.videoCtx2d=50033]="videoCtx2d",SV[SV["CDNStreaming.startPlugin"]=50034]="CDNStreaming.startPlugin",SV[SV["CDNStreaming.updatePlugin"]=50035]="CDNStreaming.updatePlugin",SV[SV["CDNStreaming.stopPlugin"]=50036]="CDNStreaming.stopPlugin",SV[SV["AIDenoiser.startPlugin"]=50037]="AIDenoiser.startPlugin",SV[SV["AIDenoiser.updatePlugin"]=50038]="AIDenoiser.updatePlugin",SV[SV["AIDenoiser.stopPlugin"]=50039]="AIDenoiser.stopPlugin",SV[SV["AudioMixer.startPlugin"]=50040]="AudioMixer.startPlugin",SV[SV["AudioMixer.updatePlugin"]=50041]="AudioMixer.updatePlugin",SV[SV["AudioMixer.stopPlugin"]=50042]="AudioMixer.stopPlugin",SV),RV=EV,CV=class{constructor(){rb(this,"_startTime"),rb(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=mO())}stop(){0===this._endTime&&(this._endTime=mO())}getDuration(){return 0===this._endTime?mO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},bV=class{constructor(e){rb(this,"_room",null),rb(this,"_durationMap"),rb(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(BO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(BO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(BO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),PN.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),PN.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),PN.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,PN.AUDIO,"main"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,PN.VIDEO,"main"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,PN.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>UO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>UO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);if(n.muteState.hasAudio&&"main"===i)if(n.remoteAudioTrack.isSubscribed){let e=new CV,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,PN.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new CV,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,PN.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDurationItem(o,PN.AUDIO),this.stopDurationItem(o,PN.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let n="".concat(e,"_").concat(i),r=new CV,o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===PN.AUDIO?[r]:[],video:t===PN.AUDIO?[]:[r]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},kV=class{constructor(e){rb(this,"_room"),rb(this,"_renderFreezeMap",new Map),rb(this,"_isVideoPlayingEventFiredMap",new Map),rb(this,"_dataFreezeMap",new Map),rb(this,"_monitorFreezeData",new Map),rb(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(BO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(BO.PLAY_TRACK_START,this.onPlayTrackStart).set(BO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDataFreeze({key:o,userId:r,type:i})})).set(BO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e="main",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}if(i.hasAuxiliary&&!n.hasAuxiliary){let e="auxiliary",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}})).set(BO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:n,type:r}=e;if(lO(t)&&this.hitTest(t.room)&&r===PN.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}n===PN.MUTE?this.onVideoTrackMuted(t):n===PN.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(BO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>UO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>UO.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i),r=this._dataFreezeMap.get(n),o=new CV;r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i);this.stopDataFreeze({key:n,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:n}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>mD?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return sb(this,arguments,(function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e="".concat(i,"_").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=mO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=mO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!lO(t)||!this.hitTest(t.room)||t.kind!==PN.VIDEO||t.hasFlag)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let e=i.durationItemList[i.durationItemList.length-1];e.stop(),e.getDuration()<mD&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,n=0;if(t)if(t.isFreeze){let e=mO()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),n=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},NV=ib(ab(),1),DV=[-1,-1,1,-1,-1,1,1,1],OV=[0,0,1,0,0,1,1,1],wV=class extends Ww{constructor(e,t){if(super(),this.context=e,rb(this,"name"),rb(this,"input"),rb(this,"output"),rb(this,"texture"),rb(this,"image"),rb(this,"ctx2d",null),rb(this,"fbo"),rb(this,"width",0),rb(this,"height",0),rb(this,"x",0),rb(this,"y",0),rb(this,"program"),rb(this,"vertexShader"),rb(this,"fragmentShader"),rb(this,"totalFrames",0),rb(this,"dropFrames",0),rb(this,"matchInputSize",!0),rb(this,"texCoordBuffer"),rb(this,"positionBuffer"),rb(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),rb(this,"cost",0),rb(this,"_canvas",null),this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,e instanceof GV){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(OV),this.positionBuffer=this.createBuffer(DV),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(sN){this.context.destroy(sN)}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof jV&&this.render(e)||this.context instanceof GV&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof jV){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:c,fps:l,name:s,cost:a},$C({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};nb([Hw(Ww.INIT,"connected",{sync:!0})],wV.prototype,"connect",1),nb([Hw("connected",Ww.INIT,{ignoreError:!0,sync:!0})],wV.prototype,"disconnect",1),nb([Hw([],"closed",{sync:!0})],wV.prototype,"close",1);var PV=[0,1,1,1,0,0,1,0],MV=class extends wV{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),rb(this,"_intervalId",0),rb(this,"_sequence",0),rb(this,"checkGLError",!1),e instanceof GV?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(PV)}start(e){this._intervalId=qw.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(qw.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof jV){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),qw.clearTask(this._intervalId)}},LV=class extends MV{constructor(e,t){super(e,t),rb(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,n)},n=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,n)};e instanceof jV&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},xV=class extends LV{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},VV=class extends LV{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;jO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>r?i=n/r:(jO.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},UV=class extends wV{constructor(e,t,i){super(e,$C({name:"imageSource"},i)),this.image=t,rb(this,"_image"),rb(this,"_totalFrames",0),rb(this,"_autoResize",!1),this._autoResize=!1!==(null==i?void 0:i.autoResize)}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(tO(this.image.getVideoPlaybackQuality)&&!Uk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:i,videoHeight:n}=this.image),this.image.width=i,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);if(!this._autoResize)return!0;if(this.width===i&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},FV=class extends UV{constructor(e,t,i){super(e,document.createElement("video"),i),this._videoTrack=t,rb(this,"_mediaStream"),this.name="videoTrackSource",this._mediaStream=new MediaStream([t]),this.image.srcObject=this._mediaStream,this.image.play()}replaceTrack(e){var t,i;this._videoTrack!==e&&(null==(t=this._mediaStream)||t.removeTrack(this._videoTrack),this._videoTrack=e,null==(i=this._mediaStream)||i.addTrack(this._videoTrack),this.image.play())}close(){var e;super.close(),null==(e=this._mediaStream)||e.removeTrack(this._videoTrack),delete this._mediaStream,this.image.srcObject=null}},BV=class extends Ww{constructor(e){super(),rb(this,"frameRate"),rb(this,"_canvas"),rb(this,"log"),rb(this,"hasAlpha",!1),rb(this,"name"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e){return new FV(this,e)}createVideoTrackDestination(e){return new LV(this,e)}createVideoImageSource(e,t){return new UV(this,e,t)}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},HV={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},jV=class extends BV{constructor(){super(...arguments),rb(this,"defaultProgam"),rb(this,"defaultVShader"),rb(this,"defaultFShader"),rb(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",HV),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}createProgram(e,t){let i=this.ctx,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),i.getProgramParameter(n,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(n)),n}};nb([Hw(Ww.INIT,"created",{sync:!0})],jV.prototype,"create",1),nb([Hw("created",Ww.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],jV.prototype,"destroy",1);var GV=class extends BV{constructor(){super(...arguments),rb(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};nb([Hw(Ww.INIT,"created",{sync:!0})],GV.prototype,"create",1),nb([Hw("created",Ww.INIT,{ignoreError:!0,sync:!0})],GV.prototype,"destroy",1);var WV=[1,0,0,0,1,1,0,1],JV=class extends wV{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof jV)try{this.setTexBuffer(WV)}catch(oN){e.destroy(oN)}else this.ctx2d&&setTimeout((e=>{e.scale(-1,1),e.translate(-this.width,0)}),0,this.ctx2d)}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},KV=class{constructor(e,t){this.node=e,this.layout=t,rb(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},YV=class extends wV{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),rb(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new KV(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 jV&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:n,height:r,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:s,fps:a,name:o},$C({parent:this.inputs.filter((e=>e)).map((e=>e.node.getInfo()))},this.lastInfo)}close(){super.close(),this.inputs.forEach((e=>{var t,i;if(e&&(null==(t=e.node)||t.disconnect(),e.positionBuffer&&this.context instanceof jV))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(n){}}))}},zV=class{constructor(e,t){this.createMediapipeSolutionsWasm=t,rb(this,"canvas"),rb(this,"locateFile"),rb(this,"_glName"),rb(this,"_solutionWasm"),rb(this,"ctx"),rb(this,"pl",{onResults:e=>this.onResults(e.get(0).glName)}),this.locateFile=t=>"".concat(e,"/").concat(t)}bindTexture(){var e;null==(e=this.ctx)||e.activeTexture(this.ctx.TEXTURE0),this.bindTexture2d(this._glName)}initialize(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"selfie_segmentation_landscape.tflite";return sb(this,null,(function*(){yield this.createMediapipeSolutionsWasm(this),this.canvas=e,this.createContext(e,!0,!0,{}),this._glName=this.createTexture(),this._solutionWasm=new this.SolutionWasm;let i=new this.StringList;i.push_back("segmentation_mask");let n=this.PacketListener.implement(this.pl);this._solutionWasm.attachMultiListener(i,n),i.delete(),this._solutionWasm.loadGraph(yield fetch(this.locateFile("selfie_segmentation.binarypb")).then((e=>e.arrayBuffer()))),this._solutionWasm.overrideFile("third_party/mediapipe/modules/selfie_segmentation/selfie_segmentation_landscape.tflite",yield fetch(this.locateFile(t)).then((e=>e.arrayBuffer())));let r=new this.GraphOptionChangeRequestList;return r.push_back({calculatorIndex:1,calculatorName:"",calculatorType:"GlScalerCalculator",fieldName:"flip_horizontal",valueBoolean:!1,valueNumber:0,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value",valueBoolean:!1,valueNumber:1,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"InferenceCalculator",calculatorName:"",fieldName:"use_cpu_inference",valueBoolean:!1,valueNumber:0,valueString:""}),this._solutionWasm.changeOptions(r),this}))}send(e,t){let i=new this.PacketDataList;i.pushTexture2d({stream:"input_frames_gpu",timestamp:1e3*performance.now(),glName:this._glName,width:e,height:t}),this._solutionWasm.send(i),i.delete()}close(){var e,t,i;null==(e=this.canvas)||delete e.getContext,delete this.readyPromiseResolve,delete this.readyPromiseReject,this.pl.onResults=null,delete this.onResults,null==(t=this.deleteTexture)||t.call(this,this._glName),null==(i=this._solutionWasm)||i.delete();for(let n of Object.keys(this))delete this[n]}},qV=class extends FV{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0}),rb(this,"ready",!1),rb(this,"_bgTexture"),rb(this,"_waterMarkTexture"),rb(this,"_lastMaskTexture"),rb(this,"_textureValid",!1),rb(this,"_selfieTextureValid",!1),rb(this,"_selfieSegmentation"),rb(this,"wasm"),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return sb(this,null,(function*(){let t=yield e.Wasm(),i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:n,height:r}=e.waterMark;this.wasm.setWaterMark(t,i,n,r)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._selfieSegmentation=yield e.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.ready=!0}))}onPredict(e){let t=this.context.ctx;this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image)),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,0==(1&this.totalFrames)?this._lastMaskTexture:this.texture),t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,this.width,this.height),this.useProgram(),this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.activeTexture(t.TEXTURE4),t.bindTexture(t.TEXTURE_2D,0!=(1&this.totalFrames)?this._lastMaskTexture:this.texture),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:n}=this.image;this.image.width=i,this.image.height=n;let r=!1;if(this.totalFrames)this._selfieSegmentation.bindTexture(),r=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),r=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===n&&r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&this._selfieSegmentation.send(i,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),null==(e=this.wasm)||e.close()}},QV=class extends NV.EventEmitter{constructor(e){let{room:t}=e;super(),rb(this,"videoContext"),rb(this,"_glVideoContext"),rb(this,"_2dVideoContext"),rb(this,"destination"),rb(this,"smallVideoContext"),rb(this,"smallDestination"),rb(this,"smallTrackSource"),rb(this,"smallImageSource"),rb(this,"_isMirror",!1),rb(this,"cameraTrack"),rb(this,"cameraNode"),rb(this,"waterMarkNode"),rb(this,"mirrorNode"),rb(this,"mixNode"),rb(this,"screenTrack"),rb(this,"screenNode"),rb(this,"selfModel",!1),rb(this,"blurRadius",3),rb(this,"Wasm"),rb(this,"_isMixScreen",!1),rb(this,"_hasWaterMark",!1),rb(this,"_virualBackground"),rb(this,"_bgAssetPath"),rb(this,"_log"),rb(this,"_checkId",0),rb(this,"_room"),rb(this,"_use2d",!1),rb(this,"_autoSwitchRenderMode",!0),rb(this,"_waterMarkOption"),rb(this,"_selfieSegmentation"),this._room=t,this._log=jO.createLogger({id:"vm",userId:t.userId,sdkAppId:t.sdkAppId}),this.smallVideoContext=new GV({frameRate:15,logger:this._log,name:"s"}),this.enablePrintDetail()}get _hasVirualBg(){return!!this._virualBackground}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 GV({frameRate:15,logger:this._log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new jV({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),UO.emit("262",{room:this._room,apiName:"videoCtxGl",error:t||new Error(e)}),this.update()}))}catch(oN){this.emit("error",{reason:"create",error:oN}),this.sendCreateResult("videoCtxGl",oN)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=qw.run(PD,(()=>{this.destination&&this._log.debug(this.destination.getInfo())}),{delay:e})}destroy(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),qw.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirualBg}get active(){return(Wk&&Gk||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl",t=arguments.length>1?arguments[1]:void 0;UO.emit("262",{room:this._room,apiName:e,error:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){if(!this._selfieSegmentation){let t=new zV(e.assetPath||"./selfie_segmentation",e.createMediapipeSolutionsWasm),i=this.getGlVideoContext();return i.available?this._selfieSegmentation=t.initialize(i._canvas,"selfie_segmentation_landscape.tflite"):Promise.reject(new Error("init virtual background failed, reason: video context unavailable"))}return this._selfieSegmentation}_setMainOutput(e){var t;let i=this.cameraTrack,{small:n,settings:r}=i;return n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new VV(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=r.width,this.smallTrackSource.height=r.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),i.setOutputMediaStreamTrack(e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack)}update(){return sb(this,null,(function*(){var e,t;if(this.cameraTrack&&this.cameraTrack.mediaTrack){if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this._use2d||!this._selfieSegmentation?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new xV(this.videoContext,{name:"mainDestination"})),this.cameraNode=new qV(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate}if(this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new JV(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 YV(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.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this._log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)}}))}changeInput(e,t){return this._log.info("change input"),e instanceof _M?this.setScreenTrack(e):e instanceof hM?this.setCameraTrack(e):e instanceof MM?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){var t;e instanceof _M?(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))}setCameraTrack(e){return sb(this,null,(function*(){this.cameraTrack=e,this.update()}))}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}loadImage(e){return new Promise(((t,i)=>{let n=new Image;n.crossOrigin="anonymous",n.src=e,n.onload=()=>t(n),n.onerror=i}))}setWatermark(e){return sb(this,null,(function*(){let t=(null==e?void 0:e.imageElement)||(yield this.loadImage(e.imageUrl)),{x:i=0,y:n=0,width:r=t.width,height:o=t.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:i,y:n,width:r,height:o,image:t},this._log.info("start watermark",JSON.stringify({x:i,y:n,width:r,height:o})),this.update()}))}stopWatermark(){var e;!this._hasWaterMark||(this._hasWaterMark=!1,this._log.info("stop watermark"),null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption,this.update())}setVirtualBackground(e){return sb(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virualBackground=yield this.loadImage(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virualBackground=e.type)}else this._virualBackground=void 0;this._log.info("".concat(this._virualBackground?"start":"stop"," visual background, ").concat((null==e?void 0:e.type)||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},XV=0,$V=class extends Ww{constructor(e){super("room"),this.seq=++XV,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=jO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,oO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),oO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),oO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new RV({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new bV({room:this}),this.badCaseDetector=new kV({room:this}),this.audioManager=new DM({room:this}),this.videoManager=new QV({room: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 isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return sb(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return sb(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return sb(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(nO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(XD(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(Wx([o,o]),hN("https://".concat(o))):(n&&hN(n),r&&Wx(r))}UO.once(BO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:Gx.main,sched_back_domain:Gx.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return sb(this,null,(function*(){var e;let t={rtt:(null==(e=this.quality)?void 0:e.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let i of this.quality.downlinkInfo)t.downlinksRTT[i.userId]=i.rtt;return t}))}getRemoteVideoStats(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let n="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(YO.INVALID_DESTROY),new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.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,UO.emit(BO.ROOM_DESTROY,{room:this})}schedule(e,t){return sb(this,null,(function*(){var i,n;let r=mO();try{let{isCached:o,result:s,detailCost:a}=yield jx({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:nN,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(NO(s,{keysToExclude:["username","credential"]}))),o&&UO.once(BO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=$C($C({},this.scheduleResult),s),rO(null==(i=s.config)?void 0:i.retryCount)&&nD(s.config.retryCount),nO(null==(n=s.config)?void 0:n.loggerDomain)&&hN(s.config.loggerDomain),UO.emit(BO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),UO.emit(BO.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:mO()-r})}catch(o){throw UO.emit(BO.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:o}),o}}))}},ZV=ib(ab()),eU=ib(ub()),tU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=oV(n),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:PN.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:o.media[0].port,protocol:o.media[0].protocol,type:PN.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((e=>({payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}))),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return s.media.push(a),[1,2,3].forEach((e=>{s.media.push(iU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),r&&s.media.push(o.media.find((e=>"dc"===e.mid))),sV(s)},iU=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:PN.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:PN.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(i.video.codecs.length>0)if(o)for(let a=0;a<i.video.codecs.length;a++)nU(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));nU(s,i.video.codecs[e])}else if(o)for(let a=0;a<n.video.codecs.length;a++)nU(s,n.video.codecs[a]);else nU(s,n.video.codecs[0]);return s.payloads=s.payloads.trim(),s},nU=(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 rU,oU=e=>{let t=eU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===PN.AUDIO||e.type===PN.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===PN.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===PN.AUDIO&&e.fmtp&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){let t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}(e)),(null==(i=e.payloads)?void 0:i.includes("datachannel"))&&t.groups&&e.mid&&(t.groups[0].mids=t.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),eU.default.write(t)},sU=((rU=sU||{}).TRACK="track",rU.DATA_CHANNEL_MESSAGE="data_channel_msg",rU[rU.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",rU[rU.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",rU.RECONNECTED="spc-reconnected",rU.RECONNECT_FAILED="spc-reconnect-failed",rU.ERROR="error",rU.SEI_MESSAGE="sei-message",rU),aU=0,cU=!1,lU=new Set,dU=1,uU=class extends ZV.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),rb(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),rb(this,"currentState","DISCONNECTED"),rb(this,"_room"),rb(this,"_signalChannel"),rb(this,"_peerConnection",null),rb(this,"_datachannel",null),rb(this,"_enableCustomMessage"),rb(this,"_log"),rb(this,"_downlinkMIDMap",new Map),rb(this,"_downlinkMIDUserIDMap",new Map),rb(this,"_reconnectionTimer",-1),rb(this,"reconnectionCount",0),rb(this,"_clientAbility",null),rb(this,"_serverAbility",null),rb(this,"addDownlinkQueue",new Set),rb(this,"removeDownlinkQueue",new Set),rb(this,"_parsedAnswer",null),rb(this,"_updateSDPPromise",null),rb(this,"_waitForPCConnectedPromise"),rb(this,"_waitForPCConnectedPromiseReject",null),rb(this,"_isSDPLogged",!1),rb(this,"seiCodec",null),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=jO.createLogger({id:"spc".concat(dU++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Nw&&(this.seiCodec=new $x(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 isUsingH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=oV(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var n;if(e.ssrcs&&!iO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return sb(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Nw,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 pU(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(PN.AUDIO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=((e,t)=>{var i,n;let r=oV(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||"",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||""),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||"";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(oN){throw this._log.error("initialize failed ".concat(oN)),oN}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return sb(this,null,(function*(){var i;try{if("CONNECTED"===this.currentState)return;let n=mO(),r={type:"answer",sdp:tU({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(mO()-n,3e4)}),null==(i=this.seiCodec)||i.handleEncodedStreams()}catch(n){let t=n instanceof fb&&n.code===_b.API_CALL_ABORTED;throw t||this._log.error("connect failed: ".concat(n),e),this.reset(),!t&&!this.isReconnecting&&(UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}}))}reconnect(){return sb(this,null,(function*(){if(-1===this._reconnectionTimer){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(ox,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:Dx,responseCommand:lx.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new fb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),this._log.warn("reconnect() success"),this.stopReconnection(),this.emit("spc-reconnected")}catch(oN){if(!this.isReconnecting)return;if(null!=oN&&oN.message.includes("timeout")){let e=ZD(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),this._reconnectionTimer=window.setTimeout((()=>{this.clearReconnectionTimer(),this.reconnect()}),e)}else this._log.error("reconnect() failed ".concat(null==oN?void 0:oN.code," ").concat(oN)),UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:oN}),this.reconnectionCount>=rD()&&this._log.warn("SDK has tried reconnect for ".concat(rD()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")}))}getPeerConnection(){return this._peerConnection}startReconnection(){return sb(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=mO();yield this.reconnect(),UO.emit(BO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(mO()-e,3e4)})}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ox,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===tD.CLOSED&&this.startReconnection()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,i=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(t," DTLS: ").concat(i)),e.target.connectionState===tD.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===tD.FAILED||e.target.connectionState===tD.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===tD.CONNECTED||e.target.connectionState===tD.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),UO.emit(BO.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return eD;let e=null;return Sw()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,Ew()&&0!==this._peerConnection.getReceivers().length&&e?e.state:eD):eD}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(sU.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return sb(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(hw(i)){let t=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);t&&this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),n&&this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{UO.off(BO.LEAVE_SUCCESS,n,this),this.off(sU.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{r();let e=new fb({code:_b.API_CALL_TIMEOUT,message:"connection timeout"});aU+=1,(e=>aU>2&&!cU&&0===lU.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),cU=!0,this.emit(sU.FIREWALL_RESTRICTION)),t(e)}),ED);UO.on(BO.LEAVE_SUCCESS,n,this),this.on(sU.CONNECTION_STATE_CHANGED,i,this)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}))),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise(((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)})):Promise.resolve()}addDownlink(e){return sb(this,null,(function*(){var t;if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP({isNeedToCreateOffer:!0}),null==(t=this.seiCodec)||t.handleEncodedStreams(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(sN){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=PN.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(PN.AUDIO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(PN.VIDEO,{direction:PN.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=oV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=iU({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:oV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}r.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(n)},{id:t.audio,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-audio")}],o.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(n)},{id:t.video,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(n)},{id:t.videoRtx,attribute:"msid",value:"".concat(n,"-").concat(PN.MAIN," ").concat(n,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],s.direction=PN.TRANSCEIVER_DIRECTION_SENDONLY;let c="".concat(n,"-aux");s.ssrcs=[{id:t.auxiliary,attribute:"cname",value:c},{id:t.auxiliary,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(PN.VIDEO)}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[r.mid,o.mid,s.mid]),this._downlinkMIDUserIDMap.set(r.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i)}removeDownlink(e,t){return sb(this,null,(function*(){if(!this._downlinkMIDMap.has(t)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected());let i=this._downlinkMIDMap.get(t),n=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=oV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&n&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(t),null==i||i.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(t,") done"))}))}setBandwidth(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(Cw()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&n?o=n:3===s&&r&&(o=r),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),r&&e[3].track&&(o=this.setStartBitrate(3,r)||o),o&&(yield this.updateSDP({localDescription:this._peerConnection.localDescription}))}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth".concat(o))}}))}setStartBitrate(e,t){var i,n;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=oV(this._peerConnection.remoteDescription.sdp)),null==(n=this._parsedAnswer.media[e])||!n.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=oV(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=oV(this._peerConnection.remoteDescription.sdp));let s=Vb?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:Vb?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:Vb?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:Vb?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:Vb?1e3*i:i}]),n&&(o.media[2].bandwidth=[{type:s,limit:Vb?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:Vb?1e3*n:n}]),r&&(o.media[3].bandwidth=[{type:s,limit:Vb?1e3*r:r}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:Vb?1e3*r:r}]);let a={type:"offer",sdp:sV(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(e){let{isNeedToCreateOffer:t=!1,localDescription:i,tinyIdRemoving:n}=e;if(!this._parsedAnswer)return;let r=sV(this._parsedAnswer);return this._updateSDPPromise=new Promise(((e,n)=>sb(this,null,(function*(){var o,s;try{t&&this._peerConnection&&(this._log.info("creating offer"),i=yield this._peerConnection.createOffer()),i&&(yield this.setOffer(i)),yield this.setAnswer({type:"answer",sdp:r}),this._updateSDPPromise=null,e()}catch(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._log.warn("local sdp: ".concat(null==i?void 0:i.sdp)||(null==(o=this._peerConnection.localDescription)?void 0:o.sdp)),this._log.warn("remote sdp: ".concat(r)||(null==(s=this._peerConnection.remoteDescription)?void 0:s.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,n(a)}})))),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:oU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var i;null==(i=this.seiCodec)||i.push(e,t)}};nb([aM()],uU.prototype,"updateSDP",1);var hU=class{constructor(e){rb(this,"tag"),rb(this,"len"),rb(this,"data");let t=new DataView(e);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(e).slice(4,4+this.len).buffer}},pU=class{constructor(e){rb(this,"tinyId"),rb(this,"data");let t=new DataView(e),i=0,n=[];for(;i<t.byteLength;){let r=t.getUint16(i+2),o=new hU(new Uint8Array(e).slice(i,i+2+2+r).buffer);n.push(o),i+=4+r}n.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},_U=new Set;function mU(){let e=Math.floor(4294967296*Math.random());return _U.has(e)?mU():(_U.add(e),e)}var fU=ib(ab()),gU=class extends fU.default{constructor(e){super(),rb(this,"userId"),rb(this,"tinyId"),rb(this,"_sdpSemantics"),rb(this,"_isUplink"),rb(this,"_room"),rb(this,"_log"),rb(this,"_signalChannel"),rb(this,"_currentState","DISCONNECTED"),rb(this,"_prevTime",-1),rb(this,"_enableSEI"),rb(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=jO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Nw&&(this._sei=new $x(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(UO.emit(BO.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"))}},TU=class extends gU{constructor(e){super(ZC($C({},e),{isUplink:!0})),rb(this,"localMainAudioTrack",null),rb(this,"localMainVideoTrack",null),rb(this,"localAuxAudioTrack",null),rb(this,"localAuxVideoTrack",null),rb(this,"_isPublishingAux",!1),rb(this,"_publishingLocalAudioTrack"),rb(this,"_publishingLocalVideoTrack"),rb(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),rb(this,"_audioManager"),this._audioManager=e.audioManager,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(Iw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===PN.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new fb({code:_b.NOT_SUPPORTED_H264,message:QO({key:KO.NOT_SUPPORTED_H264ENCODE})});Pb&&115===Ok()&&n.profile.width*n.profile.height<=230400&&(t._log.warn("fallback video to 480p"),n.setProfile(ON["480p_2"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n}let u;if(t._isPublishingAux=r,n&&!r&&n.small&&(u=t._room.videoManager.smallTrack),vw()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:u,isAuxiliary:r})),null==(e=t.singlePC.seiCodec)||e.handleEncodedStreams(),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r)n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i);else{if(n){t.localMainVideoTrack=n;let{scaleResolutionDownBy:e}=n;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(o=t.localMainAudioTrack)?void 0:o.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(l=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:l.bitrate,auxVideo:null==(d=t.localAuxVideoTrack)?void 0:d.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:wx,responseCommand:lx.SPC_PUBLISH_RESULT,data:ZC($C({},t.singlePC.uplinkSSRC),{state:t.publishState,muteState:t.muteState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=this._audioManager.mixedAudioTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e)}let d=this.setTransceiverDirection(MN.SENDONLY,l);return c.push(d),Promise.all(c)}enableSmall(e){return sb(this,null,(function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(MN.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(MN.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()}))}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.on("mute",this.sendMutedFlag,this),null==e||e.on("unmute",this.sendMutedFlag,this))}))}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach((e=>{e&&(null==e||e.off("mute",this.sendMutedFlag,this),null==e||e.off("unmute",this.sendMutedFlag,this))}))}unpublish(e){return sb(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3)):(yield o[1].replaceTrack(null),yield o[2].replaceTrack(null),t.localMainVideoTrack=null,t._mediaSettings=ZC($C({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2))),t.isMainStreamPublished||t.isAuxStreamPublished?(yield t.setTransceiverDirection(MN.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:fx,data:t,responseCommand:lx.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:gx,commandDesc:"unpublish",responseCommand:lx.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===_b.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),bw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Nx,data:this._mediaSettings,responseCommand:lx.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return sb(this,null,(function*(){var t;if(!this._peerConnection)return;let i=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(i?PN.AUXILIARY:PN.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),Iw()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return sb(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===MN.INACTIVE&&(yield this.setTransceiverDirection(MN.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return sb(this,null,(function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(t?PN.AUXILIARY:PN.MAIN," stream")),Iw()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return sb(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===PN.AUDIO)this._audioManager.mixedAudioTrack||(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(MN.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return sb(this,null,(function*(){if(!Vb)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(MN.INACTIVE,"|").concat(MN.RECVONLY,"|").concat(MN.SENDONLY,")")))&&o++,t.includes(o)){if(e===MN.INACTIVE&&i.includes("a=".concat(MN.RECVONLY)))return n=!0,"a=".concat(e);if(e===MN.SENDONLY&&i.includes("a=".concat(MN.INACTIVE)))return n=!0,"a=".concat(MN.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return sb(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!n||i.find((e=>e.track===n)))return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(n.kind," track on ").concat(r?PN.AUXILIARY:PN.MAIN," stream")),n.kind===PN.AUDIO&&i[0]&&(yield i[0].replaceTrack(this._audioManager.mixedAudioTrack)),n.kind===PN.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(n)),r&&i[3]&&(yield i[3].replaceTrack(n)))}))}setBandwidth(e){return sb(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===PN.AUDIO?e.audio=i:"big"===r?e.bigVideo=i:"small"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.send(_x,this.muteState))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&UO.emit(BO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:PN.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===PN.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===PN.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===PN.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===PN.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===pD?(this._log.error(YO.NOT_SUPPORTED_H264ENCODE),new fb({code:_b.NOT_SUPPORTED_H264,message:QO({key:KO.NOT_SUPPORTED_H264ENCODE})})):new fb({code:_b.UNKNOWN,message:QO({key:KO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lx.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return sb(this,null,(function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))}))}};function EU(e){return Object.keys(e).filter((t=>e[t]))}var SU=class extends gU{constructor(e){super(ZC($C({},e),{isUplink:!1})),rb(this,"_flag",0),rb(this,"role","anchor"),rb(this,"remoteAudioTrack"),rb(this,"remoteVideoTrack"),rb(this,"remoteAuxiliaryTrack"),rb(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new PM(this._room,this),this.remoteVideoTrack=new MM(this._room,this),this.remoteAuxiliaryTrack=new LM(this._room,this),this.initialize()}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 SO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===PN.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=PN.AUDIO;i.kind===PN.VIDEO&&(r=n===PN.MAIN?PN.VIDEO:PN.AUXILIARY);let o=this.remoteAudioTrack;r===PN.VIDEO?o=this.remoteVideoTrack:r===PN.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return sb(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info("subscribe ".concat(t," ").concat(EU(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e)}catch(sN){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(sN.message," ").concat(JSON.stringify(this.muteState))),new fb({code:_b.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):sN}}))}unsubscribe(e){return sb(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(n," stream already unsubscribed"));let r=$C({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1}}));let o="subscribe_change";Object.values(r).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(n," [").concat(EU(r),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Ex,r=lx.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Sx,r=lx.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new fb({code:i.code,message:QO({key:KO.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,!1))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return sb(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){if(e.singlePC){if(e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected(),i||!e.hasSSRC){let i={audioSsrc:mU(),bigVideoSsrc:mU(),bigVideoRtxSsrc:mU(),auxVideoSsrc:mU(),auxVideoRtxSsrc:mU()},{audioSsrc:r,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:r,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let n=yield e._signalChannel.sendWaitForResponseWithRetry({command:Px,responseCommand:lx.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==n.data.code)throw new fb({code:n.data.code,message:n.data.message})}catch(n){throw yield e.removeDownlink(),n}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return sb(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};nb([rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this.off("closed",r),n(new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.CONNECTION_ABORTED,data:e})}))};this.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this.off("closed",r)}))}))}))],SU.prototype,"subscribe",1);var IU=SU;var{isString:vU,isPlainObject:yU,isUndefined:AU,getNetworkType:RU,getTerminalType:CU,isEmpty:bU}=Sb,kU=class extends $V{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=yw,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=RU(),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 mV(this,this._log),this.userManager=new eL(this.userId,this._log),this._version=nN,this.sdpSemantics=hD,AU(e.sdpSemantics)?JO.isUnifiedPlanDefault()&&(this.sdpSemantics=uD):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(this._networkType)),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!AU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!AU(e.enableSPC)&&yw&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return sb(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var n in e)YC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&JC)for(var n of JC(e))t.indexOf(n)<0&&zC.call(e,n)&&(i[n]=e[n]);return i})(e,[]);UO.emit(BO.REMOTE_PUBLISH_STATE_CHANGED,$C({room:this},t)),this.emit("remote-publish-state-changed",$C({},t))})),this._joinOptions=e,new Promise(((t,i)=>sb(this,null,(function*(){this._joinReject=i;try{this.checkDestroy();let i=yield this.initialize();yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(n){i(n)}this._joinReject=null}))))}))}doJoin(e){return new Promise(((t,i)=>sb(this,null,(function*(){var n,r,o;let s;if(e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(nx,(e=>{this.clearJoinTimeout(),UO.emit(BO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),oO(null==(r=null==(n=this.scheduleResult)?void 0:n.config)?void 0:r.singlePC)&&yw&&(this.enableSPC=this.scheduleResult.config.singlePC),this.enableSPC&&!this.singlePC){this.singlePC=new uU({signalChannel:this._signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(e=>this.emit("sei-message",e))),this.singlePC.once("error",(()=>this.fallbackToMPC()));try{s=yield this.singlePC.initialize()}catch(l){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:CU(),netType:bN[this._networkType],bussinessInfo:this._businessInfo,ability:s,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(o=this.scheduleResult.config)?void 0:o.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{i(new fb({code:_b.JOIN_ROOM_FAILED,message:QO({key:KO.JOIN_ROOM_TIMEOUT})}))}),c),UO.emit(BO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?Ox:ux,a),this._signalChannel.once(lx.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:n,message:r,data:o,tinyId:s}=e.data;UO.emit(BO.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(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((()=>{})),t()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(r)),i(new fb({code:_b.JOIN_ROOM_FAILED,extraCode:n,message:QO({key:KO.JOIN_ROOM_FAILED,data:{error:r,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return sb(this,null,(function*(){if(this.isJoined)try{if(this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId)),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),yield this._signalChannel.connect()),yield this.doJoin(ZC($C({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),Xw.logSuccessEvent({userId:this.userId,eventType:aD.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(sU.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof TU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.doSubscribe()})))};this.singlePC.on(sU.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof _V&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(oD){this._log.warn("reJoin fail ".concat(oD)),this.reset(),Xw.logFailedEvent({userId:this.userId,eventType:aD.REJOIN,error:oD}),this.emit("error",new fb({code:_b.JOIN_ROOM_FAILED,message:QO({key:KO.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return sb(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...zx.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new qx({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC,room:this}),this._networkQuality||(this._networkQuality=new TV({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(TV.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),IP(this,this._signalChannel).add(rx,(e=>{UO.emit(BO.SIGNAL_CONNECTION_STATE_CHANGED,$C({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(sx,(e=>{this.reset(),this.emit("error",e)})).add(lx.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n})})).add(lx.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(lx.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(lx.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if(Xw.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(ix,(e=>{this.tinyId=e.signalInfo.tinyId,UO.emit(BO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),UO.emit(BO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n}))}setSignalChannel(e){this._signalChannel=e,e||vP(this)}leave(){return sb(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(oD){}this._log.info("leave() => leaving room"),UO.emit(BO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(hx)}))}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach((e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")}))}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){-1===this._heartbeat&&(this._heartbeat=qw.run(OD,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),qw.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return sb(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if(XM.has(e)){let t=XM.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return XM.delete(e),t}return[]}(this.userId):[],r=$C({str_sdk_version:iN,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:bN[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);UO.emit(BO.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(px,r),this.emit("heartbeat-report",ZC($C({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n}}));UO.emit(BO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:n}=e,r=new(this.singlePC?IU:dV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit("remote-published",r)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==_b.ICE_TRANSPORT_ERROR&&(i===_b.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",ZC($C({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=qw.run(OD,this.syncUserList.bind(this)))}stopSyncUserListInterval(){qw.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:bx,responseCommand:lx.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n}}));throw QO({key:KO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:lx.USER_LIST_RES,code:i,message:n}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!iV)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(){this.singlePC||this.getAllConnections().forEach((e=>{if(e instanceof nV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===tD.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return sb(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),Xw.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(!1),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new _V({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach((e=>{let t=new dV({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(t,e.userId),this.remotePublishedUserMap.set(e.userId,t),e.isMainStreamSubscribed&&t.subscribe(e.subscribeState,"main"),e.isAuxStreamSubscribed&&t.subscribe(e.subscribeState,"auxiliary")}))}))}destroy(){this.isDestroyed||(this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close(),this._signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return sb(this,null,(function*(){this.role!==e&&("audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))}))}doSwitchRole(e){let t={command:kx,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:lx.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this._signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:n}=t.data;if(0!==i)throw new fb({code:_b.SWITCH_ROLE_FAILED,message:QO({key:KO.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e})).catch((e=>{throw e instanceof fb&&e.getCode()===_b.API_CALL_TIMEOUT&&(e=new fb({code:_b.SWITCH_ROLE_FAILED,message:QO({key:KO.SWITCH_ROLE_TIMEOUT})})),this._log.error(e),e}))}publish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof uM&&(t instanceof mM?i.audio=t:e.audio=t),t instanceof hM&&(t instanceof _M&&2===t.mediaType?i.video=t:e.video=t)}));let n=bU(e),r=bU(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new TU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new _V({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",(e=>{this.emit("media-connection-state-changed",ZC($C({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==_b.ICE_TRANSPORT_ERROR&&(t===_b.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");n||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),r||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let e={},i={};t.forEach((t=>{!t.mediaTrack||!t.isPublished||(t instanceof uM&&(t instanceof mM?i.audio=t:e.audio=t),t instanceof hM&&(t instanceof _M&&2===t.mediaType?i.video=t:e.video=t))}));try{let n=t.map((e=>e.kind)).join(",");bU(e)||(this._log.info("unpublish() => main ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),bU(i)||(this._log.info("unpublish() => aux ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(n){}0===this.localTracks.size&&!this.audioManager.mixedAudioTrack&&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?this.uplinkConnection.replaceTrack(e).then((t=>{UO.emit(BO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return sb(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return sb(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:PN.VIDEO,videoType:PN.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)}))}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let r=$C({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),UO.emit(BO.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info("subscribe() => ".concat(e," ").concat(n," [").concat(aV(r),"] prev: [").concat(aV(i.subscribeState),"]")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),UO.emit(BO.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}catch(aN){let i=aN instanceof fb?aN.getCode():_b.UNKNOWN,r=aN;throw aN instanceof fb?i===_b.REMOTE_STREAM_NOT_EXIST&&(r=new fb({code:_b.API_CALL_ABORTED,message:QO({key:KO.API_CALL_ABORTED,data:{message:aN.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new fb({code:i,message:QO({key:KO.SUBSCRIBE_FAILED,data:{message:aN.message,userId:e,streamType:n}})}),this._log.error(r)),r}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return sb(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n})}catch(aN){this._log.warn("unsubscribe() => failed ".concat(aN))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),UO.emit(BO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void qw.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),UO.emit(BO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&qw.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=qw.run(wD,(()=>{var e;let t=[];null==(e=this.remotePublishedUserMap)||e.forEach((e=>{if(e.muteState.hasAudio){let i=Math.floor(100*e.remoteAudioTrack.getAudioLevel());t.push({userId:e.userId,volume:i})}})),this.emit("audio-volume",t)}),{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e}))}getLocalVideoStats(){return sb(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return sb(this,null,(function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let i=yield this._stats.getReceiverStats(t);e.downlinksRTT[i.userId]=i.rtt}return e}))}getRemoteVideoStats(e){return sb(this,null,(function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)"main"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),"auxiliary"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return sb(this,null,(function*(){let e={};for(let[t,i]of this.remotePublishedUserMap)i.muteState.hasAudio&&(e[t]=i.remoteAudioTrack.stat);return e}))}setTurnServer(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));let i=[];Array.isArray(e)?e.forEach((e=>i.push(Sb.getTurnServer(e)))):Sb.isPlainObject(e)&&i.push(Sb.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:Rx,data:e,timeout:5e3,responseCommand:lx.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:Cx,data:e,timeout:5e3,responseCommand:lx.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?Ix:yx,data:e,timeout:5e3,responseCommand:t?lx.START_PUBLISH_TENCENT_CDN_RES:lx.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?vx:Ax,data:e,timeout:5e3,responseCommand:t?lx.STOP_PUBLISH_TENCENT_CDN_RES:lx.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:Mx,data:e,timeout:5e3,responseCommand:lx.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((e=>{}))}getIceServers(){return 0===this._turnServers.length&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Sb.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return(null==(e=this._signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this._signalChannel&&(e&&this._signalChannel.keepAlive&&this._signalChannel.isConnected?this._signalChannel.stopKeepAliveIn(3600):this._signalChannel.close(),this.setSignalChannel(null)),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return sb(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:n,hasVideo:r}}=e;if(!n&&!r||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&n)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!n&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(ND-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=ND}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(ND-o.reSubscribeCount,".")),o.isSubscribing=!1,0===o.reSubscribeCount&&this._changeBigSmallRecords.delete(i)}}))}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ND};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big"))}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(vU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!AU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new fb({code:_b.INVALID_PARAMETER,message:QO({key:KO.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(!AU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new fb({code:_b.INVALID_PARAMETER,message:QO({key:KO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!AU(e.userDefinePushArgs)){if(!(vU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new fb({code:_b.INVALID_PARAMETER,message:QO({key:KO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}bU(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}};return nb([Hw(["left",Ww.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"),Hx(!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))}}),rM((e=>{let t=new ZL;return function(i,n,r){return sb(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new fb({code:_b.INVALID_OPERATION,message:QO({key:KO.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)),UO.emit(BO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield JO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Sb.getEnv();s||(s=yN.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(LN.OLD_CLOUD_LADDER)?s=yN.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(LN.WEBRTC)&&(s=yN.WEBRTC))),Xw.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),ex.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!JO.isWebRTCSupported()||!a&&!c)throw new fb({code:_b.NOT_SUPPORTED,message:QO({key:KO.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Sb.getEnv()&&(yield this.schedule(o,r));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Sb.performanceNow(),UO.emit(BO.JOIN_SUCCESS,{room:this}),Xw.uploadEvent({log:"stat-conv-".concat(Number(Kk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),UO.emit(BO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],kU.prototype,"join",1),nb([Hw("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),rM((e=>function(){return sb(this,null,(function*(){UO.emit(BO.LEAVE_START,{room:this}),yield e.call(this),UO.emit(BO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),function(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return null==(t=oM.get(this))||t.forEach((e=>n.push(e))),null==(i=sM.get(this))||i.forEach((e=>e.forEach((e=>n.push(e))))),n.forEach((t=>{t.reject(new fb({code:_b.API_CALL_ABORTED,message:e}))})),oM.delete(this),sM.delete(this),r.apply(this,s)},n}}("leave room"),Ux({fnName:"publish",validateArgs:!1}),Ux({fnName:"unsubscribe",validateArgs:!1})],kU.prototype,"leave",1),nb([aM(),rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return sb(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;UO.emit("61",{room:this});for(let e of i)"audio"===e.kind&&(yield this.audioManager.addAudioTrack(e));let t=e.apply(this,i);return i.forEach((e=>{var i;e.publish(this,t),"audio"===e.kind&&(null==(i=this.audioManager.localMixAudioTrack)||i.publish(this,t))})),t}))})),Vx({settings:{retries:rD,timeout:e=>ZD(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),UO.emit(BO.PUBLISH_FAILED,{room:this}))}})],kU.prototype,"publish",1),nb([Ux({fnName:"publish",callback(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];0===this.localTracks.size&&(null==(e=this.uplinkConnection)||e.close("you unpublished"),this.uplinkConnection=null,i.forEach((e=>e.unpublish())))}}),function(e){return function(t,i,n){let r=n.value;return n.value=function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let o=oM.get(this);if(o){let t=o.filter(((t,n)=>{if(0===n)return!0;let r=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(r=!1)})),!r||(t.reject(new fb({code:_b.API_CALL_ABORTED,message:e})),!1)}));oM.set(this,t)}return r.apply(this,i)},n}}("api-call"),aM(),rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((e=>{"audio"===e.kind&&this.audioManager.removeAudioTrack(e)}));let r=e.apply(this,i);return i.forEach((e=>e.unpublish())),r}))],kU.prototype,"unpublish",1),nb([cM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),rM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(r))),r})),Vx({settings:{retries:rD,timeout:e=>ZD(e)},onError(e,t,i,n){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),UO.emit(BO.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}))}})],kU.prototype,"subscribe",1),nb([Ux({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")}))}}),cM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],kU.prototype,"unsubscribe",1),$L.create=$L._create.bind($L,kU),$L}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TRTC=t()}(this,(function(){function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(t){return!0}},n=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=n,o=Function.prototype,s=o.call,a=r&&o.bind.bind(s,s),c=r?a:function(e){return function(){return s.apply(e,arguments)}},l=c,d=l({}.toString),u=l("".slice),h=function(e){return u(d(e),8,-1)},p=i,m=h,_=Object,f=c("".split),g=p((function(){return!_("z").propertyIsEnumerable(0)}))?function(e){return"String"==m(e)?f(e,""):_(e)}:_,T=function(e){return null==e},E=T,S=TypeError,I=function(e){if(E(e))throw S("Can't call method on "+e);return e},v=g,y=I,A=function(e){return v(y(e))},R=function(e){return e&&e.Math==Math&&e},C=R("object"==typeof globalThis&&globalThis)||R("object"==typeof window&&window)||R("object"==typeof self&&self)||R("object"==typeof t&&t)||function(){return this}()||Function("return this")(),b={},k={get exports(){return b},set exports(e){b=e}},D=C,N=Object.defineProperty,O=function(e,t){try{N(D,e,{value:t,configurable:!0,writable:!0})}catch(i){D[e]=t}return t},w=O,P="__core-js_shared__",M=C[P]||w(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,K=Math.random(),Y=W(1..toString),z=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Y(++J+K,36)},q="undefined"!=typeof navigator&&String(navigator.userAgent)||"",Q=C,X=q,$=Q.process,Z=Q.Deno,ee=$&&$.versions||Z&&Z.version,te=ee&&ee.v8;te&&(V=(x=te.split("."))[0]>0&&x[0]<4?1:+(x[0]+x[1])),!V&&X&&(!(x=X.match(/Edge\/(\d+)/))||x[1]>=74)&&(x=X.match(/Chrome\/(\d+)/))&&(V=+x[1]);var ie=V,ne=ie,re=i,oe=!!Object.getOwnPropertySymbols&&!re((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ne&&ne<41})),se=oe&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ae=b,ce=G,le=z,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]})),De=ke&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Ne={},Oe=ve,we=C.document,Pe=Oe(we)&&Oe(we.createElement),Me=function(e){return Pe?we.createElement(e):{}},Le=Me,xe=!ke&&!i((function(){return 7!=Object.defineProperty(Le("div"),"a",{get:function(){return 7}}).a})),Ve=n,Ue=Function.prototype.call,Fe=Ve?Ue.bind(Ue):function(){return Ue.apply(Ue,arguments)},Be=C,He=Ee,je=function(e,t){return arguments.length<2?(i=Be[e],He(i)?i:void 0):Be[e]&&Be[e][t];var i},Ge=c({}.isPrototypeOf),We=je,Je=Ee,Ke=Ge,Ye=Object,ze=se?function(e){return"symbol"==typeof e}:function(e){var t=We("Symbol");return Je(t)&&Ke(t.prototype,Ye(e))},qe=String,Qe=function(e){try{return qe(e)}catch(t){return"Object"}},Xe=Ee,$e=Qe,Ze=TypeError,et=function(e){if(Xe(e))return e;throw Ze($e(e)+" is not a function")},tt=et,it=T,nt=function(e,t){var i=e[t];return it(i)?void 0:tt(i)},rt=Fe,ot=Ee,st=ve,at=TypeError,ct=Fe,lt=ve,dt=ze,ut=nt,ht=function(e,t){var i,n;if("string"===t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;if(ot(i=e.valueOf)&&!st(n=rt(i,e)))return n;if("string"!==t&&ot(i=e.toString)&&!st(n=rt(i,e)))return n;throw at("Can't convert object to primitive value")},pt=TypeError,mt=_e("toPrimitive"),_t=function(e,t){if(!lt(e)||dt(e))return e;var i,n=ut(e,mt);if(n){if(void 0===t&&(t="default"),i=ct(n,e,t),!lt(i)||dt(i))return i;throw pt("Can't convert object to primitive value")}return void 0===t&&(t="number"),ht(e,t)},ft=_t,gt=ze,Tt=function(e){var t=ft(e,"string");return gt(t)?t:t+""},Et=ke,St=xe,It=De,vt=Ce,yt=Tt,At=TypeError,Rt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,bt="enumerable",kt="configurable",Dt="writable";Ne.f=Et?It?function(e,t,i){if(vt(e),t=yt(t),vt(i),"function"==typeof e&&"prototype"===t&&"value"in i&&Dt in i&&!i[Dt]){var n=Ct(e,t);n&&n[Dt]&&(e[t]=i.value,i={configurable:kt in i?i[kt]:n[kt],enumerable:bt in i?i[bt]:n[bt],writable:!1})}return Rt(e,t,i)}:Rt:function(e,t,i){if(vt(e),t=yt(t),vt(i),St)try{return Rt(e,t,i)}catch(n){}if("get"in i||"set"in i)throw At("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Nt=Math.ceil,Ot=Math.floor,wt=Math.trunc||function(e){var t=+e;return(t>0?Ot:Nt)(t)},Pt=wt,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,Kt=Gt,Yt=function(e){return function(t,i,n){var r,o=Wt(t),s=Kt(o),a=Jt(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},zt={includes:Yt(!0),indexOf:Yt(!1)},qt={},Qt=G,Xt=A,$t=zt.indexOf,Zt=qt,ei=c([].push),ti=function(e,t){var i,n=Xt(e),r=0,o=[];for(i in n)!Qt(Zt,i)&&Qt(n,i)&&ei(o,i);for(;t.length>r;)Qt(n,i=t[r++])&&(~$t(o,i)||ei(o,i));return o},ii=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ni=ti,ri=ii,oi=Object.keys||function(e){return ni(e,ri)},si=ke,ai=De,ci=Ne,li=Ce,di=A,ui=oi;be.f=si&&!ai?Object.defineProperties:function(e,t){li(e);for(var i,n=di(t),r=ui(t),o=r.length,s=0;o>s;)ci.f(e,i=r[s++],n[i]);return e};var hi,pi=je("document","documentElement"),mi=z,_i=b("keys"),fi=function(e){return _i[e]||(_i[e]=mi(e))},gi=Ce,Ti=be,Ei=ii,Si=qt,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},Di=function(){try{hi=new ActiveXObject("htmlfile")}catch(r){}var e,t,i;Di="undefined"!=typeof document?document.domain&&hi?ki(hi):(t=vi("iframe"),i="java"+Ai+":",t.style.display="none",Ii.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(bi("document.F=Object")),e.close(),e.F):ki(hi);for(var n=Ei.length;n--;)delete Di[yi][Ei[n]];return Di()};Si[Ri]=!0;var Ni=Object.create||function(e,t){var i;return null!==e?(Ci[yi]=gi(e),i=new Ci,Ci[yi]=null,i[Ri]=e):i=Di(),void 0===t?i:Ti.f(i,t)},Oi=_e,wi=Ni,Pi=Ne.f,Mi=Oi("unscopables"),Li=Array.prototype;null==Li[Mi]&&Pi(Li,Mi,{configurable:!0,value:wi(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=Ne,Ki=Wi,Yi=ke?function(e,t,i){return Ji.f(e,t,Ki(1,i))}:function(e,t,i){return e[t]=i,e},zi=Gi,qi=C,Qi=ve,Xi=Yi,$i=G,Zi=M,en=fi,tn=qt,nn="Object already initialized",rn=qi.TypeError,on=qi.WeakMap;if(zi||Zi.state){var sn=Zi.state||(Zi.state=new on);sn.get=sn.get,sn.has=sn.has,sn.set=sn.set,xi=function(e,t){if(sn.has(e))throw rn(nn);return t.facade=e,sn.set(e,t),t},Vi=function(e){return sn.get(e)||{}},Ui=function(e){return sn.has(e)}}else{var an=en("state");tn[an]=!0,xi=function(e,t){if($i(e,an))throw rn(nn);return t.facade=e,Xi(e,an,t),t},Vi=function(e){return $i(e,an)?e[an]:{}},Ui=function(e){return $i(e,an)}}var cn={set:xi,get:Vi,has:Ui,enforce:function(e){return Ui(e)?Vi(e):xi(e,{})},getterFor:function(e){return function(t){var i;if(!Qi(t)||(i=Vi(t)).type!==e)throw rn("Incompatible receiver, "+e+" required");return i}}},ln={},dn={},un={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,pn=hn&&!un.call({1:2},1);dn.f=pn?function(e){var t=hn(this,e);return!!t&&t.enumerable}:un;var mn=ke,_n=Fe,fn=dn,gn=Wi,Tn=A,En=Tt,Sn=G,In=xe,vn=Object.getOwnPropertyDescriptor;ln.f=mn?vn:function(e,t){if(e=Tn(e),t=En(t),In)try{return vn(e,t)}catch(i){}if(Sn(e,t))return gn(!_n(fn.f,e,t),e[t])};var yn={},An={get exports(){return yn},set exports(e){yn=e}},Rn=ke,Cn=G,bn=Function.prototype,kn=Rn&&Object.getOwnPropertyDescriptor,Dn=Cn(bn,"name"),Nn={EXISTS:Dn,PROPER:Dn&&"something"===function(){}.name,CONFIGURABLE:Dn&&(!Rn||Rn&&kn(bn,"name").configurable)},On=Ee,wn=M,Pn=c(Function.toString);On(wn.inspectSource)||(wn.inspectSource=function(e){return Pn(e)});var Mn=wn.inspectSource,Ln=c,xn=i,Vn=Ee,Un=G,Fn=ke,Bn=Nn.CONFIGURABLE,Hn=Mn,jn=cn.enforce,Gn=cn.get,Wn=String,Jn=Object.defineProperty,Kn=Ln("".slice),Yn=Ln("".replace),zn=Ln([].join),qn=Fn&&!xn((function(){return 8!==Jn((function(){}),"length",{value:8}).length})),Qn=String(String).split("String"),Xn=An.exports=function(e,t,i){"Symbol("===Kn(Wn(t),0,7)&&(t="["+Yn(Wn(t),/^Symbol\(([^)]*)\)/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Un(e,"name")||Bn&&e.name!==t)&&(Fn?Jn(e,"name",{value:t,configurable:!0}):e.name=t),qn&&i&&Un(i,"arity")&&e.length!==i.arity&&Jn(e,"length",{value:i.arity});try{i&&Un(i,"constructor")&&i.constructor?Fn&&Jn(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(r){}var n=jn(e);return Un(n,"source")||(n.source=zn(Qn,"string"==typeof t?t:"")),e};Function.prototype.toString=Xn((function(){return Vn(this)&&Gn(this).source||Hn(this)}),"toString");var $n=Ee,Zn=Ne,er=yn,tr=O,ir=function(e,t,i,n){n||(n={});var r=n.enumerable,o=void 0!==n.name?n.name:t;if($n(i)&&er(i,o,n),n.global)r?e[t]=i:tr(t,i);else{try{n.unsafe?e[t]&&(r=!0):delete e[t]}catch(s){}r?e[t]=i:Zn.f(e,t,{value:i,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return e},nr={},rr=ti,or=ii.concat("length","prototype");nr.f=Object.getOwnPropertyNames||function(e){return rr(e,or)};var sr={};sr.f=Object.getOwnPropertySymbols;var ar,cr,lr,dr=je,ur=nr,hr=sr,pr=Ce,mr=c([].concat),_r=dr("Reflect","ownKeys")||function(e){var t=ur.f(pr(e)),i=hr.f;return i?mr(t,i(e)):t},fr=G,gr=_r,Tr=ln,Er=Ne,Sr=function(e,t,i){for(var n=gr(t),r=Er.f,o=Tr.f,s=0;s<n.length;s++){var a=n[s];fr(e,a)||i&&fr(i,a)||r(e,a,o(t,a))}},Ir=i,vr=Ee,yr=/#|\.prototype\./,Ar=function(e,t){var i=Cr[Rr(e)];return i==kr||i!=br&&(vr(t)?Ir(t):!!t)},Rr=Ar.normalize=function(e){return String(e).replace(yr,".").toLowerCase()},Cr=Ar.data={},br=Ar.NATIVE="N",kr=Ar.POLYFILL="P",Dr=Ar,Nr=C,Or=ln.f,wr=Yi,Pr=ir,Mr=O,Lr=Sr,xr=Dr,Vr=function(e,t){var i,n,r,o,s,a=e.target,c=e.global,l=e.stat;if(i=c?Nr:l?Nr[a]||Mr(a,{}):(Nr[a]||{}).prototype)for(n in t){if(o=t[n],r=e.dontCallGetSet?(s=Or(i,n))&&s.value:i[n],!xr(c?n:a+(l?".":"#")+n,e.forced)&&void 0!==r){if(typeof o==typeof r)continue;Lr(o,r)}(e.sham||r&&r.sham)&&wr(o,"sham",!0),Pr(i,n,o,e)}},Ur=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Fr=G,Br=Ee,Hr=B,jr=Ur,Gr=fi("IE_PROTO"),Wr=Object,Jr=Wr.prototype,Kr=jr?Wr.getPrototypeOf:function(e){var t=Hr(e);if(Fr(t,Gr))return t[Gr];var i=t.constructor;return Br(i)&&t instanceof i?i.prototype:t instanceof Wr?Jr:null},Yr=i,zr=Ee,qr=ve,Qr=Kr,Xr=ir,$r=_e("iterator"),Zr=!1;[].keys&&("next"in(lr=[].keys())?(cr=Qr(Qr(lr)))!==Object.prototype&&(ar=cr):Zr=!0);var eo=!qr(ar)||Yr((function(){var e={};return ar[$r].call(e)!==e}));eo&&(ar={}),zr(ar[$r])||Xr(ar,$r,(function(){return this}));var to={IteratorPrototype:ar,BUGGY_SAFARI_ITERATORS:Zr},io=Ne.f,no=G,ro=_e("toStringTag"),oo=function(e,t,i){e&&!i&&(e=e.prototype),e&&!no(e,ro)&&io(e,ro,{configurable:!0,value:t})},so=to.IteratorPrototype,ao=Ni,co=Wi,lo=oo,uo=Bi,ho=function(){return this},po=function(e,t,i,n){var r=t+" Iterator";return e.prototype=ao(so,{next:co(+!n,i)}),lo(e,r,!1),uo[r]=ho,e},mo=c,_o=et,fo=Ee,go=String,To=TypeError,Eo=function(e,t,i){try{return mo(_o(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(n){}},So=Ce,Io=function(e){if("object"==typeof e||fo(e))return e;throw To("Can't set "+go(e)+" as a prototype")},vo=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=Eo(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(n){}return function(i,n){return So(i),Io(n),t?e(i,n):i.__proto__=n,i}}():void 0),yo=Vr,Ao=Fe,Ro=Ee,Co=po,bo=Kr,ko=vo,Do=oo,No=Yi,Oo=ir,wo=Bi,Po=Nn.PROPER,Mo=Nn.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,n,r,o,s){Co(i,t,n);var a,c,l,d=function(e){if(e===r&&_)return _;if(!xo&&e in p)return p[e];switch(e){case Uo:case Fo:case Bo:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,m=p[Vo]||p["@@iterator"]||r&&p[r],_=!xo&&m||d(r),f="Array"==t&&p.entries||m;if(f&&(a=bo(f.call(new e)))!==Object.prototype&&a.next&&(bo(a)!==Lo&&(ko?ko(a,Lo):Ro(a[Vo])||Oo(a,Vo,Ho)),Do(a,u,!0)),Po&&r==Fo&&m&&m.name!==Fo&&(Mo?No(p,"name",Fo):(h=!0,_=function(){return Ao(m,this)})),r)if(c={values:d(Fo),keys:o?_:d(Uo),entries:d(Bo)},s)for(l in c)(xo||h||!(l in p))&&Oo(p,l,c[l]);else yo({target:t,proto:!0,forced:xo||h},c);return p[Vo]!==_&&Oo(p,Vo,_,{name:r}),wo[t]=_,c},Go=function(e,t){return{value:e,done:t}},Wo=A,Jo=Fi,Ko=Bi,Yo=cn,zo=Ne.f,qo=jo,Qo=Go,Xo=ke,$o="Array Iterator",Zo=Yo.set,es=Yo.getterFor($o),ts=qo(Array,"Array",(function(e,t){Zo(this,{type:$o,target:Wo(e),index:0,kind:t})}),(function(){var e=es(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,Qo(void 0,!0)):Qo("keys"==i?n:"values"==i?t[n]:[n,t[n]],!1)}),"values"),is=Ko.Arguments=Ko.Array;if(Jo("keys"),Jo("values"),Jo("entries"),Xo&&"values"!==is.name)try{zo(is,"name",{value:"values"})}catch(BU){}var ns={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},rs=Me("span").classList,os=rs&&rs.constructor&&rs.constructor.prototype,ss=os===Object.prototype?void 0:os,as=C,cs=ns,ls=ss,ds=ts,us=Yi,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(BU){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(BU){e[i]=ds[i]}}};for(var gs in cs)fs(as[gs]&&as[gs].prototype,gs);fs(ls,"DOMTokenList");var Ts="undefined"!=typeof process&&"process"==h(process),Es=yn,Ss=Ne,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,Ds=function(e,t){if(bs(t,e))return e;throw ks("Incorrect invocation")},Ns={};Ns[_e("toStringTag")]="z";var Os="[object z]"===String(Ns),ws=Ee,Ps=h,Ms=_e("toStringTag"),Ls=Object,xs="Arguments"==Ps(function(){return arguments}()),Vs=Os?Ps:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(BU){}}(t=Ls(e),Ms))?i:xs?Ps(t):"Object"==(n=Ps(t))&&ws(t.callee)?"Arguments":n},Us=c,Fs=i,Bs=Ee,Hs=Vs,js=Mn,Gs=function(){},Ws=[],Js=je("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,Ys=Us(Ks.exec),zs=!Ks.exec(Gs),qs=function(e){if(!Bs(e))return!1;try{return Js(Gs,Ws,e),!0}catch(BU){return!1}},Qs=function(e){if(!Bs(e))return!1;switch(Hs(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return zs||!!Ys(Ks,js(e))}catch(BU){return!0}};Qs.sham=!0;var Xs,$s,Zs,ea,ta=!Js||Fs((function(){var e;return qs(qs.call)||!qs(Object)||!qs((function(){e=!0}))||e}))?Qs:qs,ia=ta,na=Qe,ra=TypeError,oa=function(e){if(ia(e))return e;throw ra(na(e)+" is not a constructor")},sa=Ce,aa=oa,ca=T,la=_e("species"),da=function(e,t){var i,n=sa(e).constructor;return void 0===n||ca(i=sa(n)[la])?t:aa(i)},ua=n,ha=Function.prototype,pa=ha.apply,ma=ha.call,_a="object"==typeof Reflect&&Reflect.apply||(ua?ma.bind(pa):function(){return ma.apply(pa,arguments)}),fa=h,ga=c,Ta=function(e){if("Function"===fa(e))return ga(e)},Ea=et,Sa=n,Ia=Ta(Ta.bind),va=function(e,t){return Ea(e),void 0===t?e:Sa?Ia(e,t):function(){return e.apply(t,arguments)}},ya=c([].slice),Aa=TypeError,Ra=function(e,t){if(e<t)throw Aa("Not enough arguments");return e},Ca=/(?:ipad|iphone|ipod).*applewebkit/i.test(q),ba=C,ka=_a,Da=va,Na=Ee,Oa=G,wa=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,Ka=0,Ya={},za="onreadystatechange";wa((function(){Xs=ba.location}));var qa=function(e){if(Oa(Ya,e)){var t=Ya[e];delete Ya[e],t()}},Qa=function(e){return function(){qa(e)}},Xa=function(e){qa(e.data)},$a=function(e){ba.postMessage(Ja(e),Xs.protocol+"//"+Xs.host)};Fa&&Ba||(Fa=function(e){xa(arguments.length,1);var t=Na(e)?e:Ga(e),i=Ma(arguments,1);return Ya[++Ka]=function(){ka(t,void 0,i)},$s(Ka),Ka},Ba=function(e){delete Ya[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=Da(ea.postMessage,ea)):ba.addEventListener&&Na(ba.postMessage)&&!ba.importScripts&&Xs&&"file:"!==Xs.protocol&&!wa($a)?($s=$a,ba.addEventListener("message",Xa,!1)):$s=za in La("script")?function(e){Pa.appendChild(La("script"))[za]=function(){Pa.removeChild(this),qa(e)}}:function(e){setTimeout(Qa(e),0)});var Za={set:Fa,clear:Ba},ec=function(){this.head=null,this.tail=null};ec.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var tc,ic,nc,rc,oc,sc=ec,ac=/ipad|iphone|ipod/i.test(q)&&"undefined"!=typeof Pebble,cc=/web0s(?!.*chrome)/i.test(q),lc=C,dc=va,uc=ln.f,hc=Za.set,pc=sc,mc=Ca,_c=ac,fc=cc,gc=Ts,Tc=lc.MutationObserver||lc.WebKitMutationObserver,Ec=lc.document,Sc=lc.process,Ic=lc.Promise,vc=uc(lc,"queueMicrotask"),yc=vc&&vc.value;if(!yc){var Ac=new pc,Rc=function(){var e,t;for(gc&&(e=Sc.domain)&&e.exit();t=Ac.get();)try{t()}catch(BU){throw Ac.head&&tc(),BU}e&&e.enter()};mc||gc||fc||!Tc||!Ec?!_c&&Ic&&Ic.resolve?((rc=Ic.resolve(void 0)).constructor=Ic,oc=dc(rc.then,rc),tc=function(){oc(Rc)}):gc?tc=function(){Sc.nextTick(Rc)}:(hc=dc(hc,lc),tc=function(){hc(Rc)}):(ic=!0,nc=Ec.createTextNode(""),new Tc(Rc).observe(nc,{characterData:!0}),tc=function(){nc.data=ic=!ic}),yc=function(e){Ac.head||tc(),Ac.add(e)}}var Cc=yc,bc=function(e){try{return{error:!1,value:e()}}catch(BU){return{error:!0,value:BU}}},kc=C.Promise,Dc="object"==typeof Deno&&Deno&&"object"==typeof Deno.version,Nc=!Dc&&!Ts&&"object"==typeof window&&"object"==typeof document,Oc=C,wc=kc,Pc=Ee,Mc=Dr,Lc=Mn,xc=_e,Vc=Nc,Uc=Dc,Fc=ie;wc&&wc.prototype;var Bc=xc("species"),Hc=!1,jc=Pc(Oc.PromiseRejectionEvent),Gc=Mc("Promise",(function(){var e=Lc(wc),t=e!==String(wc);if(!t&&66===Fc)return!0;if(!Fc||Fc<51||!/native code/.test(e)){var i=new wc((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};if((i.constructor={})[Bc]=n,!(Hc=i.then((function(){}))instanceof n))return!0}return!t&&(Vc||Uc)&&!jc})),Wc={CONSTRUCTOR:Gc,REJECTION_EVENT:jc,SUBCLASSING:Hc},Jc={},Kc=et,Yc=TypeError,zc=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw Yc("Bad Promise constructor");t=e,i=n})),this.resolve=Kc(t),this.reject=Kc(i)};Jc.f=function(e){return new zc(e)};var qc,Qc,Xc,$c=Vr,Zc=Ts,el=C,tl=Fe,il=ir,nl=vo,rl=oo,ol=Cs,sl=et,al=Ee,cl=ve,ll=Ds,dl=da,ul=Za.set,hl=Cc,pl=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(BU){}},ml=bc,_l=sc,fl=cn,gl=kc,Tl=Jc,El="Promise",Sl=Wc.CONSTRUCTOR,Il=Wc.REJECTION_EVENT,vl=Wc.SUBCLASSING,yl=fl.getterFor(El),Al=fl.set,Rl=gl&&gl.prototype,Cl=gl,bl=Rl,kl=el.TypeError,Dl=el.document,Nl=el.process,Ol=Tl.f,wl=Ol,Pl=!!(Dl&&Dl.createEvent&&el.dispatchEvent),Ml="unhandledrejection",Ll=function(e){var t;return!(!cl(e)||!al(t=e.then))&&t},xl=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,l=e.reject,d=e.domain;try{a?(s||(2===t.rejection&&Hl(t),t.rejection=1),!0===a?i=o:(d&&d.enter(),i=a(o),d&&(d.exit(),r=!0)),i===e.promise?l(kl("Promise-chain cycle")):(n=Ll(i))?tl(n,i,c,l):c(i)):l(o)}catch(BU){d&&!r&&d.exit(),l(BU)}},Vl=function(e,t){e.notified||(e.notified=!0,hl((function(){for(var i,n=e.reactions;i=n.get();)xl(i,e);e.notified=!1,t&&!e.rejection&&Fl(e)})))},Ul=function(e,t,i){var n,r;Pl?((n=Dl.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),el.dispatchEvent(n)):n={promise:t,reason:i},!Il&&(r=el["on"+e])?r(n):e===Ml&&pl("Unhandled promise rejection",i)},Fl=function(e){tl(ul,el,(function(){var t,i=e.facade,n=e.value;if(Bl(e)&&(t=ml((function(){Zc?Nl.emit("unhandledRejection",n,i):Ul(Ml,i,n)})),e.rejection=Zc||Bl(e)?2:1,t.error))throw t.value}))},Bl=function(e){return 1!==e.rejection&&!e.parent},Hl=function(e){tl(ul,el,(function(){var t=e.facade;Zc?Nl.emit("rejectionHandled",t):Ul("rejectionhandled",t,e.value)}))},jl=function(e,t,i){return function(n){e(t,n,i)}},Gl=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Vl(e,!0))},Wl=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw kl("Promise can't be resolved itself");var n=Ll(t);n?hl((function(){var i={done:!1};try{tl(n,t,jl(Wl,i,e),jl(Gl,i,e))}catch(BU){Gl(i,BU,e)}})):(e.value=t,e.state=1,Vl(e,!1))}catch(BU){Gl({done:!1},BU,e)}}};if(Sl&&(bl=(Cl=function(e){ll(this,bl),sl(e),tl(qc,this);var t=yl(this);try{e(jl(Wl,t),jl(Gl,t))}catch(BU){Gl(t,BU)}}).prototype,(qc=function(e){Al(this,{type:El,done:!1,notified:!1,parent:!1,reactions:new _l,rejection:!1,state:0,value:void 0})}).prototype=il(bl,"then",(function(e,t){var i=yl(this),n=Ol(dl(this,Cl));return i.parent=!0,n.ok=!al(e)||e,n.fail=al(t)&&t,n.domain=Zc?Nl.domain:void 0,0==i.state?i.reactions.add(n):hl((function(){xl(n,i)})),n.promise})),Qc=function(){var e=new qc,t=yl(e);this.promise=e,this.resolve=jl(Wl,t),this.reject=jl(Gl,t)},Tl.f=Ol=function(e){return e===Cl||undefined===e?new Qc(e):wl(e)},al(gl)&&Rl!==Object.prototype)){Xc=Rl.then,vl||il(Rl,"then",(function(e,t){var i=this;return new Cl((function(e,t){tl(Xc,i,e,t)})).then(e,t)}),{unsafe:!0});try{delete Rl.constructor}catch(BU){}nl&&nl(Rl,bl)}$c({global:!0,constructor:!0,wrap:!0,forced:Sl},{Promise:Cl}),rl(Cl,El,!1),ol(El);var Jl=Bi,Kl=_e("iterator"),Yl=Array.prototype,zl=function(e){return void 0!==e&&(Jl.Array===e||Yl[Kl]===e)},ql=Vs,Ql=nt,Xl=T,$l=Bi,Zl=_e("iterator"),ed=function(e){if(!Xl(e))return Ql(e,Zl)||Ql(e,"@@iterator")||$l[ql(e)]},td=Fe,id=et,nd=Ce,rd=Qe,od=ed,sd=TypeError,ad=function(e,t){var i=arguments.length<2?od(e):t;if(id(i))return nd(td(i,e));throw sd(rd(e)+" is not iterable")},cd=Fe,ld=Ce,dd=nt,ud=function(e,t,i){var n,r;ld(e);try{if(!(n=dd(e,"return"))){if("throw"===t)throw i;return i}n=cd(n,e)}catch(BU){r=!0,n=BU}if("throw"===t)throw i;if(r)throw n;return ld(n),i},hd=va,pd=Fe,md=Ce,_d=Qe,fd=zl,gd=Gt,Td=Ge,Ed=ad,Sd=ed,Id=ud,vd=TypeError,yd=function(e,t){this.stopped=e,this.result=t},Ad=yd.prototype,Rd=function(e,t,i){var n,r,o,s,a,c,l,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),m=!(!i||!i.INTERRUPTED),_=hd(t,d),f=function(e){return n&&Id(n,"normal",e),new yd(!0,e)},g=function(e){return u?(md(e),m?_(e[0],e[1],f):_(e[0],e[1])):m?_(e,f):_(e)};if(h)n=e.iterator;else if(p)n=e;else{if(!(r=Sd(e)))throw vd(_d(e)+" is not iterable");if(fd(r)){for(o=0,s=gd(e);s>o;o++)if((a=g(e[o]))&&Td(Ad,a))return a;return new yd(!1)}n=Ed(e,r)}for(c=h?e.next:n.next;!(l=pd(c,n)).done;){try{a=g(l.value)}catch(BU){Id(n,"throw",BU)}if("object"==typeof a&&a&&Td(Ad,a))return a}return new yd(!1)},Cd=_e("iterator"),bd=!1;try{var kd=0,Dd={next:function(){return{done:!!kd++}},return:function(){bd=!0}};Dd[Cd]=function(){return this},Array.from(Dd,(function(){throw 2}))}catch(BU){}var Nd=function(e,t){if(!t&&!bd)return!1;var i=!1;try{var n={};n[Cd]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(BU){}return i},Od=kc,wd=Wc.CONSTRUCTOR||!Nd((function(e){Od.all(e).then(void 0,(function(){}))})),Pd=Fe,Md=et,Ld=Jc,xd=bc,Vd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{all:function(e){var t=this,i=Ld.f(t),n=i.resolve,r=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||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise}});var Ud=Vr,Fd=Wc.CONSTRUCTOR,Bd=kc,Hd=je,jd=Ee,Gd=ir,Wd=Bd&&Bd.prototype;if(Ud({target:"Promise",proto:!0,forced:Fd,real:!0},{catch:function(e){return this.then(void 0,e)}}),jd(Bd)){var Jd=Hd("Promise").prototype.catch;Wd.catch!==Jd&&Gd(Wd,"catch",Jd,{unsafe:!0})}var Kd=Fe,Yd=et,zd=Jc,qd=bc,Qd=Rd;Vr({target:"Promise",stat:!0,forced:wd},{race:function(e){var t=this,i=zd.f(t),n=i.reject,r=qd((function(){var r=Yd(t.resolve);Qd(e,(function(e){Kd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var Xd=Fe,$d=Jc;Vr({target:"Promise",stat:!0,forced:Wc.CONSTRUCTOR},{reject:function(e){var t=$d.f(this);return Xd(t.reject,void 0,e),t.promise}});var Zd=Ce,eu=ve,tu=Jc,iu=function(e,t){if(Zd(e),eu(t)&&t.constructor===e)return t;var i=tu.f(e);return(0,i.resolve)(t),i.promise},nu=Vr,ru=Wc.CONSTRUCTOR,ou=iu;je("Promise"),nu({target:"Promise",stat:!0,forced:ru},{resolve:function(e){return ou(this,e)}});var su=Ee,au=ve,cu=vo,lu=function(e,t,i){var n,r;return cu&&su(n=t.constructor)&&n!==i&&au(r=n.prototype)&&r!==i.prototype&&cu(e,r),e},du=ve,uu=h,hu=_e("match"),pu=function(e){var t;return du(e)&&(void 0!==(t=e[hu])?!!t:"RegExp"==uu(e))},mu=Vs,_u=String,fu=function(e){if("Symbol"===mu(e))throw TypeError("Cannot convert a Symbol value to a string");return _u(e)},gu=Ce,Tu=function(){var e=gu(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Eu=Fe,Su=G,Iu=Ge,vu=Tu,yu=RegExp.prototype,Au=function(e){var t=e.flags;return void 0!==t||"flags"in yu||Su(e,"flags")||!Iu(yu,e)?t:Eu(vu,e)},Ru=i,Cu=C.RegExp,bu=Ru((function(){var e=Cu("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),ku=bu||Ru((function(){return!Cu("a","y").sticky})),Du=bu||Ru((function(){var e=Cu("^r","gy");return e.lastIndex=2,null!=e.exec("str")})),Nu={BROKEN_CARET:Du,MISSED_STICKY:ku,UNSUPPORTED_Y:bu},Ou=Ne.f,wu=i,Pu=C.RegExp,Mu=wu((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=Dr,ju=lu,Gu=Yi,Wu=nr.f,Ju=Ge,Ku=pu,Yu=fu,zu=Au,qu=Nu,Qu=function(e,t,i){i in e||Ou(e,i,{configurable:!0,get:function(){return t[i]},set:function(e){t[i]=e}})},Xu=ir,$u=i,Zu=G,eh=cn.enforce,th=Cs,ih=Mu,nh=Vu,rh=_e("match"),oh=Fu.RegExp,sh=oh.prototype,ah=Fu.SyntaxError,ch=Bu(sh.exec),lh=Bu("".charAt),dh=Bu("".replace),uh=Bu("".indexOf),hh=Bu("".slice),ph=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,mh=/a/g,_h=/a/g,fh=new oh(mh)!==mh,gh=qu.MISSED_STICKY,Th=qu.UNSUPPORTED_Y,Eh=Uu&&(!fh||gh||ih||nh||$u((function(){return _h[rh]=!1,oh(mh)!=mh||oh(_h)==_h||"/a/i"!=oh(mh,"i")})));if(Hu("RegExp",Eh)){for(var Sh=function(e,t){var i,n,r,o,s,a,c=Ju(sh,this),l=Ku(e),d=void 0===t,u=[],h=e;if(!c&&l&&d&&e.constructor===Sh)return e;if((l||Ju(sh,e))&&(e=e.source,d&&(t=zu(h))),e=void 0===e?"":Yu(e),t=void 0===t?"":Yu(t),h=e,ih&&"dotAll"in mh&&(n=!!t&&uh(t,"s")>-1)&&(t=dh(t,/s/g,"")),i=t,gh&&"sticky"in mh&&(r=!!t&&uh(t,"y")>-1)&&Th&&(t=dh(t,/y/g,"")),nh&&(o=function(e){for(var t,i=e.length,n=0,r="",o=[],s={},a=!1,c=!1,l=0,d="";n<=i;n++){if("\\"===(t=lh(e,n)))t+=lh(e,++n);else if("]"===t)a=!1;else if(!a)switch(!0){case"["===t:a=!0;break;case"("===t:ch(ph,hh(e,n+1))&&(n+=2,c=!0),r+=t,l++;continue;case">"===t&&c:if(""===d||Zu(s,d))throw new ah("Invalid capture group name");s[d]=!0,o[o.length]=[d,l],c=!1,d="";continue}c?d+=t:r+=t}return[r,o]}(e),e=o[0],u=o[1]),s=ju(oh(e,t),c?this:sh,Sh),(n||r||u.length)&&(a=eh(s),n&&(a.dotAll=!0,a.raw=Sh(function(e){for(var t,i=e.length,n=0,r="",o=!1;n<=i;n++)"\\"!==(t=lh(e,n))?o||"."!==t?("["===t?o=!0:"]"===t&&(o=!1),r+=t):r+="[\\s\\S]":r+=t+lh(e,++n);return r}(e),i)),r&&(a.sticky=!0),u.length&&(a.groups=u)),e!==h)try{Gu(s,"source",""===h?"(?:)":h)}catch(BU){}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=Nu,kh=Ni,Dh=cn.get,Nh=Mu,Oh=Vu,wh=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||Nh||Oh)&&(Mh=function(e){var t,i,n,r,o,s,a,c=this,l=Dh(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&&(n=c.lastIndex),r=yh(Ph,p?i:c,g),p?r?(r.input=Uh(r.input,f),r[0]=Uh(r[0],f),r.index=c.lastIndex,c.lastIndex+=r[0].length):c.lastIndex=0:Fh&&r&&(c.lastIndex=c.global?r.index+r[0].length:n),Hh&&r&&r.length>1&&yh(wh,r[0],i,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(r[o]=void 0)})),r&&h)for(r.groups=s=kh(null),o=0;o<h.length;o++)s[(a=h[o])[0]]=r[a[1]];return r});var jh=Mh;Vr({target:"RegExp",proto:!0,forced:/./.exec!==jh},{exec:jh});var Gh=h,Wh=Array.isArray||function(e){return"Array"==Gh(e)},Jh=Wh,Kh=ta,Yh=ve,zh=_e("species"),qh=Array,Qh=function(e){var t;return Jh(e)&&(t=e.constructor,(Kh(t)&&(t===qh||Jh(t.prototype))||Yh(t)&&null===(t=t[zh]))&&(t=void 0)),void 0===t?qh:t},Xh=va,$h=g,Zh=B,ep=Gt,tp=function(e,t){return new(Qh(e))(0===t?0:t)},ip=c([].push),np=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,l,d,u){for(var h,p,m=Zh(c),_=$h(m),f=Xh(l,d),g=ep(_),T=0,E=u||tp,S=t?E(c,g):i||s?E(c,0):void 0;g>T;T++)if((a||T in _)&&(p=f(h=_[T],T,m),e))if(t)S[T]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return T;case 2:ip(S,h)}else switch(e){case 4:return!1;case 7:ip(S,h)}return o?-1:n||r?r:S}},rp={forEach:np(0),map:np(1),filter:np(2),some:np(3),every:np(4),find:np(5),findIndex:np(6),filterReject:np(7)},op=i,sp=function(e,t){var i=[][e];return!!i&&op((function(){i.call(null,t||function(){return 1},1)}))},ap=rp.forEach,cp=sp("forEach")?[].forEach:function(e){return ap(this,e,arguments.length>1?arguments[1]:void 0)},lp=C,dp=ns,up=ss,hp=cp,pp=Yi,mp=function(e){if(e&&e.forEach!==hp)try{pp(e,"forEach",hp)}catch(BU){e.forEach=hp}};for(var _p in dp)dp[_p]&&mp(lp[_p]&&lp[_p].prototype);mp(up);var fp=et,gp=B,Tp=g,Ep=Gt,Sp=TypeError,Ip=function(e){return function(t,i,n,r){fp(i);var o=gp(t),s=Tp(o),a=Ep(o),c=e?a-1:0,l=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=l;break}if(c+=l,e?c<0:a<=c)throw Sp("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=l)c in s&&(r=i(r,s[c],c,o));return r}},vp={left:Ip(!1),right:Ip(!0)}.left;Vr({target:"Array",proto:!0,forced:!Ts&&ie>79&&ie<83||!sp("reduce")},{reduce:function(e){var t=arguments.length;return vp(this,e,t,t>1?arguments[1]:void 0)}});var yp=Ta,Ap=ir,Rp=jh,Cp=i,bp=_e,kp=Yi,Dp=bp("species"),Np=RegExp.prototype,Op=c,wp=Mt,Pp=fu,Mp=I,Lp=Op("".charAt),xp=Op("".charCodeAt),Vp=Op("".slice),Up=function(e){return function(t,i){var n,r,o=Pp(Mp(t)),s=wp(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=xp(o,s))<55296||n>56319||s+1===a||(r=xp(o,s+1))<56320||r>57343?e?Lp(o,s):n:e?Vp(o,s,s+2):r-56320+(n-55296<<10)+65536}},Fp={codeAt:Up(!1),charAt:Up(!0)},Bp=Fp.charAt,Hp=c,jp=B,Gp=Math.floor,Wp=Hp("".charAt),Jp=Hp("".replace),Kp=Hp("".slice),Yp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,qp=function(e,t,i,n,r,o){var s=i+e.length,a=n.length,c=zp;return void 0!==r&&(r=jp(r),c=Yp),Jp(o,c,(function(o,c){var l;switch(Wp(c,0)){case"$":return"$";case"&":return e;case"`":return Kp(t,0,i);case"'":return Kp(t,s);case"<":l=r[Kp(c,1,-1)];break;default:var d=+c;if(0===d)return o;if(d>a){var u=Gp(d/10);return 0===u?o:u<=a?void 0===n[u-1]?Wp(c,1):n[u-1]+Wp(c,1):o}l=n[d-1]}return void 0===l?"":l}))},Qp=Fe,Xp=Ce,$p=Ee,Zp=h,em=jh,tm=TypeError,im=_a,nm=Fe,rm=c,om=function(e,t,i,n){var r=bp(e),o=!Cp((function(){var t={};return t[r]=function(){return 7},7!=""[e](t)})),s=o&&!Cp((function(){var t=!1,i=/a/;return"split"===e&&((i={}).constructor={},i.constructor[Dp]=function(){return i},i.flags="",i[r]=/./[r]),i.exec=function(){return t=!0,null},i[r](""),!t}));if(!o||!s||i){var a=yp(/./[r]),c=t(r,""[e],(function(e,t,i,n,r){var s=yp(e),c=t.exec;return c===Rp||c===Np.exec?o&&!r?{done:!0,value:a(t,i,n)}:{done:!0,value:s(i,t,n)}:{done:!1}}));Ap(String.prototype,e,c[0]),Ap(Np,r,c[1])}n&&kp(Np[r],"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=nt,fm=qp,gm=function(e,t){var i=e.exec;if($p(i)){var n=Qp(i,e,t);return null!==n&&Xp(n),n}if("RegExp"===Zp(e))return Qp(em,e,t);throw tm("RegExp#exec called on incompatible receiver")},Tm=_e("replace"),Em=Math.max,Sm=Math.min,Im=rm([].concat),vm=rm([].push),ym=rm("".indexOf),Am=rm("".slice),Rm=function(e){return void 0===e?e:String(e)},Cm="$0"==="a".replace(/./,"$0"),bm=!!/./[Tm]&&""===/./[Tm]("a","$0"),km=!sm((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));om("replace",(function(e,t,i){var n=bm?"$":"$0";return[function(e,i){var n=pm(this),r=lm(e)?void 0:_m(e,Tm);return r?nm(r,e,n,i):nm(t,hm(n),e,i)},function(e,r){var o=am(this),s=hm(e);if("string"==typeof r&&-1===ym(r,n)&&-1===ym(r,"$<")){var a=i(t,o,s,r);if(a.done)return a.value}var c=cm(r);c||(r=hm(r));var l=o.global;if(l){var d=o.unicode;o.lastIndex=0}for(var u=[];;){var h=gm(o,s);if(null===h)break;if(vm(u,h),!l)break;""===hm(h[0])&&(o.lastIndex=mm(s,um(o.lastIndex),d))}for(var p="",m=0,_=0;_<u.length;_++){for(var f=hm((h=u[_])[0]),g=Em(Sm(dm(h.index),s.length),0),T=[],E=1;E<h.length;E++)vm(T,Rm(h[E]));var S=h.groups;if(c){var I=Im([f],T,g,s);void 0!==S&&vm(I,S);var v=hm(im(r,void 0,I))}else v=fm(f,s,g,T,S,r);g>=m&&(p+=Am(s,m,g)+v,m=g+f.length)}return p+Am(s,m)}]}),!km||!Cm||bm);var Dm=zt.includes,Nm=Fi;Vr({target:"Array",proto:!0,forced:i((function(){return!Array(1).includes()}))},{includes:function(e){return Dm(this,e,arguments.length>1?arguments[1]:void 0)}}),Nm("includes");var Om=Mt,wm=fu,Pm=I,Mm=RangeError,Lm=c,xm=Ht,Vm=fu,Um=function(e){var t=wm(Pm(this)),i="",n=Om(e);if(n<0||Infinity==n)throw Mm("Wrong number of repetitions");for(;n>0;(n>>>=1)&&(t+=t))1&n&&(i+=t);return i},Fm=I,Bm=Lm(Um),Hm=Lm("".slice),jm=Math.ceil,Gm=function(e){return function(t,i,n){var r,o,s=Vm(Fm(t)),a=xm(i),c=s.length,l=void 0===n?" ":Vm(n);return a<=c||""==l?s:((o=Bm(l,jm((r=a-c)/l.length))).length>r&&(o=Hm(o,0,r)),e?s+o:o+s)}},Wm={start:Gm(!1),end:Gm(!0)},Jm=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(q),Km=Wm.start;Vr({target:"String",proto:!0,forced:Jm},{padStart:function(e){return Km(this,e,arguments.length>1?arguments[1]:void 0)}});var Ym=i,zm=ke,qm=_e("iterator"),Qm=!Ym((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),!t.size&&!zm||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[qm]||"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=ir,$m=function(e,t,i){for(var n in t)Xm(e,n,t[n],i);return e},Zm=Tt,e_=Ne,t_=Wi,i_=function(e,t,i){var n=Zm(t);n in e?e_.f(e,n,t_(0,i)):e[n]=i},n_=Ut,r_=Gt,o_=i_,s_=Array,a_=Math.max,c_=function(e,t,i){for(var n=r_(e),r=n_(t,n),o=n_(void 0===i?n:i,n),s=s_(a_(o-r,0)),a=0;r<o;r++,a++)o_(s,a,e[r]);return s.length=a,s},l_=c_,d_=Math.floor,u_=function(e,t){var i=e.length,n=d_(i/2);return i<8?h_(e,t):p_(e,u_(l_(e,0,n),t),u_(l_(e,n),t),t)},h_=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},p_=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},m_=u_,__=Vr,f_=C,g_=Fe,T_=c,E_=ke,S_=Qm,I_=ir,v_=Is,y_=$m,A_=oo,R_=po,C_=cn,b_=Ds,k_=Ee,D_=G,N_=va,O_=Vs,w_=Ce,P_=ve,M_=fu,L_=Ni,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_),Y_=Object.getOwnPropertyDescriptor,z_=function(e){if(!E_)return f_[e];var t=Y_(f_,e);return t&&t.value},q_=z_("fetch"),Q_=z_("Request"),X_=z_("Headers"),$_=Q_&&Q_.prototype,Z_=X_&&X_.prototype,ef=f_.RegExp,tf=f_.TypeError,nf=f_.decodeURIComponent,rf=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 nf(e)}catch(BU){return e}},gf=function(e){var t=cf(e,pf," "),i=4;try{return nf(t)}catch(BU){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(rf(e),Tf,Sf)},vf=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(),n=i.value;return i.done||(i.value="keys"===t?n.key:"values"===t?n.value:[n.key,n.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,n,r,o,s,a,c=U_(e);if(c)for(i=(t=V_(e,c)).next;!(n=g_(i,t)).done;){if(o=(r=V_(w_(n.value))).next,(s=g_(o,r)).done||(a=g_(o,r)).done||!g_(o,r).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)D_(e,l)&&af(this.entries,{key:l,value:M_(e[l])})},parseQuery:function(e){if(e)for(var t,i,n=uf(e,"&"),r=0;r<n.length;)(t=n[r++]).length&&(i=uf(t,"="),af(this.entries,{key:gf(lf(i)),value:gf(sf(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],n=0;n<t.length;)e=t[n++],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,n=M_(e),r=0;r<i.length;)i[r].key===n?df(i,r,1):r++;E_||(this.length=i.length),t.updateURL()},get:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),n=0;n<t.length;n++)if(t[n].key===i)return t[n].value;return null},getAll:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),n=[],r=0;r<t.length;r++)t[r].key===i&&af(n,t[r].value);return n},has:function(e){F_(arguments.length,1);for(var t=J_(this).entries,i=M_(e),n=0;n<t.length;)if(t[n++].key===i)return!0;return!1},set:function(e,t){F_(arguments.length,1);for(var i,n=J_(this),r=n.entries,o=!1,s=M_(e),a=M_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?df(r,c--,1):(o=!0,i.value=a));o||af(r,{key:s,value:a}),E_||(this.length=r.length),n.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,n=N_(e,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((t=i[r++]).value,t.key,this)},keys:function(){return new 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(O_(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_(q_)&&__({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return q_(e,arguments.length>1?kf(arguments[1]):{})}}),k_(Q_)){var Df=function(e){return b_(this,$_),new Q_(e,arguments.length>1?kf(arguments[1]):{})};$_.constructor=Df,Df.prototype=$_,__({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Df})}}var Nf={URLSearchParams:Af,getState:J_},Of="\t\n\v\f\r \u2028\u2029\ufeff",wf=I,Pf=fu,Mf=Of,Lf=c("".replace),xf=RegExp("^["+Mf+"]+"),Vf=RegExp("(^|[^"+Mf+"])["+Mf+"]+$"),Uf=function(e){return function(t){var i=Pf(wf(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=Nn.PROPER,Hf=i,jf=Of,Gf=Ff.trim;Vr({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=Vr,Jf=ke,Kf=c,Yf=G,zf=Ee,qf=Ge,Qf=fu,Xf=Is,$f=Sr,Zf=C.Symbol,eg=Zf&&Zf.prototype;if(Jf&&zf(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=qf(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 ng="Symbol(test)"==String(Zf("test")),rg=Kf(eg.valueOf),og=Kf(eg.toString),sg=/^Symbol\((.*)\)[^)]+$/,ag=Kf("".replace),cg=Kf("".slice);Xf(eg,"description",{configurable:!0,get:function(){var e=rg(this);if(Yf(tg,e))return"";var t=og(e),i=ng?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=cn,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,n=t.index;return n>=i.length?pg(void 0,!0):(e=lg(i,n),t.index+=e.length,pg(e,!1))}));var gg,Tg=ke,Eg=c,Sg=Fe,Ig=i,vg=oi,yg=sr,Ag=dn,Rg=B,Cg=g,bg=Object.assign,kg=Object.defineProperty,Dg=Eg([].concat),Ng=!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(),n="abcdefghijklmnopqrst";return e[i]=7,n.split("").forEach((function(e){t[e]=e})),7!=bg({},e)[i]||vg(bg({},t)).join("")!=n}))?function(e,t){for(var i=Rg(e),n=arguments.length,r=1,o=yg.f,s=Ag.f;n>r;)for(var a,c=Cg(arguments[r++]),l=o?Dg(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,Og=Ce,wg=ud,Pg=va,Mg=Fe,Lg=B,xg=function(e,t,i,n){try{return n?t(Og(i)[0],i[1]):t(i)}catch(BU){wg(e,"throw",BU)}},Vg=zl,Ug=ta,Fg=Gt,Bg=i_,Hg=ad,jg=ed,Gg=Array,Wg=c,Jg=2147483647,Kg=/[^\0-\u007E]/,Yg=/[.\u3002\uFF0E\uFF61]/g,zg="Overflow: input needs wider integers to process",qg=RangeError,Qg=Wg(Yg.exec),Xg=Math.floor,$g=String.fromCharCode,Zg=Wg("".charCodeAt),eT=Wg([].join),tT=Wg([].push),iT=Wg("".replace),nT=Wg("".split),rT=Wg("".toLowerCase),oT=function(e){return e+22+75*(e<26)},sT=function(e,t,i){var n=0;for(e=i?Xg(e/700):e>>1,e+=Xg(e/t);e>455;)e=Xg(e/35),n+=36;return Xg(n+36*e/(e+38))},aT=function(e){var t=[];e=function(e){for(var t=[],i=0,n=e.length;i<n;){var r=Zg(e,i++);if(r>=55296&&r<=56319&&i<n){var o=Zg(e,i++);56320==(64512&o)?tT(t,((1023&r)<<10)+(1023&o)+65536):(tT(t,r),i--)}else tT(t,r)}return t}(e);var i,n,r=e.length,o=128,s=0,a=72;for(i=0;i<e.length;i++)(n=e[i])<128&&tT(t,$g(n));var c=t.length,l=c;for(c&&tT(t,"-");l<r;){var d=Jg;for(i=0;i<e.length;i++)(n=e[i])>=o&&n<d&&(d=n);var u=l+1;if(d-o>Xg((Jg-s)/u))throw qg(zg);for(s+=(d-o)*u,o=d,i=0;i<e.length;i++){if((n=e[i])<o&&++s>Jg)throw qg(zg);if(n==o){for(var h=s,p=36;;){var m=p<=a?1:p>=a+26?26:p-a;if(h<m)break;var _=h-m,f=36-m;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=Vr,lT=ke,dT=Qm,uT=C,hT=va,pT=c,mT=ir,_T=Is,fT=Ds,gT=G,TT=Ng,ET=function(e){var t=Lg(e),i=Ug(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=void 0!==r;o&&(r=Pg(r,n>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?r(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,r,[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,n=[],r=nT(iT(rT(e),Yg,"."),".");for(t=0;t<r.length;t++)i=r[t],tT(n,Qg(Kg,i)?"xn--"+aT(i):i);return eT(n,".")},yT=fu,AT=oo,RT=Ra,CT=Nf,bT=cn,kT=bT.set,DT=bT.getterFor("URL"),NT=CT.URLSearchParams,OT=CT.getState,wT=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),KT=pT("".slice),YT=pT("".toLowerCase),zT=pT([].unshift),qT="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]+$/,nE=/^\d+$/,rE=/^[\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,n,r;if("number"==typeof e){for(t=[],i=0;i<4;i++)zT(t,e%256),e=LT(e/256);return FT(t,".")}if("object"==typeof e){for(t="",n=function(e){for(var t=null,i=1,n=null,r=0,o=0;o<8;o++)0!==e[o]?(r>i&&(t=n,i=r),n=null,r=0):(null===n&&(n=o),++r);return r>i&&(t=n,i=r),t}(e),i=0;i<8;i++)r&&0===e[i]||(r&&(r=!1),n===i?(t+=i?":":"::",r=!0):(t+=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(KT(e,0,2))&&(2==e.length||"/"===(t=VT(e,2))||"\\"===t||"?"===t||"#"===t)},EE=function(e){return"."===e||"%2e"===YT(e)},SE={},IE={},vE={},yE={},AE={},RE={},CE={},bE={},kE={},DE={},NE={},OE={},wE={},PE={},ME={},LE={},xE={},VE={},UE={},FE={},BE={},HE=function(e,t,i){var n,r,o,s=yT(e);if(t){if(r=this.parse(s))throw PT(r);this.searchParams=null}else{if(void 0!==i&&(n=new HE(i,!0)),r=this.parse(s,null,n))throw PT(r);(o=OT(new NT)).bindURL(this),this.searchParams=o}};HE.prototype={type:"URL",parse:function(e,t,i){var n,r,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,""),n=ET(e);d<=n.length;){switch(r=n[d],l){case SE:if(!r||!UT($T,r)){if(t)return qT;l=vE;continue}u+=YT(r),l=IE;break;case IE:if(r&&(UT(ZT,r)||"+"==r||"-"==r||"."==r))u+=YT(r);else{if(":"!=r){if(t)return qT;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:"/"==n[d+1]?(l=AE,d++):(c.cannotBeABaseURL=!0,jT(c.path,""),l=UE)}break;case vE:if(!i||i.cannotBeABaseURL&&"#"!=r)return qT;if(i.cannotBeABaseURL&&"#"==r){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("/"!=r||"/"!=n[d+1]){l=RE;continue}l=kE,d++;break;case AE:if("/"==r){l=DE;break}l=VE;continue;case RE:if(c.scheme=i.scheme,r==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("/"==r||"\\"==r&&c.isSpecial())l=CE;else if("?"==r)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("#"!=r){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()||"/"!=r&&"\\"!=r){if("/"!=r){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,l=VE;continue}l=DE}else l=kE;break;case bE:if(l=kE,"/"!=r||"/"!=VT(u,d+1))continue;d++;break;case kE:if("/"!=r&&"\\"!=r){l=DE;continue}break;case DE:if("@"==r){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(r==gg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(h&&""==u)return"Invalid authority";d-=ET(u).length+1,u="",l=NE}else u+=r;break;case NE:case OE:if(t&&"file"==c.scheme){l=LE;continue}if(":"!=r||p){if(r==gg||"/"==r||"?"==r||"#"==r||"\\"==r&&c.isSpecial()){if(c.isSpecial()&&""==u)return QT;if(t&&""==u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",l=xE,t)return;continue}"["==r?p=!0:"]"==r&&(p=!1),u+=r}else{if(""==u)return QT;if(s=c.parseHost(u))return s;if(u="",l=wE,t==OE)return}break;case wE:if(!UT(eE,r)){if(r==gg||"/"==r||"?"==r||"#"==r||"\\"==r&&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+=r;break;case PE:if(c.scheme="file","/"==r||"\\"==r)l=ME;else{if(!i||"file"!=i.scheme){l=VE;continue}if(r==gg)c.host=i.host,c.path=ST(i.path),c.query=i.query;else if("?"==r)c.host=i.host,c.path=ST(i.path),c.query="",l=FE;else{if("#"!=r){TE(FT(ST(n,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("/"==r||"\\"==r){l=LE;break}i&&"file"==i.scheme&&!TE(FT(ST(n,d),""))&&(gE(i.path[0],!0)?jT(c.path,i.path[0]):c.host=i.host),l=VE;continue;case LE:if(r==gg||"/"==r||"\\"==r||"?"==r||"#"==r){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+=r;break;case xE:if(c.isSpecial()){if(l=VE,"/"!=r&&"\\"!=r)continue}else if(t||"?"!=r)if(t||"#"!=r){if(r!=gg&&(l=VE,"/"!=r))continue}else c.fragment="",l=BE;else c.query="",l=FE;break;case VE:if(r==gg||"/"==r||"\\"==r&&c.isSpecial()||!t&&("?"==r||"#"==r)){if(".."===(a=YT(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"==r||"\\"==r&&c.isSpecial()||jT(c.path,"")):EE(u)?"/"==r||"\\"==r&&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&&(r==gg||"?"==r||"#"==r))for(;c.path.length>1&&""===c.path[0];)WT(c.path);"?"==r?(c.query="",l=FE):"#"==r&&(c.fragment="",l=BE)}else u+=_E(r,pE);break;case UE:"?"==r?(c.query="",l=FE):"#"==r?(c.fragment="",l=BE):r!=gg&&(c.path[0]+=_E(r,uE));break;case FE:t||"#"!=r?r!=gg&&("'"==r&&c.isSpecial()?c.query+="%27":c.query+="#"==r?"%23":_E(r,uE)):(c.fragment="",l=BE);break;case BE:r!=gg&&(c.fragment+=_E(r,hE))}d++}},parseHost:function(e){var t,i,n;if("["==VT(e,0)){if("]"!=VT(e,e.length-1))return QT;if(t=function(e){var t,i,n,r,o,s,a,c=[0,0,0,0,0,0,0,0],l=0,d=null,u=0,h=function(){return 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(rE,h());)t=16*t+MT(h(),16),u++,i++;if("."==h()){if(0==i)return;if(u-=i,l>6)return;for(n=0;h();){if(r=null,n>0){if(!("."==h()&&n<4))return;u++}if(!UT(eE,h()))return;for(;UT(eE,h());){if(o=MT(h(),10),null===r)r=o;else{if(0==r)return;r=10*r+o}if(r>255)return;u++}c[l]=256*c[l]+r,2!=++n&&4!=n||l++}if(4!=n)return;break}if(":"==h()){if(u++,!h())return}else if(h())return;c[l++]=t}else{if(null!==d)return;u++,d=++l}}if(null!==d)for(s=l-d,l=7;0!=l&&s>0;)a=c[l],c[l--]=c[d+s-1],c[d+--s]=a;else if(8!=l)return;return c}(KT(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,n,r,o,s,a,c=JT(e,".");if(c.length&&""==c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],n=0;n<t;n++){if(""==(r=c[n]))return e;if(o=10,r.length>1&&"0"==VT(r,0)&&(o=UT(tE,r)?16:8,r=KT(r,8==o?1:2)),""===r)s=0;else{if(!UT(10==o?nE:8==o?iE:rE,r))return e;s=MT(r,o)}jT(i,s)}for(n=0;n<t;n++)if(s=i[n],n==t-1){if(s>=xT(256,5-t))return null}else if(s>255)return null;for(a=HT(i),n=0;n<i.length;n++)a+=i[n]*xT(256,3-n);return a}(e),null===t)return QT;this.host=t}else{if(UT(sE,e))return QT;for(t="",i=ET(e),n=0;n<i.length;n++)t+=_E(i[n],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,n=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,l=t+":";return null!==r?(l+="//",e.includesCredentials()&&(l+=i+(n?":"+n:"")+"@"),l+=dE(r),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(BU){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,NE)},getHostname:function(){var e=this.host;return null===e?"":dE(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,OE)},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,wE))},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=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=yT(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,n=kT(t,new HE(e,!1,i));lT||(t.href=n.serialize(),t.origin=n.getOrigin(),t.protocol=n.getProtocol(),t.username=n.getUsername(),t.password=n.getPassword(),t.host=n.getHost(),t.hostname=n.getHostname(),t.port=n.getPort(),t.pathname=n.getPathname(),t.search=n.getSearch(),t.searchParams=n.getSearchParams(),t.hash=n.getHash())},GE=jE.prototype,WE=function(e,t){return{get:function(){return DT(this)[e]()},set:t&&function(e){return DT(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 DT(this).serialize()}),{enumerable:!0}),mT(GE,"toString",(function(){return DT(this).serialize()}),{enumerable:!0}),wT){var JE=wT.createObjectURL,KE=wT.revokeObjectURL;JE&&mT(jE,"createObjectURL",hT(JE,wT)),KE&&mT(jE,"revokeObjectURL",hT(KE,wT))}AT(jE,"URL"),cT({global:!0,constructor:!0,forced:!dT,sham:!lT},{URL:jE});var YE=Vr,zE=kc,qE=i,QE=je,XE=Ee,$E=da,ZE=iu,eS=ir,tS=zE&&zE.prototype;if(YE({target:"Promise",proto:!0,real:!0,forced:!!zE&&qE((function(){tS.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=$E(this,QE("Promise")),i=XE(e);return this.then(i?function(i){return ZE(t,e()).then((function(){return i}))}:e,i?function(i){return ZE(t,e()).then((function(){throw i}))}:e)}}),XE(zE)){var iS=QE("Promise").prototype.finally;tS.finally!==iS&&eS(tS,"finally",iS,{unsafe:!0})}var nS="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,rS=Mt,oS=Ht,sS=RangeError,aS=function(e){if(void 0===e)return 0;var t=rS(e),i=oS(t);if(t!==i)throw sS("Wrong length or index");return i},cS=Array,lS=Math.abs,dS=Math.pow,uS=Math.floor,hS=Math.log,pS=Math.LN2,mS={pack:function(e,t,i){var n,r,o,s=cS(i),a=8*i-t-1,c=(1<<a)-1,l=c>>1,d=23===t?dS(2,-24)-dS(2,-77):0,u=e<0||0===e&&1/e<0?1:0,h=0;for((e=lS(e))!=e||Infinity===e?(r=e!=e?1:0,n=c):(n=uS(hS(e)/pS),e*(o=dS(2,-n))<1&&(n--,o*=2),(e+=n+l>=1?d/o:d*dS(2,1-l))*o>=2&&(n++,o/=2),n+l>=c?(r=0,n=c):n+l>=1?(r=(e*o-1)*dS(2,t),n+=l):(r=e*dS(2,l-1)*dS(2,t),n=0));t>=8;)s[h++]=255&r,r/=256,t-=8;for(n=n<<t|r,a+=t;a>0;)s[h++]=255&n,n/=256,a-=8;return s[--h]|=128*u,s},unpack:function(e,t){var i,n=e.length,r=8*n-t-1,o=(1<<r)-1,s=o>>1,a=r-7,c=n-1,l=e[c--],d=127&l;for(l>>=7;a>0;)d=256*d+e[c--],a-=8;for(i=d&(1<<-a)-1,d>>=-a,a+=t;a>0;)i=256*i+e[c--],a-=8;if(0===d)d=1-s;else{if(d===o)return i?NaN:l?-Infinity:Infinity;i+=dS(2,t),d-=s}return(l?-1:1)*i*dS(2,d-t)}},_S=B,fS=Ut,gS=Gt,TS=function(e){for(var t=_S(this),i=gS(t),n=arguments.length,r=fS(n>1?arguments[1]:void 0,i),o=n>2?arguments[2]:void 0,s=void 0===o?i:fS(o,i);s>r;)t[r++]=e;return t},ES=C,SS=c,IS=ke,vS=nS,yS=Nn,AS=Yi,RS=Is,CS=$m,bS=i,kS=Ds,DS=Mt,NS=Ht,OS=aS,wS=mS,PS=Kr,MS=vo,LS=nr.f,xS=TS,VS=c_,US=oo,FS=cn,BS=yS.PROPER,HS=yS.CONFIGURABLE,jS="ArrayBuffer",GS="DataView",WS="prototype",JS="Wrong index",KS=FS.getterFor(jS),YS=FS.getterFor(GS),zS=FS.set,qS=ES[jS],QS=qS,XS=QS&&QS[WS],$S=ES[GS],ZS=$S&&$S[WS],eI=Object.prototype,tI=ES.Array,iI=ES.RangeError,nI=SS(xS),rI=SS([].reverse),oI=wS.pack,sI=wS.unpack,aI=function(e){return[255&e]},cI=function(e){return[255&e,e>>8&255]},lI=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},dI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},uI=function(e){return oI(e,23,4)},hI=function(e){return oI(e,52,8)},pI=function(e,t,i){RS(e[WS],t,{configurable:!0,get:function(){return i(this)[t]}})},mI=function(e,t,i,n){var r=OS(i),o=YS(e);if(r+t>o.byteLength)throw iI(JS);var s=o.bytes,a=r+o.byteOffset,c=VS(s,a,a+t);return n?c:rI(c)},_I=function(e,t,i,n,r,o){var s=OS(i),a=YS(e);if(s+t>a.byteLength)throw iI(JS);for(var c=a.bytes,l=s+a.byteOffset,d=n(+r),u=0;u<t;u++)c[l+u]=d[o?u:t-u-1]};if(vS){var fI=BS&&qS.name!==jS;if(bS((function(){qS(1)}))&&bS((function(){new qS(-1)}))&&!bS((function(){return new qS,new qS(1.5),new qS(NaN),1!=qS.length||fI&&!HS})))fI&&HS&&AS(qS,"name",jS);else{(QS=function(e){return kS(this,XS),new qS(OS(e))})[WS]=XS;for(var gI,TI=LS(qS),EI=0;TI.length>EI;)(gI=TI[EI++])in QS||AS(QS,gI,qS[gI]);XS.constructor=QS}MS&&PS(ZS)!==eI&&MS(ZS,eI);var SI=new $S(new QS(2)),II=SS(ZS.setInt8);SI.setInt8(0,2147483648),SI.setInt8(1,2147483649),!SI.getInt8(0)&&SI.getInt8(1)||CS(ZS,{setInt8:function(e,t){II(this,e,t<<24>>24)},setUint8:function(e,t){II(this,e,t<<24>>24)}},{unsafe:!0})}else XS=(QS=function(e){kS(this,XS);var t=OS(e);zS(this,{type:jS,bytes:nI(tI(t),0),byteLength:t}),IS||(this.byteLength=t,this.detached=!1)})[WS],ZS=($S=function(e,t,i){kS(this,ZS),kS(e,XS);var n=KS(e),r=n.byteLength,o=DS(t);if(o<0||o>r)throw iI("Wrong offset");if(o+(i=void 0===i?r-o:NS(i))>r)throw iI("Wrong length");zS(this,{type:GS,buffer:e,byteLength:i,byteOffset:o,bytes:n.bytes}),IS||(this.buffer=e,this.byteLength=i,this.byteOffset=o)})[WS],IS&&(pI(QS,"byteLength",KS),pI($S,"buffer",YS),pI($S,"byteLength",YS),pI($S,"byteOffset",YS)),CS(ZS,{getInt8:function(e){return mI(this,1,e)[0]<<24>>24},getUint8:function(e){return mI(this,1,e)[0]},getInt16:function(e){var t=mI(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=mI(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return dI(mI(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return dI(mI(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return sI(mI(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return sI(mI(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){_I(this,1,e,aI,t)},setUint8:function(e,t){_I(this,1,e,aI,t)},setInt16:function(e,t){_I(this,2,e,cI,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){_I(this,2,e,cI,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){_I(this,4,e,lI,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){_I(this,4,e,lI,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){_I(this,4,e,uI,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){_I(this,8,e,hI,t,arguments.length>2?arguments[2]:void 0)}});US(QS,jS),US($S,GS);var vI={ArrayBuffer:QS,DataView:$S},yI=Cs,AI="ArrayBuffer",RI=vI[AI];Vr({global:!0,constructor:!0,forced:C[AI]!==RI},{ArrayBuffer:RI}),yI(AI);var CI=Vr,bI=Ta,kI=i,DI=Ce,NI=Ut,OI=Ht,wI=da,PI=vI.ArrayBuffer,MI=vI.DataView,LI=MI.prototype,xI=bI(PI.prototype.slice),VI=bI(LI.getUint8),UI=bI(LI.setUint8);CI({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:kI((function(){return!new PI(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(xI&&void 0===t)return xI(DI(this),e);for(var i=DI(this).byteLength,n=NI(e,i),r=NI(void 0===t?i:t,i),o=new(wI(this,PI))(OI(r-n)),s=new MI(this),a=new MI(o),c=0;n<r;)UI(a,c++,VI(s,n++));return o}});var FI,BI,HI,jI={},GI={get exports(){return jI},set exports(e){jI=e}},WI=nS,JI=ke,KI=C,YI=Ee,zI=ve,qI=G,QI=Vs,XI=Qe,$I=Yi,ZI=ir,ev=Is,tv=Ge,iv=Kr,nv=vo,rv=_e,ov=z,sv=cn.enforce,av=cn.get,cv=KI.Int8Array,lv=cv&&cv.prototype,dv=KI.Uint8ClampedArray,uv=dv&&dv.prototype,hv=cv&&iv(cv),pv=lv&&iv(lv),mv=Object.prototype,_v=KI.TypeError,fv=rv("toStringTag"),gv=ov("TYPED_ARRAY_TAG"),Tv="TypedArrayConstructor",Ev=WI&&!!nv&&"Opera"!==QI(KI.opera),Sv=!1,Iv={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},vv={BigInt64Array:8,BigUint64Array:8},yv=function(e){var t=iv(e);if(zI(t)){var i=av(t);return i&&qI(i,Tv)?i[Tv]:yv(t)}},Av=function(e){if(!zI(e))return!1;var t=QI(e);return qI(Iv,t)||qI(vv,t)};for(FI in Iv)(HI=(BI=KI[FI])&&BI.prototype)?sv(HI)[Tv]=BI:Ev=!1;for(FI in vv)(HI=(BI=KI[FI])&&BI.prototype)&&(sv(HI)[Tv]=BI);if((!Ev||!YI(hv)||hv===Function.prototype)&&(hv=function(){throw _v("Incorrect invocation")},Ev))for(FI in Iv)KI[FI]&&nv(KI[FI],hv);if((!Ev||!pv||pv===mv)&&(pv=hv.prototype,Ev))for(FI in Iv)KI[FI]&&nv(KI[FI].prototype,pv);if(Ev&&iv(uv)!==pv&&nv(uv,pv),JI&&!qI(pv,fv))for(FI in Sv=!0,ev(pv,fv,{configurable:!0,get:function(){return zI(this)?this[gv]:void 0}}),Iv)KI[FI]&&$I(KI[FI],gv,FI);var Rv={NATIVE_ARRAY_BUFFER_VIEWS:Ev,TYPED_ARRAY_TAG:Sv&&gv,aTypedArray:function(e){if(Av(e))return e;throw _v("Target is not a typed array")},aTypedArrayConstructor:function(e){if(YI(e)&&(!nv||tv(hv,e)))return e;throw _v(XI(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,n){if(JI){if(i)for(var r in Iv){var o=KI[r];if(o&&qI(o.prototype,e))try{delete o.prototype[e]}catch(BU){try{o.prototype[e]=t}catch(s){}}}pv[e]&&!i||ZI(pv,e,i?t:Ev&&lv[e]||t,n)}},exportTypedArrayStaticMethod:function(e,t,i){var n,r;if(JI){if(nv){if(i)for(n in Iv)if((r=KI[n])&&qI(r,e))try{delete r[e]}catch(BU){}if(hv[e]&&!i)return;try{return ZI(hv,e,i?t:Ev&&hv[e]||t)}catch(BU){}}for(n in Iv)!(r=KI[n])||r[e]&&!i||ZI(r,e,t)}},getTypedArrayConstructor:yv,isView:function(e){if(!zI(e))return!1;var t=QI(e);return"DataView"===t||qI(Iv,t)||qI(vv,t)},isTypedArray:Av,TypedArray:hv,TypedArrayPrototype:pv},Cv=C,bv=i,kv=Nd,Dv=Rv.NATIVE_ARRAY_BUFFER_VIEWS,Nv=Cv.ArrayBuffer,Ov=Cv.Int8Array,wv=!Dv||!bv((function(){Ov(1)}))||!bv((function(){new Ov(-1)}))||!kv((function(e){new Ov,new Ov(null),new Ov(1.5),new Ov(e)}),!0)||bv((function(){return 1!==new Ov(new Nv(2),1,void 0).length})),Pv=ve,Mv=Math.floor,Lv=Number.isInteger||function(e){return!Pv(e)&&isFinite(e)&&Mv(e)===e},xv=Mt,Vv=RangeError,Uv=function(e){var t=xv(e);if(t<0)throw Vv("The argument can't be less than 0");return t},Fv=RangeError,Bv=function(e,t){var i=Uv(e);if(i%t)throw Fv("Wrong offset");return i},Hv=Vs,jv=_t,Gv=TypeError,Wv=function(e){var t=jv(e,"number");if("number"==typeof t)throw Gv("Can't convert number to bigint");return BigInt(t)},Jv=va,Kv=Fe,Yv=oa,zv=B,qv=Gt,Qv=ad,Xv=ed,$v=zl,Zv=function(e){var t=Hv(e);return"BigInt64Array"==t||"BigUint64Array"==t},ey=Rv.aTypedArrayConstructor,ty=Wv,iy=Vr,ny=C,ry=Fe,oy=ke,sy=wv,ay=Rv,cy=vI,ly=Ds,dy=Wi,uy=Yi,hy=Lv,py=Ht,my=aS,_y=Bv,fy=Tt,gy=G,Ty=Vs,Ey=ve,Sy=ze,Iy=Ni,vy=Ge,yy=vo,Ay=nr.f,Ry=function(e){var t,i,n,r,o,s,a,c,l=Yv(this),d=zv(e),u=arguments.length,h=u>1?arguments[1]:void 0,p=void 0!==h,m=Xv(d);if(m&&!$v(m))for(c=(a=Qv(d,m)).next,d=[];!(s=Kv(c,a)).done;)d.push(s.value);for(p&&u>2&&(h=Jv(h,arguments[2])),i=qv(d),n=new(ey(l))(i),r=Zv(n),t=0;i>t;t++)o=p?h(d[t],t):d[t],n[t]=r?ty(o):+o;return n},Cy=rp.forEach,by=Cs,ky=Is,Dy=Ne,Ny=ln,Oy=lu,wy=cn.get,Py=cn.set,My=cn.enforce,Ly=Dy.f,xy=Ny.f,Vy=Math.round,Uy=ny.RangeError,Fy=cy.ArrayBuffer,By=Fy.prototype,Hy=cy.DataView,jy=ay.NATIVE_ARRAY_BUFFER_VIEWS,Gy=ay.TYPED_ARRAY_TAG,Wy=ay.TypedArray,Jy=ay.TypedArrayPrototype,Ky=ay.aTypedArrayConstructor,Yy=ay.isTypedArray,zy="BYTES_PER_ELEMENT",qy="Wrong length",Qy=function(e,t){Ky(e);for(var i=0,n=t.length,r=new e(n);n>i;)r[i]=t[i++];return r},Xy=function(e,t){ky(e,t,{configurable:!0,get:function(){return wy(this)[t]}})},$y=function(e){var t;return vy(By,e)||"ArrayBuffer"==(t=Ty(e))||"SharedArrayBuffer"==t},Zy=function(e,t){return Yy(e)&&!Sy(t)&&t in e&&hy(+t)&&t>=0},eA=function(e,t){return t=fy(t),Zy(e,t)?dy(2,e[t]):xy(e,t)},tA=function(e,t,i){return t=fy(t),!(Zy(e,t)&&Ey(i)&&gy(i,"value"))||gy(i,"get")||gy(i,"set")||i.configurable||gy(i,"writable")&&!i.writable||gy(i,"enumerable")&&!i.enumerable?Ly(e,t,i):(e[t]=i.value,e)};oy?(jy||(Ny.f=eA,Dy.f=tA,Xy(Jy,"buffer"),Xy(Jy,"byteOffset"),Xy(Jy,"byteLength"),Xy(Jy,"length")),iy({target:"Object",stat:!0,forced:!jy},{getOwnPropertyDescriptor:eA,defineProperty:tA}),GI.exports=function(e,t,i){var n=e.match(/\d+/)[0]/8,r=e+(i?"Clamped":"")+"Array",o="get"+e,s="set"+e,a=ny[r],c=a,l=c&&c.prototype,d={},u=function(e,t){Ly(e,t,{get:function(){return function(e,t){var i=wy(e);return i.view[o](t*n+i.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,r){var o=wy(e);i&&(r=(r=Vy(r))<0?0:r>255?255:255&r),o.view[s](t*n+o.byteOffset,r,!0)}(this,t,e)},enumerable:!0})};jy?sy&&(c=t((function(e,t,i,r){return ly(e,l),Oy(Ey(t)?$y(t)?void 0!==r?new a(t,_y(i,n),r):void 0!==i?new a(t,_y(i,n)):new a(t):Yy(t)?Qy(c,t):ry(Ry,c,t):new a(my(t)),e,c)})),yy&&yy(c,Wy),Cy(Ay(a),(function(e){e in c||uy(c,e,a[e])})),c.prototype=l):(c=t((function(e,t,i,r){ly(e,l);var o,s,a,d=0,h=0;if(Ey(t)){if(!$y(t))return Yy(t)?Qy(c,t):ry(Ry,c,t);o=t,h=_y(i,n);var p=t.byteLength;if(void 0===r){if(p%n)throw Uy(qy);if((s=p-h)<0)throw Uy(qy)}else if((s=py(r)*n)+h>p)throw Uy(qy);a=s/n}else a=my(t),o=new Fy(s=a*n);for(Py(e,{buffer:o,byteOffset:h,byteLength:s,length:a,view:new Hy(o)});d<a;)u(e,d++)})),yy&&yy(c,Wy),l=c.prototype=Iy(Jy)),l.constructor!==c&&uy(l,"constructor",c),My(l).TypedArrayConstructor=c,Gy&&uy(l,Gy,r);var h=c!=a;d[r]=c,iy({global:!0,constructor:!0,forced:h,sham:!jy},d),zy in c||uy(c,zy,n),zy in l||uy(l,zy,n),by(r)}):GI.exports=function(){},jI("Float32",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var iA=TS,nA=Wv,rA=Vs,oA=Fe,sA=i,aA=Rv.aTypedArray,cA=Rv.exportTypedArrayMethod,lA=c("".slice);cA("fill",(function(e){var t=arguments.length;aA(this);var i="Big"===lA(rA(this),0,3)?nA(e):+e;return oA(iA,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),sA((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e})));var dA=C,uA=Fe,hA=Rv,pA=Gt,mA=Bv,_A=B,fA=i,gA=dA.RangeError,TA=dA.Int8Array,EA=TA&&TA.prototype,SA=EA&&EA.set,IA=hA.aTypedArray,vA=hA.exportTypedArrayMethod,yA=!fA((function(){var e=new Uint8ClampedArray(2);return uA(SA,e,{length:1,0:3},1),3!==e[1]})),AA=yA&&hA.NATIVE_ARRAY_BUFFER_VIEWS&&fA((function(){var e=new TA(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));vA("set",(function(e){IA(this);var t=mA(arguments.length>1?arguments[1]:void 0,1),i=_A(e);if(yA)return uA(SA,this,i,t);var n=this.length,r=pA(i),o=0;if(r+t>n)throw gA("Wrong length");for(;o<r;)this[t+o]=i[o++]}),!yA||AA);var RA=q.match(/firefox\/(\d+)/i),CA=!!RA&&+RA[1],bA=/MSIE|Trident/.test(q),kA=q.match(/AppleWebKit\/(\d+)\./),DA=!!kA&&+kA[1],NA=Ta,OA=i,wA=et,PA=m_,MA=CA,LA=bA,xA=ie,VA=DA,UA=Rv.aTypedArray,FA=Rv.exportTypedArrayMethod,BA=C.Uint16Array,HA=BA&&NA(BA.prototype.sort),jA=!(!HA||OA((function(){HA(new BA(2),null)}))&&OA((function(){HA(new BA(2),{})}))),GA=!!HA&&!OA((function(){if(xA)return xA<74;if(MA)return MA<67;if(LA)return!0;if(VA)return VA<602;var e,t,i=new BA(516),n=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,n[e]=e-2*t+3;for(HA(i,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(i[e]!==n[e])return!0}));FA("sort",(function(e){return void 0!==e&&wA(e),GA?HA(this,e):PA(UA(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))}),!GA||jA);var WA=Qe,JA=TypeError,KA=Vr,YA=c,zA=et,qA=B,QA=Gt,XA=function(e,t){if(!delete e[t])throw JA("Cannot delete property "+WA(t)+" of "+WA(e))},$A=fu,ZA=i,eR=m_,tR=sp,iR=CA,nR=bA,rR=ie,oR=DA,sR=[],aR=YA(sR.sort),cR=YA(sR.push),lR=ZA((function(){sR.sort(void 0)})),dR=ZA((function(){sR.sort(null)})),uR=tR("sort"),hR=!ZA((function(){if(rR)return rR<70;if(!(iR&&iR>3)){if(nR)return!0;if(oR)return oR<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)sR.push({k:t+n,v:i})}for(sR.sort((function(e,t){return t.v-e.v})),n=0;n<sR.length;n++)t=sR[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));KA({target:"Array",proto:!0,forced:lR||!dR||!uR||!hR},{sort:function(e){void 0!==e&&zA(e);var t=qA(this);if(hR)return void 0===e?aR(t):aR(t,e);var i,n,r=[],o=QA(t);for(n=0;n<o;n++)n in t&&cR(r,t[n]);for(eR(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:$A(t)>$A(i)?1:-1}}(e)),i=QA(r),n=0;n<i;)t[n]=r[n++];for(;n<o;)XA(t,n++);return t}}),jI("Uint8",(function(e){return function(t,i,n){return e(this,t,i,n)}}));var pR=Vr,mR=Wh,_R=c([].reverse),fR=[1,2];pR({target:"Array",proto:!0,forced:String(fR)===String(fR.reverse())},{reverse:function(){return mR(this)&&(this.length=this.length),_R(this)}});var gR=Vr,TR=Fe,ER=c,SR=I,IR=Ee,vR=T,yR=pu,AR=fu,RR=nt,CR=Au,bR=qp,kR=_e("replace"),DR=TypeError,NR=ER("".indexOf);ER("".replace);var OR=ER("".slice),wR=Math.max,PR=function(e,t,i){return i>e.length?-1:""===t?i:NR(e,t,i)};gR({target:"String",proto:!0},{replaceAll:function(e,t){var i,n,r,o,s,a,c,l,d=SR(this),u=0,h=0,p="";if(!vR(e)){if(yR(e)&&(i=AR(SR(CR(e))),!~NR(i,"g")))throw DR("`.replaceAll` does not allow non-global regexes");if(n=RR(e,kR))return TR(n,e,d,t)}for(r=AR(d),o=AR(e),(s=IR(t))||(t=AR(t)),a=o.length,c=wR(1,a),u=PR(r,o,0);-1!==u;)l=s?AR(t(o,u,r)):bR(o,r,u,[],void 0,t),p+=OR(r,h,u)+l,h=u+a,u=PR(r,o,u+c);return h<r.length&&(p+=OR(r,h)),p}});let MR=!0,LR=!0;function xR(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function VR(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function UR(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 FR(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(LR=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function BR(){if("object"==typeof window){if(MR)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function HR(e,t){LR&&console.warn(e+" is deprecated, please use "+t+" instead.")}function jR(e){return"[object Object]"===Object.prototype.toString.call(e)}function GR(e){return jR(e)?Object.keys(e).reduce((function(t,i){const n=jR(e[i]),r=n?GR(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function WR(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?WR(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{WR(e,e.get(t),i)}))})))}function JR(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&WR(e,i,r)}))})),r}const KR=BR;function YR(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{i=i.filter((e=>"videoinput"===e.kind));let s=i.find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=n(e.video),KR("chrome: "+JSON.stringify(e)),r(e)}))}e.video=n(e.video)}return KR("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(o(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function zR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function 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 n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else VR(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function QR(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function XR(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach((e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{i[t]=e.stat(t)})),t[i.id]=i})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Promise(((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])})).then(i,n)}}function $R(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=>JR(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}),VR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>JR(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ZR(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function eC(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ZR(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((e=>e.track===t)))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=n[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function tC(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function iC(e,t){VR(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:zR,shimOnTrack:qR,shimGetSendersWithDtmf:QR,shimGetStats:XR,shimSenderReceiverGetStats:$R,shimAddTrackRemoveTrackWithNative:ZR,shimAddTrackRemoveTrack:eC,shimPeerConnection:tC,fixNegotiationNeeded:iC,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 n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function rC(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){HR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function oC(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 sC(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!r)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(sD){if("TypeError"!==sD.name)throw sD;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(r,o)}}function aC(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 cC(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}),VR(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function lC(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){HR("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function dC(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function uC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function hC(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 pC(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 mC(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 _C=Object.freeze({__proto__:null,shimOnTrack:oC,shimPeerConnection:sC,shimSenderGetStats:aC,shimReceiverGetStats:cC,shimRemoveStream:lC,shimRTCDataChannel:dC,shimAddTransceiver:uC,shimGetParameters:hC,shimCreateOffer:pC,shimCreateAnswer:mC,shimGetUserMedia:rC,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 fC(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 gC(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 TC(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function EC(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(SC(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function SC(e){return e&&void 0!==e.video?Object.assign({},e,{video:GR(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 n=e.iceServers[i];void 0===n.urls&&n.url?(HR("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function 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 yC(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 AC(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var RC=Object.freeze({__proto__:null,shimLocalStreamsAPI:fC,shimRemoteStreamsAPI:gC,shimCallbacksAPI:TC,shimGetUserMedia:EC,shimConstraints:SC,shimRTCIceServerUrls:IC,shimTrackEventTransceiver:vC,shimCreateOfferLegacy:yC,shimAudioContext:AC}),CC={},bC={get exports(){return CC},set exports(e){CC=e}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let r=0;r<n.length;r++)i=n[r].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let o=3;o<n.length;o++){const r=n[o],s=t.matchPrefix(e,"a=rtpmap:"+r+" ")[0];if(s){const n=t.parseRtpMap(s),o=t.matchPrefix(e,"a=fmtp:"+r+" ");switch(n.parameters=o.length?t.parseFmtp(o[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+r+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let r=0;return i.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const l=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),n.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.push({ssrc:a});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach((e=>{e.maxBitrate=d}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(bC);var kC=CC,DC=e({__proto__:null,default:kC},[CC]);function NC(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const i=new t(e),n=kC.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,VR(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||VR(e,"icecandidate",(e=>{if(e.candidate){const t=kC.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function wC(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=kC.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=kC.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=kC.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let r;r=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>r}),this._sctp=o}return i.apply(this,arguments)}}function PC(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},VR(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 LC(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function xC(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 VC(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 UC=Object.freeze({__proto__:null,shimRTCIceCandidate:NC,shimRTCIceCandidateRelayProtocol:OC,shimMaxMessageSize:wC,shimSendThrowTypeError:PC,shimConnectionState:MC,removeExtmapAllowMixed:LC,shimAddIceCandidateNullOrEmpty:xC,shimParameterlessSetLocalDescription:VC});!function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=BR,n=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=xR(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=xR(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=xR(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:n,commonShim:UC,extractVersion:xR,disableLog:UR,disableWarnings:FR,sdp:DC};switch(n.browser){case"chrome":if(!nC||!tC||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=nC,xC(e,n),VC(e),YR(e,n),zR(e),tC(e,n),qR(e),eC(e,n),QR(e),XR(e),$R(e),iC(e,n),NC(e),OC(e),MC(e),wC(e,n),PC(e),LC(e,n);break;case"firefox":if(!_C||!sC||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=_C,xC(e,n),VC(e),rC(e,n),sC(e,n),oC(e),lC(e),aC(e),cC(e),dC(e),uC(e),hC(e),pC(e),mC(e),NC(e),MC(e),wC(e,n),PC(e);break;case"safari":if(!RC||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=RC,xC(e,n),VC(e),IC(e),yC(e),TC(e),fC(e),gC(e),vC(e),EC(e),AC(e),NC(e),OC(e),wC(e,n),PC(e),LC(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var FC,BC=Object.create,HC=Object.defineProperty,jC=Object.defineProperties,GC=Object.getOwnPropertyDescriptor,WC=Object.getOwnPropertyDescriptors,JC=Object.getOwnPropertyNames,KC=Object.getOwnPropertySymbols,YC=Object.getPrototypeOf,zC=Object.prototype.hasOwnProperty,qC=Object.prototype.propertyIsEnumerable,QC=Reflect.get,XC=Math.pow,$C=(e,t,i)=>t in e?HC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,ZC=(e,t)=>{for(var i in t||(t={}))zC.call(t,i)&&$C(e,i,t[i]);if(KC)for(var i of KC(t))qC.call(t,i)&&$C(e,i,t[i]);return e},eb=(e,t)=>jC(e,WC(t)),tb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ib=(e,t)=>{for(var i in t)HC(e,i,{get:t[i],enumerable:!0})},nb=(e,t,i)=>(i=null!=e?BC(YC(e)):{},((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of JC(t))!zC.call(e,r)&&r!==i&&HC(e,r,{get:()=>t[r],enumerable:!(n=GC(t,r))||n.enumerable});return e})(!t&&e&&e.__esModule?i:HC(i,"default",{value:e,enumerable:!0}),e)),rb=(e,t,i,n)=>{for(var r,o=n>1?void 0:n?GC(t,i):t,s=e.length-1;s>=0;s--)(r=e[s])&&(o=(n?r(t,i,o):r(o))||o);return n&&o&&HC(t,i,o),o},ob=(e,t,i)=>($C(e,"symbol"!=typeof t?t+"":t,i),i),sb=(e,t,i)=>QC(YC(e),i,t),ab=(e,t,i)=>new Promise(((n,r)=>{var o=e=>{try{a(i.next(e))}catch(t){r(t)}},s=e=>{try{a(i.throw(e))}catch(t){r(t)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(e,t)).next())})),cb=tb(((e,t)=>{var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function s(e,t,i,r,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new o(i,r||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.prototype.eventNames=function(){var e,t,r=[];if(0===this._eventsCount)return r;for(t in e=this._events)i.call(e,t)&&r.push(n?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},c.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},c.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},c.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,d=this._events[a],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,i),!0;case 4:return d.fn.call(d.context,t,i,r),!0;case 5:return d.fn.call(d.context,t,i,r,o),!0;case 6:return d.fn.call(d.context,t,i,r,o,s),!0}for(l=1,c=new Array(u-1);l<u;l++)c[l-1]=arguments[l];d.fn.apply(d.context,c)}else{var h,p=d.length;for(l=0;l<p;l++)switch(d[l].once&&this.removeListener(e,d[l].fn,void 0,!0),u){case 1:d[l].fn.call(d[l].context);break;case 2:d[l].fn.call(d[l].context,t);break;case 3:d[l].fn.call(d[l].context,t,i);break;case 4:d[l].fn.call(d[l].context,t,i,r);break;default:if(!c)for(h=1,c=new Array(u-1);h<u;h++)c[h-1]=arguments[h];d[l].fn.apply(d[l].context,c)}}return!0},c.prototype.on=function(e,t,i){return s(this,e,t,i,!1)},c.prototype.once=function(e,t,i){return s(this,e,t,i,!0)},c.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!i||s.context===i)&&a(this,o);else{for(var c=0,l=[],d=s.length;c<d;c++)(s[c].fn!==t||r&&!s[c].once||i&&s[c].context!==i)&&l.push(s[c]);l.length?this._events[o]=1===l.length?l[0]:l:a(this,o)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),lb=tb(((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")}))}))})),db=tb((e=>{var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var o=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var o=0;o<n.length;o+=1)null!=e[o+1]&&(i[n[o]]=t(e[o+1]))})(n.match(e.reg),o,e.names,e.name),e.push&&i[e.push].push(o)},n=lb(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},o=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(o.push({rtp:[],fmtp:[]}),s=o[o.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(r))return i(c,s,r)}})),t.media=o,t};var o=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(o,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}})),ub=tb(((e,t)=>{var i=lb(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},o=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?n.push(i[t.name][s]):n.push(i[t.names[o]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var n=t.outerOrder||s,r=t.innerOrder||a,c=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))})),e.media.forEach((function(e){c.push(o("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?c.push(o(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){c.push(o(t,i,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),hb=tb((e=>{var t=db(),i=ub();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})),pb=nb(cb()),mb=((FC=mb||{})[FC.INVALID_PARAMETER=4096]="INVALID_PARAMETER",FC[FC.INVALID_OPERATION=4097]="INVALID_OPERATION",FC[FC.NOT_SUPPORTED=4098]="NOT_SUPPORTED",FC[FC.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",FC[FC.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",FC[FC.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",FC[FC.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",FC[FC.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",FC[FC.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",FC[FC.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",FC[FC.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",FC[FC.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",FC[FC.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",FC[FC.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",FC[FC.CLIENT_BANNED=16448]="CLIENT_BANNED",FC[FC.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",FC[FC.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",FC[FC.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",FC[FC.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",FC[FC.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",FC[FC.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",FC[FC.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",FC[FC.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",FC[FC.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",FC[FC.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",FC[FC.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",FC[FC.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",FC[FC.API_CALL_ABORTED=16461]="API_CALL_ABORTED",FC[FC.UNKNOWN=65535]="UNKNOWN",FC),_b=mb,fb=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:n=_b.UNKNOWN,extraCode:r=0,constraint:o}=e,s="<".concat(function(e){for(let t in _b)if(_b[t]===e)return t;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),a="".concat(i).concat(o?" constraint: ".concat(o):"").concat(null!=i&&i.includes(s)?"":" ".concat(s));super(a),ob(this,"code"),ob(this,"extraCode"),ob(this,"message"),ob(this,"originMessage"),ob(this,"name"),ob(this,"constraint"),this.code=n,this.extraCode=r,this.name=t,this.message=a,this.constraint=o,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},gb=fb,Tb=((new Date).getTime(),0),Eb=function(){return(new Date).getTime()+Tb},Sb=function(){let e=new Date;return e.setTime(Eb()),e.toLocaleString()},Ib={};ib(Ib,{bytes2ms:()=>KN,copyProperties:()=>JN,deepClone:()=>CO,deepMerge:()=>RO,env:()=>vb,fibonacci:()=>ZN,formatedTime:()=>DO,getConstructorName:()=>pO,getContainerFromElement:()=>bO,getEnv:()=>UN,getInternalVersion:()=>TO,getLoggerUrl:()=>BN,getMuteStateFromFlag:()=>IO,getNetworkQuality:()=>vO,getNetworkType:()=>GN,getOSType:()=>jN,getReconnectionTimeout:()=>eO,getStringByteLength:()=>wO,getSysInfo:()=>WN,getTerminalType:()=>HN,getTurnServer:()=>yO,getValueType:()=>tO,glog:()=>QN,ipv4ToUint32:()=>AO,isArray:()=>cO,isAudioWorkletSupported:()=>mO,isBoolean:()=>sO,isConstructor:()=>hO,isEmpty:()=>SO,isFunction:()=>iO,isLangChinese:()=>XN,isMediaStreamTrack:()=>lO,isNumber:()=>oO,isObject:()=>aO,isOverseaSdkAppId:()=>FN,isPlainObject:()=>$N,isPortrait:()=>MO,isPromise:()=>uO,isRemoteTrack:()=>dO,isString:()=>rO,isUndefined:()=>nO,logVisibilityState:()=>PO,ms2bytes:()=>zN,ms2samples:()=>qN,performanceNow:()=>fO,promiseAny:()=>_O,samples2ms:()=>YN,stringify:()=>NO,stringifyIncludeValue:()=>OO});var vb={};ib(vb,{ANDROID_VERSION:()=>Lb,CHROME_MAJOR_VERSION:()=>xk,CHROME_VERSION:()=>Vk,EDGE_VERSION:()=>jb,EDG_MAJOR_VERSION:()=>Jb,EDG_VERSION:()=>Wb,FIREFOX_MAJOR_VERSION:()=>Bb,FIREFOX_VERSION:()=>Fb,HUAWEI_VERSION:()=>Rk,IE_VERSION:()=>ik,IOS_MAIN_VERSION:()=>Gk,IOS_VERSION:()=>jk,IPADQQB_VERSION:()=>pk,IS_ANDROID:()=>Mb,IS_ANDROID_WEBVIEW:()=>Hk,IS_ANY_SAFARI:()=>Fk,IS_CHROME:()=>Mk,IS_CHROME_OS:()=>gk,IS_CHROMIUM_BASE:()=>Pk,IS_EDG:()=>Gb,IS_EDGE:()=>Hb,IS_ELECTRON:()=>Sk,IS_FIREFOX:()=>Ub,IS_HEADLESS_CHROME:()=>Lk,IS_HUAWEI:()=>Ak,IS_HUAWEIBROWSER:()=>yk,IS_IE:()=>tk,IS_IE8:()=>ek,IS_IOS:()=>Pb,IS_IOS_13_OR_14:()=>Kk,IS_IOS_15_1:()=>Jk,IS_IPAD:()=>Db,IS_IPADQQB:()=>hk,IS_IPAD_PRO:()=>Nb,IS_IPHONE:()=>Ob,IS_IPOD:()=>wb,IS_LINUX:()=>fk,IS_LOCAL:()=>Yk,IS_MAC:()=>_k,IS_MACQQB:()=>dk,IS_MIBROWSER:()=>Ik,IS_MQQB:()=>sk,IS_NATIVE_ANDROID:()=>Vb,IS_OLD_ANDROID:()=>xb,IS_OPPOBROWSER:()=>kk,IS_SAFARI:()=>Uk,IS_SAFARI_15_1:()=>Wk,IS_SAMSUNGBROWSER:()=>Ck,IS_SOGOU:()=>zb,IS_SOGOUM:()=>Kb,IS_TBS:()=>Qb,IS_UCBROWSER:()=>Ek,IS_VIVOBROWSER:()=>Nk,IS_WECHAT:()=>nk,IS_WIN:()=>mk,IS_WQQB:()=>ck,IS_WX:()=>Tk,IS_X5MQQB:()=>ok,IS_XWEB:()=>$b,MACQQB_VERSION:()=>uk,MI_VERSION:()=>vk,MQQB_VERSION:()=>ak,OPPO_VERSION:()=>Dk,SAFARI_VERSION:()=>Bk,SAMSUNG_VERSION:()=>bk,SOGOUM_VERSION:()=>Yb,SOGOU_VERSION:()=>qb,TBS_VERSION:()=>Xb,USER_AGENT:()=>yb,VIVO_VERSION:()=>Ok,WECHAT_VERSION:()=>rk,WQQB_VERSION:()=>lk,XWEB_VERSION:()=>Zb,browserInfo:()=>qk,getBrowserInfo:()=>Qk,getChromeMajorVersion:()=>wk,getOSName:()=>eD,getOSString:()=>tD,getUserAgentData:()=>$k,isLocalStorageEnabled:()=>zk});var yb="undefined"==typeof navigator?"":navigator.userAgent,Ab=e=>new RegExp(e,"i").test(yb),Rb=e=>{if(Ab(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=yb.match(t);if(i&&i[1])return i[1]}return""},Cb=e=>{if(Ab(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=yb.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},bb=/AppleWebKit\/([\d.]+)/i.exec(yb),kb=bb?parseFloat(bb[1]):NaN,Db=Ab("iPad"),Nb="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ab("Macintosh"),Ob=Ab("iPhone")&&!Db,wb=Ab("iPod"),Pb=Ob||Db||wb||Nb,Mb=Ab("Android"),Lb=function(){if(Mb){let e=yb.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}(),xb=Mb&&Ab("webkit")&&Lb<2.3,Vb=Mb&&Lb<5&&kb<537,Ub=Ab("Firefox"),Fb=Rb("Firefox"),Bb=Cb("Firefox"),Hb=Ab("Edge"),jb=Rb("Edge"),Gb=Ab("Edg"),Wb=Rb("Edg"),Jb=Cb("Edg"),Kb=Ab("SogouMobileBrowser"),Yb=Rb("SogouMobileBrowser"),zb=Ab("MetaSr\\s"),qb=Rb("MetaSr\\s"),Qb=Ab("TBS"),Xb=Rb("TBS"),$b=Ab("XWEB"),Zb=Rb("XWEB"),ek=Ab("MSIE\\s8\\.0"),tk=Ab("MSIE\\/\\d+"),ik=function(){if(tk){let e=/MSIE\s(\d+)\.\d/.exec(yb),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(yb)&&/rv:11.0/.test(yb)&&(t=11),t}return NaN}(),nk=Ab("(micromessenger|webbrowser)"),rk=Rb("MicroMessenger"),ok=!Qb&&Ab("MQQBrowser")&&Ab("COVC"),sk=!Qb&&Ab("MQQBrowser")&&!Ab("COVC"),ak=sk||ok?Rb("MQQBrowser"):"",ck=!Qb&&Ab(" QQBrowser"),lk=Rb(" QQBrowser"),dk=!Qb&&Ab("QQBrowserLite"),uk=Rb("QQBrowserLite"),hk=!Qb&&Ab("MQBHD"),pk=Rb("MQBHD"),mk=Ab("Windows"),_k=!Pb&&Ab("MAC OS X"),fk=!Mb&&Ab("Linux"),gk=Ab("CrOS"),Tk=Ab("MicroMessenger"),Ek=Ab("UCBrowser"),Sk=Ab("Electron"),Ik=Ab("MiuiBrowser"),vk=Rb("MiuiBrowser"),yk=Ab("HuaweiBrowser"),Ak=Ab("Huawei"),Rk=Rb("HuaweiBrowser"),Ck=Ab("SamsungBrowser"),bk=Rb("SamsungBrowser"),kk=Ab("HeyTapBrowser"),Dk=Rb("HeyTapBrowser"),Nk=Ab("VivoBrowser"),Ok=Rb("VivoBrowser"),wk=()=>Cb("Chrome"),Pk=Ab("Chrome"),Mk=!Hb&&!zb&&!Kb&&!Qb&&!$b&&!Gb&&!ck&&!Ik&&!yk&&!Ck&&!kk&&!Nk&&Pk,Lk=Ab("HeadlessChrome"),xk=wk(),Vk=Rb("Chrome"),Uk=!Pk&&!sk&&!ok&&!dk&&!hk&&Ab("Safari"),Fk=Uk||Pb,Bk=Rb("Version"),Hk=/Android.*(wv|.0.0.0)/.test(yb),jk=(()=>{if(Nb)return Bk;if(Pb){let e=yb.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})(),Gk=Number(jk.split(".")[0]),Wk="15.1"===Bk,Jk="15.1"===jk,Kk=(()=>{let e=Number(jk.split(".")[0]);return 14===e||13===e})(),Yk="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),zk=(()=>{let e;return()=>{if(nO(e))try{e=!!window.localStorage}catch(QM){e=!1}return e}})(),qk=Qk();function Qk(){let e=new Map([[Ub,["Firefox",Fb]],[Gb,["Edg",Wb]],[Mk,["Chrome",Vk]],[Uk,["Safari",Bk]],[Qb,["TBS",Xb]],[$b,["XWEB",Zb]],[nk&&Ob,["WeChat",rk]],[ck,["QQ(Win)",lk]],[sk,["QQ(Mobile)",ak]],[ok,["QQ(Mobile X5)",ak]],[dk,["QQ(Mac)",uk]],[hk,["QQ(iPad)",pk]],[Ik,["MI",vk]],[yk,["HW",Rk]],[Ck,["Samsung",bk]],[kk,["OPPO",Dk]],[Nk,["VIVO",Ok]],[Hb,["EDGE",jb]],[Kb,["SogouMobile",Yb]],[zb,["Sogou",qb]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Xk=null;function $k(){return ab(this,null,(function*(){if(Xk)return Xk;if(!navigator.userAgentData||!iO(navigator.userAgentData.getHighEntropyValues))return null;try{return Xk=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"])}catch(qM){return null}}))}var Zk=new Map([[Mb,"Android"],[Pb,"iOS"],[mk,"Windows"],[_k,"MacOS"],[fk,"Linux"],[gk,"ChromeOS"]]),eD=function(){return Zk.get(!0)?Zk.get(!0):Xk?Xk.platform:"unknown"},tD=()=>{let e=eD();return e+="/".concat(qk.name,"/").concat(Uk?qk.version:qk.version.split(".")[0]),null!=Xk&&Xk.platformVersion&&(e+="/".concat(Xk.platformVersion)),null!=Xk&&Xk.architecture&&(e+="/".concat(Xk.architecture)),e},iD={};ib(iD,{AUDIO_MUTE_BIT:()=>jD,AUDIO_STAT_BIT:()=>HD,AUX_STAT_BIT:()=>BD,AUX_STREAM_MSID:()=>JD,BACKEND_ENV:()=>xD,BASE_DOC_URL:()=>TD,BASE_HOST:()=>mD,CAPABILITIES_KEYS:()=>xN,CLASS_NAME:()=>yN,CLOUD_CONSOLE_URL:()=>gD,DATA_FREEZE_TIMING:()=>fN,DOC_URL:()=>ED,DTLS_STATE_UNKNOWN:()=>tN,ENV_NAME:()=>AD,EXCHANGE_SDP_TIMEOUT:()=>uN,INTERVAL:()=>MN,IS_WORKER:()=>lD,IS_WORKLET:()=>dD,KIBANA_EVENT:()=>cN,LOCAL_STREAM_PUBLISH_STATE:()=>_N,LOGGER_CMD_TYPE:()=>yD,LOGGER_DOMAIN:()=>SD,LOGGER_DOMAIN_OVERSEA:()=>ID,LOG_LEVEL:()=>RD,LOG_LEVEL_NAME:()=>kN,MAIN_STREAM_MSID:()=>WD,MICROPHONE_COMMUNICATIONS:()=>bN,MICROPHONE_DEFAULT:()=>RN,NAME:()=>MD,NETWORK_TYPE:()=>kD,NOT_SUPPORTED_H264:()=>mN,PAUSED_RETRY_COUNT:()=>AN,PEERCONNECTION_CONNECTING_TIMEOUT:()=>SN,PEER_CONNECTION_STATE:()=>iN,PEER_LEAVE_REASON:()=>DN,RAF:()=>PN,RECOVER_CAPTURE_INTERVAL:()=>ON,REMOTE_STREAM_TYPE_AUX:()=>YD,REMOTE_STREAM_TYPE_MAIN:()=>KD,RENDER_FREEZE_TIMING:()=>gN,RIC:()=>wN,SCHEDULE_DOMAIN:()=>IN,SCHEDULE_TIMEOUT:()=>vN,SDP_SEMANTICS_PLAN_B:()=>pN,SDP_SEMANTICS_UNIFIED_PLAN:()=>hN,SECOND_HOST:()=>_D,SIGNAL_PING_PONG_INTERVAL:()=>bD,SIGNAL_PING_TIMEOUT:()=>CD,SIGNAL_RECONNECTION_COUNT:()=>aN,SMALL_STAT_BIT:()=>FD,SPEAKER_DEFAULT:()=>CN,STORAGE_EXPIRES_TIME:()=>DD,STREAM_TYPE_BIG:()=>TN,STREAM_TYPE_SMALL:()=>EN,SUBSCRIBE_SMALL_RETRY_COUNT:()=>NN,SYNC_USER_LIST_INTERVAL:()=>lN,Scene:()=>VD,Switch:()=>ND,THIRD_HOST:()=>fD,TIMEOUT:()=>LN,TRANSPORT_DIRECTION:()=>LD,TRTC_ERROR_ASSISTANCE:()=>vD,TRTC_QUALITY_BAD:()=>$D,TRTC_QUALITY_DISCONNECTED:()=>eN,TRTC_QUALITY_EXCELLENT:()=>qD,TRTC_QUALITY_GOOD:()=>QD,TRTC_QUALITY_POOR:()=>XD,TRTC_QUALITY_UNKNOWN:()=>zD,TRTC_QUALITY_VERY_BAD:()=>ZD,UPDATE_OFFER_TIMEOUT:()=>dN,VIDEO_MUTE_BIT:()=>GD,VIDEO_STAT_BIT:()=>UD,audioProfileMap:()=>OD,getRetryCount:()=>oN,getScriptDir:()=>uD,innerVersion:()=>nD,loggerProxy:()=>hD,screenProfileMap:()=>PD,setLoggerProxy:()=>pD,setRetryCount:()=>rN,setVersion:()=>oD,version:()=>rD,videoProfileMap:()=>wD});var nD="4.15.00.1600",rD="5.0.0";function oD(e){rD=e;let[t,i,n]=e.split(".").map((e=>parseInt(e,10)));nD="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,n),".").concat(i.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var sD,aD,cD,lD="undefined"!=typeof importScripts,dD="undefined"!=typeof registerProcessor,uD=()=>{let e=lD?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},hD="",pD=e=>hD=e,mD="web.sdk.qcloud.com",_D="web.sdk.tencent.cn",fD="web.sdk.cloud.tencent.cn",gD="https://console.cloud.tencent.com/trtc",TD="https://".concat(mD,"/trtc/webrtc/v5/doc"),ED="".concat(TD,"/zh-cn/"),SD="https://yun.tim.qq.com",ID="https://apisgp.my-imcloud.com",vD="trtc_error_assistance",yD={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},AD={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},RD=((cD=RD||{})[cD.TRACE=0]="TRACE",cD[cD.DEBUG=1]="DEBUG",cD[cD.INFO=2]="INFO",cD[cD.WARN=3]="WARN",cD[cD.ERROR=4]="ERROR",cD[cD.NONE=5]="NONE",cD),CD=18e3,bD=2e3,kD={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},DD=6048e5,ND=((aD=ND||{}).USEAINS="useAINS",aD.ENABLEDEBUG="enableDebug",aD.USEV2="useV2",aD.USEWT="useWt",aD),OD={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},wD={"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}},PD={"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}},MD={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"},LD={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},xD={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},VD=((sD=VD||{}).LIVE="live",sD.RTC="rtc",sD),UD=1,FD=2,BD=4,HD=8,jD=64,GD=16,WD="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",JD="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",KD=MD.MAIN,YD=MD.AUXILIARY,zD=0,qD=1,QD=2,XD=3,$D=4,ZD=5,eN=6,tN="unknown",iN={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},nN=1/0;function rN(e){nN=e}function oN(){return nN}var sN,aN=30,cN={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"},lN=1e4,dN=1e4,uN=1e4,hN="unified-plan",pN="plan-b",mN=1028,_N=((sN=_N||{})[sN.UNPUBLISH=-1]="UNPUBLISH",sN[sN.PUBLISHING=0]="PUBLISHING",sN[sN.PUBLISHED=1]="PUBLISHED",sN),fN=500,gN=1e3,TN=MD.BIG,EN=MD.SMALL,SN=1e4,IN={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"},vN=2e3,yN={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},AN=5,RN="default",CN=RN,bN="communications",kN=Object.keys(RD),DN=["normal leave","timeout leave","kick","role change"],NN=10,ON=2e3,wN="ric",PN="raf",MN="interval",LN="timeout",xN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],VN=1e8,UN=function(){return new URLSearchParams(location.search).get("trtc_env")||""},FN=e=>Number(e)<14e8,BN=function(e,t){let i;i=hD||(FN(e)?ID:SD);let n=Math.floor(Math.random()*XC(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(e,"&cmdtype=").concat(t)};function HN(){return Mb?4:Ob?2:Db?3:_k?12:mk?5:fk?13:1}function jN(){return Mb?"Android":Ob?"iPhone":Db?"iPad":_k?"Mac":mk?"Windows":fk?"Linux":"unknown"}function GN(){let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");let n=t&&t.type&&t.type.toLowerCase(),r=t&&t.effectiveType&&t.effectiveType.toLowerCase();"slow-2"===r&&(r="2g");let o=i||"unknown";if(n)switch(n){case"cellular":case"wimax":o=r||"unknown";break;case"wifi":o="wifi";break;case"ethernet":o="wired";break;default:o="unknown"}return o}var WN=function(e){return{AbilityOption:{AVLimit:e,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:HN(),uint32_device_type:0,str_os_verion:jN(),uint32_link_type:1,str_client_version:nD,uint32_net_type:kD[GN()],ua:navigator.userAgent,version:""}}}};function JN(e,t){for(let i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){let n=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,n)}return e}function KN(e){return YN(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function YN(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function zN(e){return 4*qN(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function qN(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var QN="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},XN=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},$N=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 ZN(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:ZN(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function eO(e){return e>8?3e4:1e3*ZN(e)}function tO(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var iO=e=>"function"==typeof e,nO=e=>void 0===e,rO=e=>"string"==typeof e,oO=e=>"number"==typeof e,sO=e=>"boolean"==typeof e,aO=e=>"object"===tO(e),cO=e=>"array"===tO(e),lO=e=>tO(e)==="MediaStreamTrack".toLowerCase(),dO=e=>e.isRemote,uO=e=>"promise"===tO(e),hO=e=>iO(e)&&e.prototype.constructor===e,pO=e=>hO(e)?e.prototype.constructor.name:"",mO="undefined"!=typeof AudioWorkletNode;function _O(e){return new Promise(((t,i)=>{let n=[];e.forEach((r=>{r.then(t).catch((t=>{n.push(t),n.length===e.length&&i(n)}))}))}))}function fO(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var gO=e=>+e<10?"0".concat(e):e,TO=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),n=gO(i[1])+gO(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(n)},EO=Object.prototype.hasOwnProperty;function SO(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($N(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(EO.call(e,t))return!1;return!0}return!1}function IO(e,t){return{userId:t,hasAudio:!!(e&HD),hasVideo:!!(e&UD),hasAuxiliary:!!(e&BD),hasSmall:!!(e&FD),audioMuted:!!(e&jD),videoMuted:!!(e&GD),audioAvailable:!(!(e&HD)||e&jD),videoAvailable:!(!(e&UD)||e&GD)}}function vO(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}function yO(e){let t={urls:"turn:".concat(e.url)};return!nO(e.username)&&!nO(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",nO(e.credentialType)||(t.credentialType=e.credentialType)),t}function AO(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!rO(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,n){if(!aO(e)||!aO(t))return 0;let r,o=0,s=Object.keys(t);for(let a=0,c=s.length;a<c;a++)if(r=s[a],!(nO(t[r])||i&&i.includes(r)))if(aO(e[r])&&aO(t[r]))o+=RO(e[r],t[r],i,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=CO(t[r]),o+=1)}return o};function CO(e){if(cO(e)){let t=[];return e.forEach(((e,i)=>{t[i]=CO(e)})),t}if(aO(e)){let t={};return Object.keys(e).forEach((i=>{t[i]=CO(e[i])})),t}return e}var bO=e=>rO(e)?document.getElementById(e):e,kO=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),DO=()=>kO.format(new Date);function NO(e,t){let{keysToInclude:i,keysToExclude:n}=t;try{if(cO(e))return"[".concat(e.map((e=>NO(e,{keysToInclude:i,keysToExclude:n}))).join(","),"]");if(!$N(e)||!cO(i)&&!cO(n))return JSON.stringify(e);let t={},r=new Set(i),o=new Set(n);return Object.keys(e).forEach((s=>{(0===o.size&&r.has(s)||0===r.size&&!o.has(s))&&(t[s]=$N(e[s])||cO(e[s])?JSON.parse(NO(e[s],{keysToExclude:n,keysToInclude:i})):e[s])})),JSON.stringify(t)}catch(sN){return"{}"}}function OO(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=[];return Object.keys(e).forEach((n=>{t===e[n]&&i.push(n)})),NO(e,{keysToInclude:i})}function wO(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var PO=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&GO.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(()=>{GO.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}})(),MO=()=>{var e,t,i;return!(null==(i=null==(t=null==(e=window.screen)?void 0:e.orientation)?void 0:t.type)||!i.includes("portrait"))};function LO(e){let{url:t,body:i,method:n,timeout:r}=e,o=new XMLHttpRequest;return new Promise(((e,s)=>{o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{let t=JSON.parse(o.response);e({data:t})}catch(t){e({data:o.response})}else s({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=r||5e3,o.open(n||"POST",t,!0),o.send(i)}))}var xO,VO=function(e){let{retryFunction:t,settings:i,onError:n,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:a}=e;return function(){for(var e=arguments.length,c=new Array(e),l=0;l<e;l++)c[l]=arguments[l];let{retries:d=5,timeout:u=1e3}=i,h=0,p=-1,m=0,_=(e,i)=>ab(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<(iO(d)?d():d)?(h++,m=1,iO(r)&&r.call(this,h,t),p=window.setTimeout((()=>{p=-1,_(e,i)}),iO(u)?u(h):u)):(t(),iO(o)&&o.call(this,f))};iO(n)?n.call(this,{error:f,retry:s,reject:i,retryFuncArgs:c,retriedCount:h}):s()}}));return new Promise(_)}},UO=class{constructor(e){ob(this,"userId"),ob(this,"remoteUserId"),ob(this,"id"),ob(this,"sdkAppId"),ob(this,"type"),ob(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!sO(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):"","]")),GO.log(e,t,nO(this.userId)||SO(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)}},FO=new(nb(cb(),1).default),BO=((xO=BO||{}).ROOM_DESTROY="1",xO.JOIN_START="21",xO.JOIN_SCHEDULE_SUCCESS="22",xO.JOIN_SIGNAL_CONNECTION_START="23",xO.JOIN_SIGNAL_CONNECTION_END="24",xO.JOIN_SEND_CMD="25",xO.JOIN_RECEIVED_CMD_RES="26",xO.JOIN_SUCCESS="27",xO.JOIN_FAILED="28",xO.LEAVE_START="51",xO.LEAVE_SEND_CMD="52",xO.LEAVE_SUCCESS="53",xO.PUBLISH_START="61",xO.SEND_FIRST_VIDEO_FRAME="62",xO.PUBLISH_FAILED="63",xO.SUBSCRIBE_START="81",xO.SUBSCRIBE_SUCCESS="82",xO.SUBSCRIBE_FAILED="84",xO.UNSUBSCRIBE_SUCCESS="83",xO.LOCAL_TRACK_CAPTURE_START="101",xO.LOCAL_TRACK_CAPTURE_SUCCESS="102",xO.LOCAL_TRACK_CAPTURE_FAILED="103",xO.LOCAL_TRACK_PUBLISHED="104",xO.LOCAL_TRACK_UNPUBLISHED="105",xO.LOCAL_TRACK_REPLACED="106",xO.SWITCH_DEVICE_SUCCESS="107",xO.TRACK_MUTED="108",xO.TRACK_UNMUTED="109",xO.REMOTE_TRACK_SUBSCRIBED="110",xO.REMOTE_TRACK_UNSUBSCRIBED="111",xO.PLAY_TRACK_START="151",xO.PLAYER_STATE_CHANGED="152",xO.VIDEO_LOADED_DATA="153",xO.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",xO.WORKLET_LOADED_SUCCESS="155",xO.WORKLET_LOADED_FAILED="156",xO.SIGNAL_CONNECTION_STATE_CHANGED="201",xO.PEER_CONNECTION_STATE_CHANGED="202",xO.SINGLE_CONNECTION_STAT="203",xO.HEARTBEAT_REPORT="251",xO.RECEIVED_PUBLISHED_USER_LIST="252",xO.REMOTE_PUBLISH_STATE_CHANGED="253",xO.AUDIO_LEVEL_INTERVAL="260",xO.NETWORK_QUALITY="261",xO.API_SUCCESS_RATE="262",xO),HO=BO,jO=!(Pb||Mb||Lk),GO=new class{constructor(){ob(this,"_isEnableUploadLog",!0),ob(this,"_localJoinedUser",new Map),ob(this,"_queue",[]),ob(this,"_timeoutId",-1),ob(this,"_logLevel",1),ob(this,"_logLevelToUpload",2),!lD&&!dD&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){FO.on(HO.JOIN_SCHEDULE_SUCCESS,(e=>{let{schedule:t}=e;var i;(null==(i=null==t?void 0:t.config)?void 0:i.logLevelToUpload)&&RD[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)})),FO.on(HO.JOIN_SUCCESS,(e=>{let{room:t}=e;this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()})),FO.once(HO.JOIN_FAILED,(()=>{this.startUpload()})),FO.on(HO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.deleteJoinedUser(t.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),2e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){let i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((t=>{let{userId:n,sdkAppId:r}=t;e.map.has(n)?e.map.get(n).logs.push(i):e.map.set(n,{userId:n,sdkAppId:r,logs:[i]})}));else if(rO(i.userId)&&oO(i.sdkAppId)){let{userId:t,sdkAppId:n}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:n,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}upload(){return ab(this,null,(function*(){if(0===this._queue.length||!this._isEnableUploadLog)return;let{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{let t=[...e.values()];for(let e=0;e<t.length;e++){let{userId:i,sdkAppId:n,logs:r}=t[e];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Sb(),sdkAppId:String(n),userId:i,version:rD,log:r.map((e=>e.log)).join("\n")}),n),r.forEach((e=>e.uploaded=!0))}}catch(aD){}let i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}))}uploadLogWithRetry(e,t){return VO({retryFunction:()=>LO({url:BN(t,yD.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(Eb());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(RD[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){nO(RD[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(rO(e))return e;try{return JSON.stringify(e)}catch(sD){return""}}log(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;var o;if(t.unshift(this.getPrefix(e)),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push({log:t.reduce(((e,t)=>"".concat(e," ").concat(this.logChunkToString(t)).trim()),""),level:e,userId:n,sdkAppId:r,forAllJoinedClients:i}),e<this._logLevel)return;let s=(null==(o=RD[e])?void 0:o.toLowerCase())||"info";jO?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 UO(e)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;RD[t]&&(this._logLevelToUpload=t)}},WO=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},JO=new class{constructor(){ob(this,"_prefix","TRTC"),ob(this,"_queue",new Map),this.checkStorage()}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){zk()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix)){let t=JSON.parse(localStorage.getItem(e));if(t&&t.expiresIn<Date.now())return!0}return!1})).forEach((e=>localStorage.removeItem(e))))}doFlush(){if(zk())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(QM){GO.warn(QM)}}getItem(e){if(!zk())return null;try{let t=JSON.parse(localStorage.getItem(this.getRealKey(e)));return t&&t.expiresIn>=Date.now()?t.value:null}catch(sD){GO.warn(sD)}}setItem(e,t){if(zk())try{let i={expiresIn:Date.now()+DD,value:t};this._queue.set(this.getRealKey(e),i)}catch(sN){GO.warn(sN)}}deleteItem(e){if(!zk())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(sD){return GO.warn(sD),!1}}clear(){if(zk())try{localStorage.clear()}catch(QM){GO.warn(QM)}}},KO={};ib(KO,{HTTPS_API:()=>hw,IS_GET_CAPABILITIES_SUPPORTED:()=>Dw,IS_GET_SETTINGS_SUPPORTED:()=>kw,IS_SEI_SUPPORTED:()=>Nw,IS_SPC_SUPPORTED:()=>Aw,basis:()=>Lw,checkSystemRequirementsInternal:()=>lw,decodeSupportStatus:()=>cw,encodeSupportStatus:()=>aw,getBrowserInfo:()=>ew,getDisplayResolution:()=>mw,isAddTransceiverSupported:()=>yw,isBrowserSupported:()=>tw,isGetReceiversSupported:()=>Sw,isGetSendersSupported:()=>Iw,isGetTransceiversSupported:()=>vw,isGetUserMediaSupported:()=>_w,isMediaDevicesSupported:()=>nw,isMediaSessionSupported:()=>Pw,isMediaStreamTrackProcessorSupported:()=>sw,isReplaceTrackSupported:()=>Cw,isScreenCaptureApiAvailable:()=>uw,isSelectedCandidatePair:()=>pw,isSetParametersSupported:()=>bw,isSmallStreamAPISupported:()=>gw,isSmallStreamSupported:()=>Tw,isStopTransceiverSupported:()=>Rw,isTRTCSupported:()=>dw,isUnifiedPlanDefault:()=>Ew,isUsedInHttpProtocol:()=>ow,isWebAudioSupported:()=>fw,isWebCodecSupported:()=>ww,isWebCodecsSupported:()=>iw,isWebRTCSupported:()=>Ow,isWebTransportSupported:()=>Mw});var YO={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},zO={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(tO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(tO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:n,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:"no permission to publish() under live/".concat("audience",', please call switchRole("',"anchor",'") firstly before publish().'),INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:n}=e;return"failed to subscribe ".concat(i," ").concat(n," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as ".concat("anchor"," or ","audience","."),INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},PLAY_FAILED:e=>"".concat(e.media," play failed,browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught on ".concat(t,".on('").concat(i,"', handler), please check your code on 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"[".concat(e,"] is calling client.join api or has already joined room, please avoid repeated join."),CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:e=>"buffer size(".concat(e,") is over 1000 Bytes"),SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:n,maxSizeInSecond:r}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(r," bytes"):n," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},qO=(e,t)=>t?"".concat(TD,"/").concat(e,"/").concat(t):"".concat(TD,"/").concat(e,"/index.html"),QO=()=>{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(vD);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:n}}return{}};function XO(e){let{key:t,data:i,link:n,addDocLink:r=!0}=e,o="",s="",a="";iO(zO[t])?o=zO[t](i):rO(zO[t])&&(o=zO[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=QO();n?a="".concat(n.className,".html#").concat(n.fnName):l&&l[t]&&(iO(l[t])?a=l[t](i):rO(l[t])&&(a=l[t]));let d=o;return XN()&&(c&&c[t]&&(iO(c[t])?s=c[t](i):rO(c[t])&&(s=c[t])),s&&(d=r?"".concat(s,"\n请查看文档: ").concat(qO("zh-cn",a),"\n\n"):"".concat(s,"\n\n"),d+=o)),r&&(d+=" \nRefer to: ".concat(qO("en",a),"\n")),d}var $O={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},ZO=new Map([[Ub,["Firefox",Fb]],[Gb,["Edg",Wb]],[Mk,["Chrome",Vk]],[Uk,["Safari",Bk]],[Qb,["TBS",Xb]],[$b,["XWEB",Zb]],[nk&&Ob,["WeChat",rk]],[ck,["QQ(Win)",lk]],[sk,["QQ(Mobile)",ak]],[ok,["QQ(Mobile X5)",ak]],[dk,["QQ(Mac)",uk]],[hk,["QQ(iPad)",pk]],[Ik,["MI",vk]],[yk,["HW",Rk]],[Ck,["Samsung",bk]],[kk,["OPPO",Dk]],[Nk,["VIVO",Ok]],[Hb,["EDGE",jb]],[Kb,["SogouMobile",Yb]],[zb,["Sogou",qb]]]);function ew(){let e=ZO.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var tw=function(){return!(Ek||Hb||Gb&&Jb<80||Ub&&Bb<56)},iw=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every((e=>e in window))},nw=function(){if(!navigator.mediaDevices)return ow()||GO.error(zO.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},rw=!1;function ow(){return"http:"===location.protocol&&!Yk&&(rw||GO.error(XO({key:YO.NOT_SUPPORTED_HTTP})),rw=!0,!0)}var sw=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},aw=function(){return ab(this,null,(function*(){if($O.detail.isH264EncodeSupported||$O.detail.isVp8EncodeSupported)return{isH264EncodeSupported:$O.detail.isH264EncodeSupported,isVp8EncodeSupported:$O.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection,r=document.createElement(MD.CANVAS);r.getContext("2d");let o=r.captureStream(0);return n.addTrack(o.getVideoTracks()[0],o),e=yield n.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),$O.detail.isH264EncodeSupported=t,$O.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:$O.detail.isH264EncodeSupported,isVp8EncodeSupported:$O.detail.isVp8EncodeSupported}}catch(sN){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}}))},cw=function(){return ab(this,null,(function*(){if($O.detail.isH264DecodeSupported&&$O.detail.isVp8DecodeSupported)return{isH264DecodeSupported:$O.detail.isH264DecodeSupported,isVp8DecodeSupported:$O.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{let n=new RTCPeerConnection;return e=yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),n.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(sN){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}}))},lw=function(){return ab(this,null,(function*(){if($O.result)return $O;let e=tw(),t=Ow(),i=iw(),n=nw(),{isH264EncodeSupported:r,isVp8EncodeSupported:o}=yield aw(),{isH264DecodeSupported:s,isVp8DecodeSupported:a}=yield cw();return $O.result=e&&t&&n&&(r||o)&&(s||a),$O.detail.isBrowserSupported=e,$O.detail.isWebRTCSupported=t,$O.detail.isWebCodecsSupported=i,$O.detail.isMediaDevicesSupported=n,$O.detail.isScreenShareSupported=uw(),$O.detail.isSmallStreamSupported=Tw(),$O.detail.isH264EncodeSupported=r,$O.detail.isVp8EncodeSupported=o,$O.detail.isH264DecodeSupported=s,$O.detail.isVp8DecodeSupported=a,$O.result||GO.error("".concat(navigator.userAgent," ").concat(OO($O.detail,!1))),$O}))},dw=function(){return $O.result},uw=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},hw=(e,t,i)=>{"http:"===location.protocol&&!Yk&&(e[t]=()=>{throw new gb({code:_b.INVALID_OPERATION,message:zO.NOT_SUPPORTED_HTTP})})},pw=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(sO(e.selected)&&!e.selected)};function mw(){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 _w(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function fw(){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 gw(){return"captureStream"in HTMLCanvasElement.prototype}function Tw(){return!(nk||Pb||xk&&xk<63)&&!(!tw()||!gw())}var Ew=function(){if(nO(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:hN}),e.addTransceiver(MD.AUDIO),t=!0}catch(sD){}return null==e||e.close(),t};function Sw(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Iw(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function vw(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function yw(){return 11!==Gk&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var Aw=!(!yw()||Pk&&xk<74);function Rw(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Cw(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function bw(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Iw()}var kw=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Dw=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Nw="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&wk()>=86,Ow=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function ww(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return nO(window.AudioDecoder)||(e.AudioDecoder=!0),nO(window.AudioEncoder)||(e.AudioEncoder=!0),nO(window.VideoDecoder)||(e.VideoDecoder=!0),nO(window.VideoEncoder)||(e.VideoEncoder=!0),nO(window.ImageDecoder)||(e.ImageDecoder=!0),e}function Pw(){return"mediaSession"in navigator&&!nO(navigator.mediaSession.setActionHandler)}function Mw(){return!nO(window.WebTransport)}function Lw(){let e={browser:"".concat(qk.name,"/").concat(qk.version),os:eD(),displayResolution:mw(),isScreenShareSupported:uw(),isWebRTCSupported:Ow(),isGetUserMediaSupported:_w(),isWebAudioSupported:fw(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:ww(),isMediaSessionSupported:Pw(),isWebTransportSupported:Mw()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var xw=nb(cb(),1),Vw=Symbol("instance"),Uw=Symbol("cacheResult"),Fw=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,Ww.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Bw=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var Hw=new Map;function jw(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=Hw.get(n)||[];Hw.has(n)||Hw.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=Jw.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return i.sync?n[Uw]:Promise.resolve(n[Uw]);n.state instanceof Fw&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;Array.isArray(e)?0==e.length?n.state instanceof Fw&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new Bw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e.join("|")))):e!==n.state&&(l=new Bw(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e)));let d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(l)return d(l);let u=n.state,h=new Fw(u,t,s);Ww.call(n,h);let p=e=>{var r;return n[Uw]=e,h.aborted||(Ww.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[Uw])),e},m=e=>{let t=e instanceof Error?e.message:String(e);return Ww.call(n,u,e),d(new Bw(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(p).catch(m):i.sync?p(e):Promise.resolve(p(e))}catch(_){return m(_)}}}}var Gw="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 Ww(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(Jw.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var Jw=class extends xw.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=Jw.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[Vw];n?this.name=n.name+"-"+n.count++:i[Vw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=Hw.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);Hw.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=Jw.instances.get(e),t||Jw.instances.set(e,t=new Jw(e,void 0,Object.create(Jw.prototype)))):(t=Jw.instances2.get(e),t||Jw.instances2.set(e,t=new Jw(e.constructor.name,void 0,Object.create(Jw.prototype)))),t}static getState(e){var t;return null===(t=Jw.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Gw(Jw.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Ww.call(this,e)}};Jw.STATECHANGED="stateChanged",Jw.UPDATEAFSM="updateAFSM",Jw.INIT="[*]",Jw.ON="on",Jw.OFF="off",Jw.instances=new Map,Jw.instances2=new WeakMap;var Kw=(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)},Yw=(null==window?void 0:window.cancelIdleCallback)||function(e){clearTimeout(e)},zw=(null==window?void 0:window.cancelAnimationFrame)||(null==window?void 0:window.mozCancelAnimationFrame),qw=class{static generateTaskID(){return this.currentTaskID++}static run(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:LN,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;i=ZC(e===MN?{delay:2e3,count:0,backgroundTask:!0}:e===wN?{delay:1e4,count:0}:e===PN?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},i),aO(t)&&(i=ZC(ZC({},i),t)),iO(e)&&(t=e,e=LN);let n=ZC({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i);return this.taskMap.set(n.taskID,n),this[e](n),n.taskID}static interval(e){return e.intervalID=setInterval((()=>{e.callback(),e.loopCount+=1,this.isBreakLoop(e)}),e.delay)}static intervalInWorker(e){e.delay=(1e3/e.fps).toFixed(2);let t=new Worker(URL.createObjectURL(new Blob(["\n let timerID = null;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timerID = setInterval(() => {\n self.postMessage('tick');\n }, ".concat(e.delay,");\n } else if (e.data === 'stop') {\n clearInterval(timerID);\n }\n };\n ")])));t.onmessage=i=>{"tick"===i.data&&(e.callback(),e.loopCount+=1,this.isBreakLoop(e)&&t.postMessage("stop"))},e.worker=t,t.postMessage("start")}static timeout(e){let t=()=>{if(e.callback(),e.loopCount+=1,!this.isBreakLoop(e))return e.timeoutID=setTimeout(t,e.delay)};return e.timeoutID=setTimeout(t,e.delay)}static ric(e){let t,i=fO(),n=()=>{if(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),!this.isBreakLoop(e))return e.ricID=Kw(n,{timeout:e.delay})};return e.ricID=Kw(n,{timeout:e.delay})}static raf(e){e.delay=(1e3/e.fps).toFixed(2);let t,i=fO(),n=()=>document.hidden&&e.backgroundTask?(t=fO()-i,i=fO(),e.callback(),e.loopCount+=1,this.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(n,e.delay-Math.floor(t%e.delay))):(t=fO()-i,t>=e.delay&&(i=fO()-Math.floor(t%e.delay),e.callback(),e.loopCount+=1),this.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(n));if(e.rafID=requestAnimationFrame(n),e.backgroundTask){let t=()=>{if(document.hidden){let t=fO()-i;t>=e.delay?n():e.timeoutID=setTimeout(n,e.delay-t)}};document.addEventListener("visibilitychange",t),e.onVisibilitychange=t,document.hidden&&t()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:t,timeoutID:i,rafID:n,ricID:r,onVisibilitychange:o,worker:s}=this.taskMap.get(e);return s&&s.terminate(),t&&clearInterval(t),i&&clearTimeout(i),n&&zw(n),r&&Yw(r),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.taskMap.has(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};qw.taskMap=new Map,qw.currentTaskID=1;var Qw=qw;MD.SEI_MESSAGE;var Xw={LOADED_DATA:MD.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed"},$w=new class{constructor(){this._roomIdMap=new Map,"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:rD,env:AD.QCLOUD,browserVersion:qk.name+qk.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:n,roomId:r}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(r))}logSuccessEvent(e){Yk||!GO.isAbleToUpload||this._configs.env===AD.QCLOUD&&this.uploadEventToKibana(eb(ZC({},e),{result:"success"}))}logFailedEvent(e){if(Yk||!GO.isAbleToUpload)return;let{eventType:t,code:i,error:n,userId:r}=e,o={roomId:this._roomIdMap.get(r||this._configs.userId),userId:r,eventType:t,result:"failed",code:i||(null==n?void 0:n.extraCode)||(null==n?void 0:n.code)||_b.UNKNOWN};this._configs.env===AD.QCLOUD&&this.uploadEventToKibana(eb(ZC({},o),{error:n}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:n}=e,r={timestamp:Sb(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:rD,log:t};n&&(r.errorInfo=n.message),this.sendRequest(BN(this._configs.sdkAppId,yD.LOG),r)}sendRequest(e,t){GO.isAbleToUpload?LO({url:e,body:JSON.stringify(t)}).catch((()=>{})):setTimeout((()=>{this.sendRequest(e,t)}),1e3)}},Zw="trtc_autoplay",eP="".concat(Zw,"_mask"),tP="".concat(Zw,"_wrapper"),iP="".concat(Zw,"_header"),nP="".concat(Zw,"_content"),rP="".concat(Zw,"_action_wrapper"),oP="".concat(Zw,"_question"),sP="".concat(Zw,"_collapse"),aP="".concat(Zw,"_action_confirm"),cP="".concat(Zw,"_detail"),lP="#2473E8",dP="dialog",uP="".concat(dP,"-show"),hP="".concat(dP,"-1"),pP="".concat(dP,"-2"),mP=!1,_P=()=>!!document.querySelector(".".concat(tP)),fP="".concat(TD,"/").concat(XN()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),gP="<br><a href='".concat(fP,"' target='_blank'>").concat(XN()?"其他方案?":"Any other solution?","</a>"),TP="".concat(XN()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(gP):"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(gP)),EP=class{constructor(){if(ob(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),ob(this,"_dialogNode",null),ob(this,"_bodyPosition",""),ob(this,"_showDetail",!1),ob(this,"_isCollapseClicked",!1),ob(this,"_isQuestionClicked",!1),XN()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!mP){let e=document.createElement("style");e.innerHTML=".".concat(eP,"{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(eP," div:not(.").concat(rP,"){display:block !important;}.").concat(tP,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(tP," a{color:").concat(lP,";}.").concat(iP,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(nP,"{margin:8px 0;}.").concat(rP,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(sP,"{margin-right:auto;cursor:pointer}.").concat(oP,"{height:100%;line-height:16px;cursor:pointer;}.").concat(aP,"{margin-left:8px;color:#fff;background:").concat(lP,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(aP,":hover{opacity:0.9;}.").concat(sP,",.").concat(aP,",.").concat(nP,",.").concat(oP,"{font-size:14px;}@media screen and (max-width:750px){.").concat(tP,"{width:80vw;}}"),document.head.appendChild(e),mP=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(eP,"\"><div class='").concat(tP,"'><div class='").concat(iP,"'>").concat(location.host,"</div><div class='").concat(nP,"'>").concat(this.content,"</div><div class='").concat(cP,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(TP,"</div><div class='").concat(rP,"'></div></div></div>").trim();let t=document.createElement("button");t.className=aP,t.innerText=XN()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=oP,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=sP,n.innerText="".concat(XN()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let r=e.content.firstChild,o=r.querySelector(".".concat(rP));return o.appendChild(n),o.appendChild(i),o.appendChild(t),r}addDiaLog(){_P()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(tP)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",GO.info("show autoplay dialog"),$w.uploadEvent({log:uP}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){GO.warn("confirm clicked, try resume stream"),FO.emit(HO.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(cP));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||$w.uploadEvent({log:hP}),this._isCollapseClicked=!0}onQuestionClick(){window.open(fP,"_blank"),this._isQuestionClicked||$w.uploadEvent({log:pP}),this._isQuestionClicked=!0}},SP={};ib(SP,{create:()=>vP,remove:()=>yP});var IP=new WeakMap;function vP(e,t){IP.has(e)||IP.set(e,[]);let i=IP.get(e),n={add:(e,r)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,r)),t.addEventListener(e,r)):(i.push(t.off.bind(t,e,r)),t.on(e,r)),n)};return n}function yP(e){let t=IP.get(e);t&&(t.forEach((e=>e())),IP.delete(e))}var AP=class extends Jw{constructor(e,t){super(e.id,"".concat(t,"-player")),this.kind=t,ob(this,"id"),ob(this,"element",null),ob(this,"container",null),ob(this,"mediaStream",new MediaStream),ob(this,"track"),ob(this,"url"),ob(this,"attr"),ob(this,"muted"),ob(this,"_log"),ob(this,"_pausedRetryCount"),ob(this,"_isElementPlayingFired",!1),ob(this,"_interval"),this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=AN,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return"PLAYING"===this._state}get isStopped(){return"STOPPED"===this._state}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(Xw.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element))){let t=new MediaStream;t.addTrack(e),this.element.srcObject=t}}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))}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return ab(this,null,(function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(sD){let t=XO({key:YO.PLAY_FAILED,data:{media:this.kind,error:sD}});if(this.track&&!this.track.muted&&this._log.warn(sD),t.includes("NotAllowedError"))throw new gb({code:_b.PLAY_NOT_ALLOWED,message:t})}}))}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(MD.ENDED),this._interval>0&&Qw.clearTask(this._interval)}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this.isPlaying?Promise.resolve():Jk?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,t){this.element&&(this.element.style.width="".concat(e,"px"),this.element.style.height="".concat(t,"px"))}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return vP(this.element,this.element).add(MD.PLAYING,e).add(MD.ENDED,e).add(MD.PAUSE,e).add(MD.ERROR,e).add(MD.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);null==SP||SP.create(this.track,this.track).add(MD.ENDED,e).add(MD.MUTE,e).add(MD.UNMUTE,e),this.track.readyState===MD.ENDED&&this.handleTrackEvent({type:MD.ENDED}),this.track.muted&&this.handleTrackEvent({type:MD.MUTE})}}bindAutoPlayEvent(){FO.on(HO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&yP(this.track)}unbindEvents(){this.element&&yP(this.element),this.unbindTrackEvents(),FO.off(HO.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var t;switch(e.type){case MD.PLAYING:this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(MD.PLAYING),this._interval&&(Qw.clearTask(this._interval),this._interval=-1);break;case MD.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(MD.ENDED);break;case MD.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(MD.PAUSE);let e=this.container&&document.getElementById(this.container.id);e||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id));let i=wk();this._pausedRetryCount>0&&(this.kind===MD.VIDEO&&!_P()||this.kind===MD.AUDIO&&(oO(i)&&i<=70||!e))&&(this._log.info("".concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),Pb&&(this._interval=Qw.run(LN,(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case MD.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)),$w.uploadEvent({log:"stat-".concat(this.kind,"-").concat(cN.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error})}break;case MD.LOADEDDATA:this.kind===MD.VIDEO&&this.emit(Xw.LOADED_DATA)}}handleTrackEvent(e){switch(e.type){case MD.ENDED:this._log.info("".concat(this.kind," track is ended")),this.handleStopped(MD.ENDED);break;case MD.MUTE:this._log.info("".concat(this.kind," track is unable to provide media output")),this.handlePaused(MD.MUTE);break;case MD.UNMUTE:this._log.info("".concat(this.kind," track is able to provide media output")),this._isElementPlayingFired&&this.handlePlaying(MD.UNMUTE)}}handlePlaying(e){this.emit(Xw.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Xw.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Xw.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};rb([jw([],"PLAYING",{sync:!0})],AP.prototype,"handlePlaying",1),rb([jw("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],AP.prototype,"handlePaused",1),rb([jw([],"STOPPED",{sync:!0})],AP.prototype,"handleStopped",1);var RP=class extends AP{constructor(e){super(e,MD.VIDEO),ob(this,"viewMirror",!1),ob(this,"objectFit"),nO(e.viewMirror)||(this.viewMirror=e.viewMirror),nO(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var e;let t=document.createElement(MD.VIDEO);if(this.track){let e=new MediaStream;e.addTrack(this.track),t.srcObject=e}t.muted=!0;let i="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");this.viewMirror&&(i+="transform: scaleX(-1);"),t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",i),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),null==(e=this.container)||e.appendChild(t),this.element=t,this.bindElementEvents()}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(MD.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(MD.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){super.handleElementEvent(e);let t=e.type;if(this.viewMirror&&this.element){let e=this.element.style.transform;t===MD.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):t===MD.LEAVE_PICTURE_IN_PICTURE&&!e.includes("scaleX")&&(this.element.style.transform="".concat(e," scaleX(-1)"))}}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)}setViewMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit="".concat(e)),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){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}},CP=!1,bP=class{constructor(e){ob(this,"context_"),ob(this,"blob_"),this.context_=e.context,this.blob_=new Blob(['class VolumeMeter extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=this.intervalTime,this.isStop=!1,this.port.onmessage=t=>{let{data:e}=t;switch(e.name){case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"stop":this.isStop=!0}}}process(t){let e=t[0];if(this.isStop)return!1;if(e.length>0){let i=e[0],s=0;for(let l=0;l<i.length;++l)s=Math.max(Math.abs(i[l]),s);this.volume=s,this.tick-=i.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume}))}return!0}}registerProcessor("volume-meter",VolumeMeter);'],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return ab(this,null,(function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),GO.info("worklet addModule success"),FO.emit(HO.WORKLET_LOADED_SUCCESS),CP=!0}catch(QM){GO.info("worklet addModule catch error. ".concat(QM.message)),FO.emit(HO.WORKLET_LOADED_FAILED)}}))}get initWorkletSuccess(){return CP}};"undefined"!=typeof window&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var kP,DP,NP=0,OP=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new window.AudioContext(ZC({sampleRate:48e3},t)),n=++NP,r=()=>{"suspended"===i.state?(i.resume(),document.addEventListener("click",r)):"interrupted"===i.state?i.resume():document.removeEventListener("click",r)};return document.addEventListener("click",r),i.onstatechange=()=>{GO.info("".concat(e,"-").concat(n," context state: ").concat(i.state)),r()},i},wP=0,PP=class{constructor(e){ob(this,"_volume"),ob(this,"_log"),ob(this,"_track"),ob(this,"_stream"),ob(this,"_audioCtx"),ob(this,"_destination"),ob(this,"_streamSource"),ob(this,"_scriptProcessorNode"),ob(this,"_audioWorkletNode"),ob(this,"_interval");let{track:t,log:i}=e;this._volume=0,this._log=i,this._track=t,kP||(kP=OP("volume-meter")),this._audioCtx=kP,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,FO.on(HO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),mO?(FO.on(HO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),FO.on(HO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),wP+=1}preload(){DP?DP.initWorkletSuccess&&this.initAudioWorklet():DP=new bP({context:kP})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(QM){$w.logFailedEvent({userId:this._log.userId,eventType:cN.LOAD_WORKLET,error:QM}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),i=0;for(let n=0;n<t.length;++n)i+=t[n]*t[n];this._volume=Math.sqrt(i/t.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(QM){this._log.error("volumeMeter init script processor error: ".concat(QM))}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,FO.off(HO.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),FO.off(HO.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),FO.off(HO.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),wP>0&&(wP-=1),0===wP&&(null==kP||kP.close(),kP=null,DP=null)}resume(){null==kP||kP.resume()}setTrack(e){if(this._audioCtx&&this._audioWorkletNode){if(!e)return this._streamSource.disconnect();this._track=e,this._streamSource.disconnect(),this._streamSource=this._audioCtx.createMediaStreamSource(new MediaStream([e])),this._streamSource.connect(this._audioWorkletNode)}}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})}},MP=null,LP=0,xP=class extends AP{constructor(e){super(e,MD.AUDIO),ob(this,"_volumeMeter"),ob(this,"_gainedTrack",null),ob(this,"_gainNode",null),ob(this,"_destination",null),ob(this,"_mediaStreamSource",null),ob(this,"_sourceElement",null),ob(this,"_outputDeviceId"),ob(this,"_volume",1),ob(this,"_loop",!1),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter?this._volumeMeter.setTrack(e):e&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new PP({track:this._gainedTrack||e,log:this._log})}initializeElement(){if(("15.2"===jk||"15.3"===jk||"15.4"===jk)&&this.muted)return void this._log.info("audioElement is muted.");let e=document.createElement(MD.AUDIO);this.track&&(e.srcObject=new MediaStream([this._gainedTrack||this.track])),e.muted=this.muted,e.setAttribute("id","audio_".concat(this.id)),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,this.bindElementEvents()}play(){return ab(this,null,(function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield sb(xP.prototype,this,"play").call(this)}))}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),this.destroyGain(),super.stop()}resume(){return ab(this,null,(function*(){yield sb(xP.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()}))}setSinkId(e){return ab(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))}))}setVolume(e){this._volume=e,this._gainNode?this._gainNode.gain.value=e:e>1?this.createGain(e):this.element&&(this.element.volume=e)}createGain(e){if(!this.track)return;MP||(MP=OP("player")),this._log.info("create gainNode ".concat(e));let t=MP.createMediaStreamSource(new MediaStream([this.track])),i=MP.createGain(),n=MP.createMediaStreamDestination();t.connect(i),i.connect(n),i.gain.value=e,this._gainNode=i,this._destination=n,this._mediaStreamSource=t,this._gainedTrack=n.stream.getAudioTracks()[0],LP+=1,this.element&&(yP(this.element),this._sourceElement=this.element,this.element.muted=!0,this.element=null),this.play()}destroyGain(){var e,t,i;!this._gainNode||(this._log.info("destroy gainNode"),null==(e=this._gainNode)||e.disconnect(),null==(t=this._destination)||t.disconnect(),null==(i=this._mediaStreamSource)||i.disconnect(),this._gainNode=null,this._destination=null,this._mediaStreamSource=null,this._sourceElement&&(this._sourceElement.srcObject=null,this._sourceElement=null),this._gainedTrack=null,0===(LP-=1)&&MP&&(this._log.info("destroy gain audioContext"),MP.close(),MP=null))}setLoop(e){!this.element||(this.element.loop=e,this._loop=e)}getAudioLevel(){var e;return(null==(e=this._volumeMeter)?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return null==(e=this._volumeMeter)?void 0:e.getInternalAudioLevel()}},VP=class extends Jw{constructor(e){let{userId:t,sdkAppId:i,mediaType:n,room:r,isInitPlayer:o=!0}=e;var s;super(),ob(this,"id",WO()),ob(this,"userId",""),ob(this,"isRemote"),ob(this,"mediaType"),ob(this,"room"),ob(this,"user"),ob(this,"_log"),ob(this,"_inputTrack"),ob(this,"_outputTrack"),ob(this,"isPlayCalled"),ob(this,"container",null),ob(this,"player"),ob(this,"subVideoPlayerMap"),ob(this,"muted",!1),ob(this,"playerMuted",!1),ob(this,"abortCtrl"),ob(this,"audioOutputDeviceId"),ob(this,"playbackVolume",1),ob(this,"objectFit","cover"),ob(this,"mirror",!1),ob(this,"isScreen",!1),ob(this,"manager"),nO(t)||(this.userId=t),this.mediaType=n,this._log=GO.createLogger({id:"".concat(this.kind[0],"t"),userId:null==(s=r||this.room)?void 0:s.userId,remoteUserId:this instanceof dM?void 0:this.userId,sdkAppId:i,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof dM}),o&&this.initPlayer()}get log(){return this._log||GO}get kind(){return 1===this.mediaType?MD.AUDIO:MD.VIDEO}get strMediaType(){return 4===this.mediaType?MD.VIDEO:2===this.mediaType?MD.SCREEN:MD.AUDIO}get streamType(){return 0==(2&this.mediaType)?"main":"auxiliary"}play(e,t){return ab(this,null,(function*(){let i=cO(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!nO(t.muted)&&this.setPlayerMute(t.muted),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.setMirror(null==t?void 0:t.mirror),void(this.kind===MD.VIDEO&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),cO(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!nO(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===MD.VIDEO)&&this.setPlayerMute(!0),t&&!nO(t.objectFit)&&(this.objectFit=t.objectFit),this.setMirror(null==t?void 0:t.mirror),this.kind===MD.VIDEO&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,i&&(this.container=i,this.player.setContainer(i)),FO.emit(HO.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this._outputTrack),yield this.player.play(),cO(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}}else this.log.info("play has not mediaTrack, abort")}))}setMirror(e,t){if(this.isScreen||this.kind!==MD.VIDEO||nO(e)&&this.isRemote)return;this.mirror=nO(e)?"view":e;let i=this.player;if(t&&(i=t),sO(this.mirror))return i.setViewMirror(this.mirror),void(this.room&&(this.room.videoManager.mirror=!1));switch(this.mirror){case"view":this.room&&(this.room.videoManager.mirror=!1),i.setViewMirror(!0);break;case"publish":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!0);break;case"both":this.room&&(this.room.videoManager.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return ab(this,null,(function*(){if(!this._outputTrack||this.kind===MD.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var n;e.find((e=>i===e))||(t.stop(),t.setContainer(null),null==(n=this.subVideoPlayerMap)||n.delete(i))}));for(let[n,r]of e.entries()){let e=this.subVideoPlayerMap.get(r);e?t&&(nO(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new RP({id:this.userId||this.id,track:this.outMediaTrack,container:r,muted:this.playerMuted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let e of i)this.setMirror(null==t?void 0:t.mirror,e),yield e.play()}))}initPlayer(){this.log.info("create player"),this.kind===MD.AUDIO?this.player=new xP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new RP({id:this.userId||this.id,track:this.outMediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,log:this.log}),this.player.on(Xw.LOADED_DATA,(()=>{FO.emit(HO.VIDEO_LOADED_DATA,{track:this})})),this.player.on(Xw.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.player.on(Xw.PLAYER_STATE_CHANGED,(e=>{FO.emit(HO.PLAYER_STATE_CHANGED,ZC({track:this},e)),this.emit("player-state-changed",e)}))}setAudioOutput(e){return ab(this,null,(function*(){var t;this.audioOutputDeviceId=e,yield null==(t=this.player)?void 0:t.setSinkId(e)}))}setAudioVolume(e){var t;this.playbackVolume=e,this.log.info("setAudioVolume to ".concat(e)),null==(t=this.player)||t.setVolume(e)}getAudioLevel(){var e;return(null==(e=this.player)?void 0:e.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.player.setContainer(null)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop(),e.setContainer(null)})),this.container=null)}resume(){return ab(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){return this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),FO.emit(e?HO.TRACK_MUTED:HO.TRACK_UNMUTED,{track:this}),!0}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}setInputMediaStreamTrack(e){let t=this._inputTrack;if(e!==t)return this._inputTrack=e,e.enabled=!this.muted,this.emit("input-media-track-changed",e||null,t||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,e.enabled=!this.muted,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.outMediaTrack),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 EP;else{let e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0),document.removeEventListener("touchstart",e,!0)}))};document.addEventListener("click",e,!0),document.addEventListener("touchstart",e,!0)}}};rb([jw([],Jw.INIT,{sync:!0})],VP.prototype,"close",1);var UP=Object.prototype.hasOwnProperty;var FP=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($N(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(UP.call(e,t))return!1;return!0}return!1},BP=nb(cb(),1),HP=e=>t=>t.deviceId===e,jP=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";ob(this,"kind"),ob(this,"type"),ob(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&&JP(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(HP(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Added");GO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(HP(e.deviceId))){let i="".concat(this.kind).concat(this.type,"Removed");GO.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},GP=class extends BP.EventEmitter{constructor(){super(),ob(this,"audioInputs",new jP(MD.AUDIO)),ob(this,"videoInputs",new jP(MD.VIDEO)),ob(this,"audioOutputs",new jP(MD.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||Qw.run(MN,(()=>{this.update()}),{delay:1e4}))}init(){KP().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}update(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){let i=yield KP(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e}()}))}},WP=dD||lD?null:new GP;function JP(e){return e.deviceId===e.groupId&&""===e.groupId}function KP(){return ab(this,arguments,(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function*(){if(ow()||!nw())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(0!==e){let i={audio:!1,video:!1};if(t.forEach((e=>{JP(e)&&(e.kind===MD.AUDIO_INPUT?i.audio=!0:e.kind===MD.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e=yield navigator.mediaDevices.getUserMedia(i);t=yield navigator.mediaDevices.enumerateDevices(),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&&QP.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}()}))}function YP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return WP.update(e?1:0).then((e=>e.audioInputs.devices))}function zP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return WP.update(e?2:0).then((e=>e.videoInputs.devices))}function qP(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return ab(this,null,(function*(){return WP.update(e?1:0).then((e=>e.audioOutputs.devices))}))}var QP=new Set;function XP(e,t){return ab(this,null,(function*(){let i=(yield YP()).find((e=>e.deviceId===RN));return(null==i?void 0:i.groupId)===e&&i.label===t}))}var $P=VO({retryFunction:function(e){return ab(this,null,(function*(){let t=function(e){return{audio:eM(e),video:tM(e)}}(e);GO.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],n=[],r=["label","deviceId"];t.audio&&(i=yield YP(),GO.info("microphones: ".concat(NO(i,{keysToInclude:r})))),t.video&&(n=yield zP(),GO.info("cameras: ".concat(NO(n,{keysToInclude:r}))));try{let e=yield navigator.mediaDevices.getUserMedia(t);return Dw&&e.getTracks().forEach((e=>{GO.info("".concat(e.kind," capabilities: ").concat(NO(e.getCapabilities(),{keysToInclude:xN})))})),e}catch(o){if("NotFoundError"===o.name){if(e.video&&n&&0===n.length)throw new gb({code:_b.DEVICE_NOT_FOUND,message:XO({key:YO.CAMERA_NOT_FOUND})});if(e.audio&&i&&0===i.length)throw new gb({code:_b.DEVICE_NOT_FOUND,message:XO({key:YO.MICROPHONE_NOT_FOUND})})}throw new gb({code:_b.INITIALIZE_FAILED,name:o.name,message:o.message,constraint:o.constraint})}}))},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:n,retryFuncArgs:r,retriedCount:o}=e,s=o+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===s?r[0].video&&(r[0].maxResolution=!1,r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)):2===s?r[0].useDeviceIdOnly=!0:3===s&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),i()):n(t),r[0].microphoneId&&ZP(r[0].microphoneId,!1),r[0].cameraId&&ZP(r[0].cameraId,!0)},onRetrying:e=>{GO.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{$w.logFailedEvent({eventType:cN.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{$w.logSuccessEvent({eventType:cN.GET_USER_MEDIA_RETRY}),$w.uploadEvent({log:"stat-".concat(cN.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function ZP(e,t){return ab(this,null,(function*(){let i=(t?yield zP():yield YP()).find((t=>t.deviceId===e));i&&iO(i.getCapabilities)&&GO.warn(NO(i.getCapabilities(),{keysToInclude:xN}))}))}function eM(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!FP(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(oO(e.channelCount)&&(t.channelCount=e.channelCount),sO(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),sO(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),sO(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!FP(t)||t)}function tM(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&&!FP(i)?i:(e.width&&(i.width={ideal:e.width},t&&!Ub&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!Ub&&(i.height.max=e.height)),Ub&&_k&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!FP(i)||i)}var iM=$P;function nM(e){return oM(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return ab(this,null,(function*(){return yield e.apply(this,n),t.apply(this,n)}))}))}function rM(e){return oM(((t,i)=>function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return ab(this,null,(function*(){return e.call(this,t.apply(this,n))}))}))}function oM(e){return function(t,i,n){return n.value=e(n.value,i),n}}var sM=new WeakMap,aM=new WeakMap;function cM(){return function(e,t,i){let n=i.value,r=e=>{let{fn:t,args:i,context:n,resolve:r,reject:o}=e;t.apply(n,i).then(r,o)};return i.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(sM.has(this)){let o=sM.get(this),{length:s}=o;o.push({fn:n,args:t,context:this,resolve:e,reject:i}),0===s&&r({fn:n,args:t,context:this,resolve:e,reject:i})}else sM.set(this,[{fn:n,args:t,context:this,resolve:e,reject:i}]),r({fn:n,args:t,context:this,resolve:e,reject:i})})).finally((()=>{let e=sM.get(this);e&&(e.shift(),e[0]&&r(ZC({},e[0])))}))},i}}function lM(e){return function(t,i,n){let r=n.value,o=t=>oO(e)?t[e]:e(...t),s=e=>{let{fn:t,args:i,context:n,resolve:r,reject:a}=e;t.apply(n,i).then(r,a).finally((()=>{if(aM.has(n)&&aM.get(n).has(o(i))){let e=aM.get(n).get(o(i));e&&(e.shift(),e[0]&&s(ZC({},e[0])))}}))};return n.value=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return new Promise(((e,i)=>{if(aM.has(this))if(aM.get(this).has(o(t))){let n=aM.get(this).get(o(t));if(n){let{length:o}=n;n.push({fn:r,args:t,context:this,resolve:e,reject:i}),0===o&&s({fn:r,args:t,context:this,resolve:e,reject:i})}}else aM.get(this).set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),s({fn:r,args:t,context:this,resolve:e,reject:i});else{let n=new Map;n.set(o(t),[{fn:r,args:t,context:this,resolve:e,reject:i}]),aM.set(this,n),s({fn:r,args:t,context:this,resolve:e,reject:i})}}))},n}}var dM=class extends VP{constructor(e){super({mediaType:e,isInitPlayer:!(arguments.length>1&&void 0!==arguments[1])||arguments[1]}),ob(this,"isRemote",!1),ob(this,"deviceId"),ob(this,"groupId",""),ob(this,"label",""),ob(this,"_isRecapturing",!1),ob(this,"_lastRecaptureTime",0),ob(this,"_onMuteTimeoutId",-1),ob(this,"profile"),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}get isPublished(){return"publish"===this.state}installTrackEvent(e){vP(e,e).add(MD.MUTE,this.onTrackMuted).add(MD.UNMUTE,this.onTrackUnmuted).add(MD.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===MD.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){yP(e)}setStateToCapture(){}capture(e){return ab(this,null,(function*(){var t;try{let i;FO.emit(HO.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(i=new MediaStream,i.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),i=yield iM(e));let n=i.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),FO.emit(HO.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),i}catch(aD){throw FO.emit(HO.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:aD}),this.log.error("getUserMedia error observed ".concat(aD)),aD}}))}setInputMediaStreamTrack(e){this.state===Jw.INIT&&this.setStateToCapture(),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack);let t=super.setInputMediaStreamTrack(e);return this.installTrackEvent(e),t}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),FO.emit(HO.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return ab(this,null,(function*(){if(this.mediaTrack&&kw){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;(yield function(e){return ab(this,arguments,(function(e){let{newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:r,kind:o}=e;return function*(){return t===i&&(o!==MD.AUDIO||t!==RN||(yield XP(n,r)))}()}))}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=i,t&&(this.groupId=t),KP().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===MD.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(MD.AUDIO_INPUT);return!!QP.has(i)}(this.mediaTrack)||this.kind===MD.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(MD.VIDEO_INPUT);return!!QP.has(i)}(this.mediaTrack)||this._isRecapturing||e&&_k&&Uk)}onTrackMuted(){if(PO(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ON)return void setTimeout((()=>this.onTrackMuted()),ON);this._onMuteTimeoutId=setTimeout((()=>ab(this,null,(function*(){var e;(null==(e=this.mediaTrack)?void 0:e.muted)&&"visible"===document.visibilityState&&this.recapture(yield this.getRecoverCaptureDeviceId())}))),5e3)}}onTrackUnmuted(){this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return ab(this,null,(function*(){if(this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ON)return void setTimeout((()=>this.onTrackEnded()),ON);this.recapture(yield this.getRecoverCaptureDeviceId())}}))}recapture(e){return ab(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 YP():yield zP()).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 ab(this,null,(function*(){let e=this instanceof pM;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let i=(uM.get(t)||0)+1;if(uM.set(t,i),i>=3){let n=e?(yield zP()).find((e=>!uM.has(e.deviceId))):(yield YP()).find((e=>!uM.has(e.deviceId)));n&&(this.log.warn("".concat(t," capture fail ").concat(i," times, change new ").concat(n.deviceId)),t=n.deviceId)}}return t}))}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}};rb([jw(Jw.INIT,"capture",{ignoreError:!0,sync:!0})],dM.prototype,"setStateToCapture",1),rb([cM()],dM.prototype,"capture",1),rb([jw("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),FO.emit(HO.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===_b.API_CALL_ABORTED&&(t="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:i})}})],dM.prototype,"publish",1),rb([oM((e=>function(){return ab(this,null,(function*(){let t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),2===this.mediaType&&(this.mediaType=4)}))})),jw([],"capture",{sync:!0})],dM.prototype,"unpublish",1);var uM=new Map;FO.on(HO.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&uM.delete(e.track.deviceId)}));var hM=class extends dM{constructor(e){super(1),ob(this,"mediaType",1),ob(this,"volume",0),ob(this,"captureVolume",1),ob(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,"playerMuted",!0),this.manager=e}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}capture(e){let{deviceId:t,customSource:i,useExactDeviceId:n=!1}=e;return super.capture({video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:n,customSource:i})}switchDevice(e){return ab(this,null,(function*(){if(this.mediaTrack){if(this.deviceId===e){if(e!==RN)return;if(yield XP(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)),FO.emit(HO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(sN){throw this.log.error("switch microphone failed ".concat(sN)),this.deviceId&&this.recapture(this.deviceId),sN}}}))}listenDeviceChange(){WP&&!WP.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&WP.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return ab(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current microphone is lost: ".concat(JSON.stringify(e)));let t=yield YP();t[0]?this.recapture(t[0].deviceId):WP.on("audioInputAdded",this.handleMicrophoneAdded,this)}}))}handleMicrophoneAdded(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}update3A(e){return ab(this,arguments,(function(e){var t=this;let{echoCancellation:i,noiseSuppression:n,autoGainControl:r}=e;return function*(){let e=!1;!nO(i)&&i!==t.profile.echoCancellation&&(t.profile.echoCancellation=i,e=!0),!nO(n)&&n!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=n,e=!0),!nO(r)&&r!==t.profile.autoGainControl&&(t.profile.autoGainControl=r,e=!0),e&&t.deviceId&&(yield t.recapture(t.deviceId))}()}))}setCaptureVolume(e){var t;let i=e/100;i!==this.captureVolume&&(null==(t=this.manager)||t.setCaptureVolume(i),this.captureVolume=i)}unpublish(){var e;return null==(e=this.manager)||e.removeAudioTrack(this),super.unpublish()}close(){WP.off("audioInputAdded",this.handleMicrophoneAdded,this),WP.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}},pM=class extends dM{constructor(e){super(4),ob(this,"mediaType",4),ob(this,"profile",{width:640,height:480,frameRate:15,bitrate:500}),ob(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0}),ob(this,"small"),ob(this,"isNeedToSetBandwidth"),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(eb(ZC({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",t),this.on("publish",t)}get facingMode(){if(kw&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}capture(e){let{deviceId:t,facingMode:i,useExactDeviceId:n=!1,customSource:r}=e;return super.capture({audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,customSource:r})}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),null==(t=this.room)?void 0:t.replaceTrack(this)}setProfile(e){!e||(e.width*e.height<=19200&&Mb&&Pk&&(this.log.warn("resolution is ".concat(e.width,"*").concat(e.height,", fallback to 240*180")),e.width>e.height?(e.width=240,e.height=180):(e.width=180,e.height=240),e.bitrate=Math.max(e.bitrate,150)),e.bitrate&&(this.isNeedToSetBandwidth=e.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(e):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(eb(ZC({},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:MD.VIDEO,videoType:MD.BIG})})):void 0}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return kw&&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:MO()&&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 ab(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),FO.emit(HO.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(sN){throw this.log.error("switch camera failed ".concat(sN)),this.deviceId&&this.recapture(this.deviceId),sN}}))}listenDeviceChange(){WP&&!WP.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&WP.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return ab(this,null,(function*(){if(e.deviceId===this.deviceId){this.log.warn("current camera is lost: ".concat(JSON.stringify(e)));let t=yield zP();t[0]?this.recapture(t[0].deviceId):WP.on("videoInputAdded",this.handleCameraAdded,this)}}))}handleCameraAdded(e){return ab(this,null,(function*(){this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}))}close(){WP.off("videoInputAdded",this.handleCameraAdded,this),WP.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}};var mM=function(e){return ab(this,null,(function*(){let t=null,i=function(e){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:Uk?{max:e.width}:{ideal:e.width,max:e.width},height:Uk?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:"monitor"};if(t.video=i,e.systemAudio){let{echoCancellation:i=!0,noiseSuppression:n=!1,autoGainControl:r=!1}=e;t.audio={echoCancellation:i,noiseSuppression:n,autoGainControl:r,sampleRate:48e3}}return t}(e);GO.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let n=yield navigator.mediaDevices.getDisplayMedia(i);if(e.systemAudio&&0===n.getAudioTracks().length&&(Mk&&xk<74||Uk||Ub)&&GO.warn("Your browser not support capture system audio"),e.frameRate&&n.getVideoTracks()[0]&&n.getVideoTracks()[0].applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height}).catch((e=>{GO.warn("screen applyConstraints failed: ".concat(e))})),e.audio){let i=function(e){let t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return nO(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e);GO.info("getUserMedia with constraints: ".concat(JSON.stringify(i))),t=yield navigator.mediaDevices.getUserMedia(i),n.addTrack(t.getAudioTracks()[0])}return n}))},_M=class extends pM{constructor(e){super(e),ob(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),ob(this,"objectFit","contain"),ob(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}capture(e){return ab(this,arguments,(function(e){var t=this;let{systemAudio:i=!1,autoGainControl:n,echoCancellation:r,noiseSuppression:o,audioTrack:s,videoTrack:a}=e;return function*(){try{let e;return a||s?(e=new MediaStream,a&&e.addTrack(a),s&&e.addTrack(s)):e=yield mM({audio:!1,systemAudio:i,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:n,echoCancellation:r,noiseSuppression:o}),yield t.setInputMediaStreamTrack(e.getVideoTracks()[0]),e}catch(e){throw t.log.error("getDisplayMedia error observed ".concat(e)),e instanceof gb?e:new gb({code:_b.INITIALIZE_FAILED,name:e.name,message:e.message})}}()}))}switchDevice(e){return ab(this,null,(function*(){throw new Error("Method not implemented.")}))}},fM=class extends hM{constructor(e){super(e),this._log.id="s-".concat(this._log.id)}},gM=class extends hM{constructor(e){super(e),ob(this,"_inputs",new Map),ob(this,"_destination"),ob(this,"audioContext",OP("audio-mixer")),this._log.id="m-".concat(this._log.id),"running"!==this.audioContext.state&&this._log.warn("audio mixer context state: ".concat(this.audioContext.state)),this._destination=this.audioContext.createMediaStreamDestination(),this._destination.channelCount=1}addTrack(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._inputTrack=e;let i=this.audioContext.createMediaStreamSource(new MediaStream([t?e.clone():e]));this._inputs.set(e,{sourceNode:i,clone:t}),i.connect(this._destination),this._outputTrack||(this._outputTrack=this._destination.stream.getAudioTracks()[0],this.setStateToCapture())}setTrackCaptureVolume(e,t){if(!this._inputs.has(e)||!this._destination)return;let i=this._inputs.get(e),{sourceNode:n}=i;i.gainNode||(this._log.info("create GainNode"),i.gainNode=this.audioContext.createGain()),i.gainNode.gain.value=t,n.disconnect(),n.connect(i.gainNode).connect(this._destination)}publish(e,t){return this.room=e,t}unpublish(){delete this.room}replaceTrack(e,t){var i;if(!this.hasMix)return;let n=1;if(t){let r=this._inputs.get(t);r&&(r.sourceNode.disconnect(),r.gainNode&&(n=r.gainNode.gain.value,null==(i=r.gainNode)||i.disconnect()),this._inputs.delete(t),this.addTrack(e.outMediaTrack,r.clone),1!==n&&this.setTrackCaptureVolume(e.outMediaTrack,n))}}removeTrack(e){let t=this._inputs.get(e);!t||(t.sourceNode.disconnect(),this._inputs.delete(e),this._inputTrack===e&&delete this._inputTrack,0===this._inputs.size&&(delete this._outputTrack,this.unpublish(),this.close()))}close(){this.stop(),this.audioContext.close()}get hasMix(){return!!this._outputTrack}set channelCount(e){this._destination.channelCount=e}};rb([jw("capture","publish",{ignoreError:!0})],gM.prototype,"publish",1),rb([jw([],"capture",{sync:!0})],gM.prototype,"unpublish",1);var TM=class extends dM{constructor(e,t){super(1),ob(this,"musicId"),ob(this,"mediaType",1),ob(this,"volume",0),ob(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),ob(this,"playerMuted",!1),ob(this,"audio"),ob(this,"_audioContext"),ob(this,"_destination"),ob(this,"_source",null),this.manager=e,this.initAudioContext(),this._destination=this._audioContext.createMediaStreamDestination(),this._destination.channelCount=1,this.audio=document.createElement("audio"),this.audio.src=t.url,this.audio.crossOrigin="anonymous",sO(t.loop)&&this.loop(t.loop),oO(t.volume)&&this.setVolume(t.volume),t.id&&(this.musicId=t.id),this._source=this._audioContext.createMediaElementSource(this.audio),this._source.connect(this._destination),this.setInputMediaStreamTrack(this._destination.stream.getAudioTracks()[0]),this.installPlayerEvent()}play(){return ab(this,null,(function*(){try{yield this.audio.play(),yield sb(TM.prototype,this,"play").call(this,null,{muted:!1}),this._log.info("music ".concat(this.musicId," play success"))}catch(sD){this._log.error("music ".concat(this.musicId," play error"),sD)}}))}installPlayerEvent(){this.audio.addEventListener("error",this.handleAudioError.bind(this))}uninstallPlayerEvent(){this.audio.removeEventListener("error",this.handleAudioError.bind(this))}handleAudioError(e){this._log.warn("local music ".concat(this.musicId," audio error"),e)}initAudioContext(){this._audioContext=OP("music"),"running"!==this._audioContext.state&&this._log.warn("local music ".concat(this.musicId," context state: ").concat(this._audioContext.state))}destroy(){var e,t;null==(e=this._source)||e.disconnect(),null==(t=this._destination)||t.disconnect(),this.uninstallPlayerEvent(),this.player.stop(),this._audioContext.close().then((()=>{this._source=null,this._destination=null,this._audioContext=null}))}getStream(){var e;return(null==(e=this._destination)?void 0:e.stream)||null}seek(e){e<0&&e>this.duration()?this._log.warn("Time beyond song duration."):this.audio.currentTime=e}getPosition(){return this.audio.currentTime||0}setVolume(e){e>1&&e<0?this.log.warn("volume is out of range"):this.audio.volume=e}getVolume(){return this.audio.volume||0}setPlayBackRate(e){e>8&&e<0?this.log.warn("rate is out of range"):this.audio.playbackRate=e}getPlayBackRate(){return this.audio.playbackRate||0}duration(){return this.audio.duration||0}loop(e){return this.audio&&sO(e)&&(this.audio.loop=e),this.audio.loop||!1}setOperation(e){"pause"===e&&this.audio.pause(),"resume"===e&&(this.audio.pause(),this.audio.play()),"stop"===e&&(this.audio.pause(),this.seek(0))}listenDeviceChange(){}},EM="input",SM="output",IM={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};var vM=e=>(e=Number(e))>0&&e<14e8;function yM(e){return ab(this,arguments,(function(e){let{sdkAppId:t,userId:i,userSig:n,timestamp:r}=e;return function*(){let e="https://".concat(function(e){let t;return t=vM(e)?IM.MAIN_OVERSEA:IM.MAIN,t}(t),"/api/v1/audioAiAuth?sdkAppId=").concat(t,"&userId=").concat(i,"&userSig=").concat(n,"×tamp=").concat(r),o=yield fetch(e),{data:{errCode:s,errMsg:a,sign:c,status:l}}=yield o.json();if("1"===l)return{auth:!0,sign:c,status:l,message:a};let d="Init RTCAIDenoiser failed.",u="";switch(s){case 1:u="Please check your params.";break;case 2:u="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:u="Server is invalid. Please contact our engineer. ";break;case 4:u="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:u="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:u="Your version is not supported."}return{auth:!1,status:l,message:a?"".concat(d," Reason: ").concat(a,". ").concat(u):"".concat(d,", ").concat(u)}}()}))}var AM=nb(cb(),1);function RM(e,t){t=t||{};let i,n=e.numberOfChannels,{sampleRate:r}=e,o=t.float32?3:1,s=3===o?32:16;return i=2===n?function(e,t){let i=e.length+t.length,n=new Float32Array(i),r=0,o=0;for(;r<i;)n[r++]=e[o],n[r++]=t[o],o++;return n}(e.getChannelData(0),e.getChannelData(1)):e.getChannelData(0),function(e,t,i,n,r){let o=r/8,s=n*o,a=new ArrayBuffer(44+e.length*o),c=new DataView(a);return CM(c,0,"RIFF"),c.setUint32(4,36+e.length*o,!0),CM(c,8,"WAVE"),CM(c,12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,t,!0),c.setUint16(22,n,!0),c.setUint32(24,i,!0),c.setUint32(28,i*s,!0),c.setUint16(32,s,!0),c.setUint16(34,r,!0),CM(c,36,"data"),c.setUint32(40,e.length*o,!0),1===t?function(e,t,i){for(let n=0;n<i.length;n++,t+=2){let r=Math.max(-1,Math.min(1,i[n]));e.setInt16(t,r<0?32768*r:32767*r,!0)}}(c,44,e):function(e,t,i){for(let n=0;n<i.length;n++,t+=4)e.setFloat32(t,i[n],!0)}(c,44,e),a}(i,o,r,n,s)}function CM(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}var bM,kM=class{constructor(e){ob(this,"audioContext_"),ob(this,"inputPCM_",new Float32Array),ob(this,"outputPCM_",new Float32Array),this.audioContext_=e}onDump(e,t){if(t===EM){let t=this.inputPCM_.length,i=new Float32Array(t+e[0].length);i.set(this.inputPCM_),i.set(e[0],t),this.inputPCM_=i}if(t===SM){let t=this.outputPCM_.length,i=new Float32Array(t+e[0].length);i.set(this.outputPCM_),i.set(e[0],t),this.outputPCM_=i}}getBlob(e){let t=e===EM?this.inputPCM_:this.outputPCM_,i=this.audioContext_.createBuffer(2,t.length,48e3);i.copyToChannel(t,0,0),i.copyToChannel(t,1,0);let n=RM(i);return i=null,new window.Blob([new DataView(n)],{type:"audio/wav"})}reset(){this.inputPCM_=new Float32Array,this.outputPCM_=new Float32Array}destroy(){this.reset()}},DM=class{constructor(e){let{sdkAppId:t,userId:i,audioContext:n,sign:r,status:o,worklet:s,timestamp:a,logger:c}=e;ob(this,"audioContext_"),ob(this,"destination_"),ob(this,"gainNode_"),ob(this,"log_"),ob(this,"workletNode_"),ob(this,"isDumping_",!1),ob(this,"dump_"),ob(this,"audioTrack_"),ob(this,"source_"),ob(this,"denoiserTrack_"),ob(this,"enableDenoise_",!0),ob(this,"emitter_",new AM.default),this.audioContext_=n,this.destination_=this.audioContext_.createMediaStreamDestination(),this.gainNode_=this.audioContext_.createGain(),this.gainNode_.gain.value=1.1,this.log_=c,this.workletNode_=s,this.workletNode_.connect(this.gainNode_).connect(this.destination_),this.workletNode_.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:i,timestamp:a,sign:r,status:o}}),this.workletNode_.port.onmessage=e=>{let{type:t,data:i}=e.data;if("ondump"===t&&this.isDumping_){let{inputPCM:e,outputPCM:t}=i;this.dump_.onDump(e,EM),this.dump_.onDump(t,SM)}"dumped"===t&&this.dumped()},this.dump_=new kM(this.audioContext_)}dumped(){this.isDumping_=!1;let e=this.dump_.getBlob(EM),t=this.dump_.getBlob(SM);this.emitter_.emit("ondumpend",{blob:e,name:EM}),this.emitter_.emit("ondumpend",{blob:t,name:SM}),this.dumpedWAV(e,EM),this.dumpedWAV(t,SM),this.dump_.reset()}dumpedWAV(e,t){let i=window.URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download="".concat(t,"-").concat(Date.now(),".wav"),n.click(),window.URL.revokeObjectURL(i),n.href=""}process(e){return ab(this,null,(function*(){if(this.audioTrack_=e,!this.audioTrack_)throw new Error("RTCAIDenoiser: cannot process without audioTrack.");let t=new MediaStream;t.addTrack(this.audioTrack_),this.source_=this.audioContext_.createMediaStreamSource(t),yield this.source_.connect(this.workletNode_),yield this.enableTrackANS(this.audioTrack_,!1);let i=this.destination_.stream;return this.denoiserTrack_=i.getAudioTracks()[0],this.log_.info("RTCAIDenoiser: denoiser process track ID: ".concat(e.id," success.")),this.denoiserTrack_}))}updateTrack(e){return ab(this,null,(function*(){var t;let i=new MediaStream;yield i.addTrack(e);let n=this.audioContext_.createMediaStreamSource(i);this.source_.disconnect(),n.connect(this.workletNode_),null==(t=this.audioTrack_)||t.stop(),this.audioTrack_=e,this.source_=n,this.log_.info("RTCAIDenoiser: updateTrack success.")}))}disable(){return ab(this,null,(function*(){var e;return this.enableDenoise_=!1,null==(e=this.workletNode_)||e.port.postMessage({type:"disable"}),this.audioTrack_&&(yield this.enableTrackANS(this.audioTrack_,!0)),this.log_.info("RTCAIDenoiser: disable ai denoiser."),this.enableDenoise_}))}enable(){return ab(this,null,(function*(){var e;return this.enableDenoise_=!0,null==(e=this.workletNode_)||e.port.postMessage({type:"enable"}),this.audioTrack_&&(yield this.enableTrackANS(this.audioTrack_,!1)),this.log_.info("RTCAIDenoiser: enable ai denoiser."),this.enableDenoise_}))}enableTrackANS(e,t){let i=e.getConstraints();return i.noiseSuppression=t,e.applyConstraints(i).catch((e=>this.log_.warn("".concat(t?"enable":"disable"," ANS failed "),e)))}startDump(){return this.isDumping_?(this.log_.info("RTCAIDenoiser: data is currently being dumped."),!1):(this.workletNode_.port.postMessage({type:"startDump"}),this.dump_?this.dump_.reset():this.dump_=new kM(this.audioContext_),this.isDumping_=!0,this.log_.info("RTCAIDenoiser: start dump data."),!0)}stopDump(){!this.isDumping_||(this.workletNode_.port.postMessage({type:"stopDump"}),this.isDumping_=!1,this.log_.info("RTCAIDenoiser: stop dump data."))}getAudioTrack(){return this.audioTrack_}getDenoiserTrack(){return this.destination_.stream.getAudioTracks()[0]}get enabled(){return this.enableDenoise_}destroy(){var e,t,i,n,r,o;this.log_.info("RTCAIDenoiser: destroy processor."),null==(e=this.audioTrack_)||e.stop(),null==(t=this.workletNode_)||t.port.postMessage({type:"destroy"}),this.workletNode_.port.onmessage=null,null==(i=this.source_)||i.disconnect(),null==(n=this.destination_)||n.disconnect(),null==(r=this.workletNode_)||r.disconnect(),null==(o=this.dump_)||o.destroy(),this.emitter_.removeAllListeners()}on(e,t,i){this.emitter_.on(e,t,i)}off(e,t,i){"*"===e?this.emitter_.removeAllListeners():this.emitter_.off(e,t,i)}},NM=class{constructor(e){let{assetsPath:t,log:i,audioContext:n}=e;this.isLoaded_=!1,this.audioContext_=n,this.log_=i,this.assetsPath_=t}createProcessor(e){return ab(this,null,(function*(){let t=String(Date.now()).slice(0,-3),{auth:i,sign:n,status:r,message:o}=yield yM(eb(ZC({},e),{timestamp:t}));if(!i)throw this.log_.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(i,". Message: ").concat(o)),new Error(o);try{yield this.load()}catch(c){throw new Error("Init wasm failed, please check your assetsPath.")}let s=yield this.initWorklet(),a=new DM(eb(ZC({},e),{audioContext:this.audioContext_,timestamp:t,sign:n,status:r,worklet:s,logger:this.log_}));return this.log_.info("RTCAIDenoiser: ".concat(e.userId," create denoiser processor success.")),a}))}load(){return ab(this,null,(function*(){if(!this.isLoaded_)try{yield this.audioContext_.audioWorklet.addModule("".concat(this.assetsPath_,"/denoiser-wasm.js")),this.isLoaded_=!0}catch(QM){throw this.log_.error("Init assets from ".concat(this.assetsPath_," failed! Reason: ").concat(QM)),QM}}))}initWorklet(){return ab(this,null,(function*(){try{return new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}catch(QM){return yield this.load(),new AudioWorkletNode(this.audioContext_,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1})}}))}destroy(){var e;null==(e=this.audioContext_)||e.close()}isSupported(){return"AudioWorklet"in window&&"WebAssembly"in window}};var OM=class{constructor(e){let{room:t}=e;ob(this,"_localAudioTrack",null),ob(this,"_localScreenAudioTrack",null),ob(this,"localMixAudioTrack"),ob(this,"isDenoiserInit",!1),ob(this,"isDenoiserEnabled",!1),ob(this,"isDenoiserProcessed",!1),ob(this,"mixedMusicMap",new Map),ob(this,"cacheMusicMap",new Map),ob(this,"_log"),ob(this,"denoiserTrack",null),ob(this,"denoiser",null),ob(this,"denoiserProcessor"),ob(this,"initProcessorOptions"),ob(this,"denoiserContext"),this._log=GO.createLogger({id:"am",userId:t.userId,sdkAppId:t.sdkAppId})}get mixedAudioTrack(){var e,t,i,n,r,o;if(kw&&(this._localAudioTrack||this.localMixAudioTrack)){let s=null==(t=null==(e=this._localAudioTrack)?void 0:e.mediaTrack)?void 0:t.getSettings(),a=null==(n=null==(i=this._localAudioTrack)?void 0:i.outMediaTrack)?void 0:n.getSettings(),c=null==(o=null==(r=this.localMixAudioTrack)?void 0:r.outMediaTrack)?void 0:o.getSettings();this._log.info("local audio track input sampleRate: ".concat(null==s?void 0:s.sampleRate," output sampleRate: ").concat(null==a?void 0:a.sampleRate," audio mixer sampleRate: ").concat(null==c?void 0:c.sampleRate))}return this.localMixAudioTrack?this.localMixAudioTrack.outMediaTrack:null}dump(e){var t,i,n,r,o,s;if(!this._localAudioTrack)return;let a=[],c=[];null!=(t=this._localAudioTrack)&&t.mediaTrack&&(a.push(null==(i=this._localAudioTrack)?void 0:i.mediaTrack),c.push("mic")),null!=(n=this._localAudioTrack)&&n.outMediaTrack&&(a.push(null==(r=this._localAudioTrack)?void 0:r.outMediaTrack),c.push("mic-processed")),null!=(o=this.localMixAudioTrack)&&o.outMediaTrack&&(a.push(this.localMixAudioTrack.outMediaTrack),c.push("mix")),this._log.info("dump audio track ".concat(c,", duration: ").concat(e));let l=new AbortController,d=[],u=setTimeout((()=>{this._log.info('dump audio track complete please input "download()" to download.'),l.abort("timeout")}),1e3*e),h=()=>{for(let e=0;e<c.length;e++){let t=URL.createObjectURL(new Blob(d[e])),i=document.createElement("a");i.href=t,i.download="".concat(c[e],".pcm"),i.style.display="none",document.body.appendChild(i),i.click(),URL.revokeObjectURL(t),i.remove()}clearTimeout(u),l.abort("download")},p=function(e,t){return ab(this,null,(function*(){bM||(bM=e.audioWorklet.addModule(URL.createObjectURL(new Blob(["registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});"],{type:"application/javascript"})))),yield bM;let i=new AudioWorkletNode(e,"dumper",{numberOfInputs:t.length,numberOfOutputs:0}),n=t.map((t=>e.createMediaStreamSource(new MediaStream([t.clone()]))));return t.forEach(((e,t)=>{n[t].connect(i,0,t)})),new ReadableStream({start(e){i.port.onmessage=t=>{e.enqueue(t.data)}},cancel(){n.forEach((e=>e.disconnect())),i.port.close()}})}))}((null==(s=this.localMixAudioTrack)?void 0:s.audioContext)||OP("dump"),a).then((e=>e.pipeTo(new WritableStream({write(e){e.forEach(((e,t)=>d[t]=d[t]?d[t].concat(e[0]):[e[0]]))}}),l).catch((e=>h))));return{then:p.then.bind(p),download:h}}get hasScreenAudioTrack(){return null!==this._localScreenAudioTrack}get hasAudioTrack(){return null!==this._localAudioTrack}changeInput(e){var t,i,n,r;if(e instanceof fM)return this._localScreenAudioTrack=e,e.setOutputMediaStreamTrack(e.mediaTrack);let o=e.outMediaTrack||void 0;return e instanceof TM?(e.setOutputMediaStreamTrack(e.mediaTrack),void(o?null==(t=this.localMixAudioTrack)||t.replaceTrack(e,o):null==(i=this.localMixAudioTrack)||i.addTrack(e.outMediaTrack))):e instanceof hM?(this._localAudioTrack=e,void(this.isDenoiserProcessed?(null==(n=this.denoiserProcessor)||n.updateTrack(e.mediaTrack),e.setOutputMediaStreamTrack(this.denoiserTrack)):(e.setOutputMediaStreamTrack(e.mediaTrack),null==(r=this.localMixAudioTrack)||r.replaceTrack(e,o)))):e instanceof MM?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){if(e instanceof hM)return this.removeAudioTrack(e)}addMusicSource(e){return ab(this,null,(function*(){var t;this._log.info("add music source, id: ".concat(e.id," url: ").concat(e.url));let i,{id:n,url:r,loop:o,volume:s}=e;if(!this.mixedMusicMap.has(n))return this.cacheMusicMap.has(n)?(i=this.cacheMusicMap.get(n),i.audio.currentTime=0,null==(t=this.localMixAudioTrack)||t.addTrack(i.outMediaTrack)):i=new TM(this,e),i.play(),this._log.info("start mix audio ".concat(n," success.")),this.mixedMusicMap.set(n,i),this.cacheMusicMap.set(n,i),i}))}updateMusicSource(e){return ab(this,null,(function*(){let{id:t,volume:i,loop:n,operation:r,seekFrom:o}=e;if(this._log.info("update music source, ".concat(JSON.stringify(e))),this.mixedMusicMap.has(t)){let e=this.mixedMusicMap.get(t);nO(i)||e.setVolume(i),nO(n)||e.loop(n),nO(r)||e.setOperation(r),nO(o)||e.seek(o)}}))}addAudioTrack(e){return ab(this,null,(function*(){var t;if(this.localMixAudioTrack||(this.localMixAudioTrack=new gM(this)),this._log.info("start add audioTrack, userId: ".concat(e.userId)),e===this._localAudioTrack){if(kw){let i=null==(t=e.mediaTrack)?void 0:t.getSettings();this.localMixAudioTrack.channelCount=(null==i?void 0:i.channelCount)||1}this.mixedMusicMap.forEach((e=>{var t;null==(t=this.localMixAudioTrack)||t.addTrack(e.outMediaTrack)}))}this.localMixAudioTrack.addTrack(e.outMediaTrack,jk.startsWith("14.5")),this._localAudioTrack&&1!==this._localAudioTrack.captureVolume&&this.setCaptureVolume(this._localAudioTrack.captureVolume)}))}removeAudioTrack(e){e===this._localAudioTrack&&this.localMixAudioTrack&&this.mixedMusicMap.forEach((e=>{this.localMixAudioTrack.removeTrack(e.outMediaTrack)})),this.localMixAudioTrack&&(this.localMixAudioTrack.removeTrack(e.outMediaTrack),this.localMixAudioTrack.hasMix||delete this.localMixAudioTrack)}removeMusicSource(e){let{id:t}=e;if(this.mixedMusicMap.has(t)){this._log.info("remove music source, music id: ".concat(t));let e=this.mixedMusicMap.get(t);e.stop(),this.mixedMusicMap.delete(t),this.localMixAudioTrack&&this.localMixAudioTrack.removeTrack(e.outMediaTrack)}"*"===t&&this.destroyAllMusic()}destroyAllMusic(){this._log.info("destroy all music source."),this.mixedMusicMap.forEach(((e,t)=>{this.removeMusicSource({id:t})}))}destroyAllCache(){this._log.info("destroy all music cache."),this.cacheMusicMap.forEach((e=>e.stop()))}initDenoiser(e){return ab(this,null,(function*(){let{assetsPath:t,sdkAppId:i,userId:n,userSig:r}=e;try{(!this.denoiserContext||"closed"===this.denoiserContext.state)&&(this.denoiserContext=OP("denoiser")),this.denoiser||(this.denoiser=new NM({assetsPath:t,log:this._log,audioContext:this.denoiserContext})),this.denoiserProcessor||(this.denoiserProcessor=yield this.denoiser.createProcessor({sdkAppId:i,userId:n,userSig:r})),this.isDenoiserInit=!0,this.initProcessorOptions=e}catch(cD){throw cD}}))}enableDenoiser(e){return ab(this,null,(function*(){var e,t,i,n;if(this.isDenoiserEnabled=!0,this.hasAudioTrack)if(this.isDenoiserProcessed)null==(n=this.denoiserProcessor)||n.enable();else{let n=null==(e=this._localAudioTrack)?void 0:e.mediaTrack;if(!n)return;this.denoiserProcessor||(yield this.initDenoiser(this.initProcessorOptions)),this.denoiserTrack=yield this.denoiserProcessor.process(n),this.isDenoiserProcessed=!0,null==(t=this._localAudioTrack)||t.setOutputMediaStreamTrack(this.denoiserTrack),null==(i=this.localMixAudioTrack)||i.replaceTrack(this._localAudioTrack,n)}}))}disableDenoiser(){return ab(this,null,(function*(){var e;this.isDenoiserEnabled&&(null==(e=this.denoiserProcessor)||e.disable(),this.isDenoiserEnabled=!1)}))}setCaptureVolume(e){var t;this.localMixAudioTrack&&this._localAudioTrack&&this._localAudioTrack.outMediaTrack&&(null==(t=this.localMixAudioTrack)||t.setTrackCaptureVolume(this._localAudioTrack.outMediaTrack,e))}destroyDenoiserProcessor(){var e;this.denoiserProcessor&&(this.denoiserProcessor.destroy(),delete this.denoiserProcessor,this.isDenoiserInit=!1,this.isDenoiserEnabled=!1,this.isDenoiserProcessed=!1,null==(e=this.denoiserTrack)||e.stop(),this.denoiserTrack=null),this.denoiserContext&&(this.denoiserContext.close(),delete this.denoiserContext)}destroy(){var e;this.destroyAllMusic(),this.destroyAllCache(),this.destroyDenoiserProcessor(),null==(e=this.denoiser)||e.destroy(),this.localMixAudioTrack&&(this.localMixAudioTrack.close(),delete this.localMixAudioTrack)}},wM=class extends VP{constructor(e,t,i){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:i,room:e}),this.room=e,this.user=t,ob(this,"tinyId"),ob(this,"isRemote",!0),this.tinyId=t.tinyId}setMute(e){return 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===wM.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)}},PM=wM;ob(PM,"STATE_SUBSCRIBE","subscribe"),rb([jw(Jw.INIT,PM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),FO.emit(HO.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],PM.prototype,"subscribe",1),rb([jw(PM.STATE_SUBSCRIBE,Jw.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),FO.emit(HO.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],PM.prototype,"unsubscribe",1);var MM=class extends PM{constructor(e,t){super(e,t,1),ob(this,"volume",0),ob(this,"mediaType",1),ob(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}},LM=class extends PM{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4),ob(this,"mediaType",4),ob(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.videoManager}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}},xM=class extends LM{constructor(e,t){super(e,t,2),ob(this,"mediaType",2),ob(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function VM(){}var UM=e=>e(),FM=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,BM=1,HM=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new KM(e,this,this.streamId++);return YM.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},jM=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=VM,this.error=VM,this.next=VM,this.dispose=VM,this.subscribe=VM,this.doDefer()}subscribe(e){return e instanceof HM?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(UM),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}},GM=class extends jM{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 WM(e,t,i){if(FM()){let n=Object.defineProperties(Object.setPrototypeOf(e,HM.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}});YM.create(n);for(let e=0;e<i.length;e++){let t=i[e];"function"==typeof t&&t instanceof HM&&YM.addSource(n,t)}return n}return e}function JM(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var KM=class extends GM{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{YM.defer(this.source,this.id)}))}next(e){YM.next(this.source,this.id,e),this.sink.next(e)}complete(){YM.complete(this.source,this.id),this.sink.complete()}error(e){YM.complete(this.source,this.id,e),this.sink.error(e)}},YM={addSource(e,t){JM("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){JM("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:n}=e;JM("subscribe",{id:i,end:n,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){JM("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){JM("defer",{id:e.id,streamId:t})},pipe(e){JM("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){JM("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=BM++),JM("create",{name:e.toString(),id:e.id})}},zM=class extends jM{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 qM,QM,XM=(qM=class extends GM{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},QM="map",function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return e=>{if(e instanceof HM){let i=WM((n=>{let r=new qM(n,...t);r.sourceId=i.id,r.subscribe(e)}),QM,arguments);return i.source=e,YM.pipe(i),i}return i=>e(new qM(i,...t))}});!function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];i.reduce(((e,t)=>t(e)),e)}(function(e){return WM((t=>{let i=0,n=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(n)})),"interval"}),"interval",arguments)}(250),XM((()=>performance.now())),function(){return e=>{let t=new zM(e);if(e instanceof HM){let i=WM((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,YM.pipe(i),i}return WM(t.add.bind(t),"share",arguments)}}());var $M=new Map;function ZM(e,t){let i=eb(ZC({},t),{timestamp:Eb()});$M.has(e)?$M.get(e).push(i):$M.set(e,[i])}FO.on(HO.JOIN_SUCCESS,(e=>{let{room:t}=e;ZM(t.userId,{eventId:32788,eventDesc:"join room"})})),FO.on(HO.LEAVE_START,(e=>{let{room:t}=e;ZM(t.userId,{eventId:32789,eventDesc:"leave room"})})),FO.on(HO.LOCAL_TRACK_PUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32769;4===t.mediaType?e=32768:2===t.mediaType&&(e=32805),ZM(t.room.userId,{eventId:e,eventDesc:"publish ".concat(t.kind)})}})),FO.on(HO.LOCAL_TRACK_UNPUBLISHED,(e=>{let{track:t}=e;if(t.room){let e=32771;4===t.mediaType?e=32770:2===t.mediaType&&(e=32806),ZM(t.room.userId,{eventId:e,eventDesc:"unpublish ".concat(t.kind)})}})),FO.on(HO.TRACK_MUTED,(e=>{let{track:t}=e;t.room&&(t.kind===MD.AUDIO?ZM(t.room.userId,{eventId:t.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:t.isRemote?t.userId:void 0}):ZM(t.room.userId,{eventId:t.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:t.isRemote?t.userId:void 0}))})),FO.on(HO.TRACK_UNMUTED,(e=>{let{track:t}=e;t.room&&(t.kind===MD.AUDIO?ZM(t.room.userId,{eventId:t.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:t.isRemote?t.userId:void 0}):ZM(t.room.userId,{eventId:t.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:t.isRemote?t.userId:void 0}))})),FO.on(HO.REMOTE_TRACK_SUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&ZM(t.room.userId,{eventId:32777,eventDesc:"".concat(MD.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&ZM(t.room.userId,{eventId:32776,eventDesc:"".concat(MD.SUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&ZM(t.room.userId,{eventId:32803,eventDesc:"".concat(MD.SUBSCRIBE," ").concat(MD.SMALL_VIDEO),remoteUserId:t.userId}))})),FO.on(HO.REMOTE_TRACK_UNSUBSCRIBED,(e=>{let{track:t}=e;!t.room||(1===t.mediaType&&ZM(t.room.userId,{eventId:32779,eventDesc:"".concat(MD.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),4===t.mediaType&&ZM(t.room.userId,{eventId:32778,eventDesc:"".concat(MD.UNSUBSCRIBE," ").concat(t.kind),remoteUserId:t.userId}),8===t.mediaType&&ZM(t.room.userId,{eventId:32804,eventDesc:"".concat(MD.UNSUBSCRIBE," ").concat(MD.SMALL_VIDEO),remoteUserId:t.userId}))})),FO.on(HO.SWITCH_DEVICE_SUCCESS,(e=>{let{track:t}=e;t.room&&ZM(t.room.userId,{eventId:t.kind===MD.VIDEO?32780:32781,eventDesc:"switch ".concat(t.kind===MD.VIDEO?"camera":"microphone")})})),FO.on(HO.LOCAL_TRACK_REPLACED,(e=>{let{track:t}=e;t.room&&ZM(t.room.userId,{eventId:t.kind===MD.VIDEO?32782:32783,eventDesc:"replace ".concat(t.kind)})})),FO.on(HO.SIGNAL_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o}=e;switch(o){case"CONNECTED":"RECONNECTING"===r?(t=32795,i="signal reconnected"):(t=32791,i="signal connected");break;case"DISCONNECTED":"RECONNECTING"===r?(t=32796,i="signal reconnect fail"):(t=32790,i="signal disconnected");break;case"RECONNECTING":t=32794,i="signal reconnecting"}t&&i&&ZM(n.userId,{eventId:t,eventDesc:i})})),FO.on(HO.PEER_CONNECTION_STATE_CHANGED,(e=>{let t,i,{room:n,prevState:r,state:o,remoteUserId:s}=e,a=!!s,c=a?"downlink":"uplink";switch(o){case"CONNECTED":"RECONNECTING"===r?(t=a?32801:32798,i="".concat(c," reconnected")):(t=a?32793:32792,i="".concat(c," connected"));break;case"DISCONNECTED":"RECONNECTING"===r&&(t=a?32802:32799,i="".concat(c," reconnect fail"));break;case"RECONNECTING":t=a?32800:32797,i="".concat(c," reconnecting")}t&&i&&ZM(n.userId,{eventId:t,eventDesc:i,remoteUserId:s})}));var eL=nb(cb(),1),tL=class extends eL.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,ob(this,"userMap",new Map),ob(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:n,role:r}=e;if(this.userMap.has(t))return;let o={userId:i,tinyId:n,role:20===r?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;let n="peer leave [".concat(e,"]");nO(t)||(n+=":".concat(DN[t])),this._log.info(n);let r=this.remotePublishedUserMap.get(e);if(r){let t=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:t,muteState:r.muteState,flag:0})}this.userMap.delete(e),this.emit("2",i.userId)}setUserList(e){this.userMap.forEach((t=>{e.findIndex((e=>e[this.key]===t[this.key]))<0&&this.deleteUser(t[this.key],0)})),e.forEach((e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)}))}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach((t=>{let i=t[this.key];if(e.findIndex((e=>e[this.key]===t[this.key]))<0){this._log.info("remote [".concat(i,"] unpublish"));let e=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:e,muteState:t.muteState,flag:0})}})),e.forEach((e=>{var t;let i=e[this.key];if(i===this.mySelfId)return;let{flag:n,userId:r,tinyId:o}=e,s=IO(n,r),a=null==(t=this.remotePublishedUserMap.get(i))?void 0:t.muteState;if(a){let e=this.remotePublishedUserMap.get(i);e&&e.flag!==n&&(e.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(e.muteState))),this.emit("6",{prevMuteState:a,muteState:s,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(s))),this.addUser({userId:r,tinyId:o,role:20}),this.emit("3",e),this.emit("6",{prevMuteState:IO(0,r),muteState:s,flag:n})}))}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var iL,nL=!0,rL={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"},oL={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},sL=((iL=sL||{})[iL.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",iL[iL.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",iL[iL.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",iL[iL.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",iL[iL.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",iL[iL.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",iL[iL.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",iL[iL.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",iL[iL.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",iL[iL.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",iL[iL.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",iL[iL.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",iL[iL.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",iL[iL.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",iL[iL.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",iL[iL.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",iL[iL.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",iL[iL.INVALID_OPERATION=5100]="INVALID_OPERATION",iL[iL.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",iL[iL.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",iL[iL.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",iL[iL.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",iL[iL.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",iL[iL.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",iL[iL.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",iL[iL.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",iL[iL.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",iL[iL.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",iL[iL.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",iL[iL.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",iL[iL.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",iL[iL.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",iL[iL.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",iL[iL.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",iL[iL.DEVICE_ERROR=5300]="DEVICE_ERROR",iL[iL.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",iL[iL.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",iL[iL.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",iL[iL.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",iL[iL.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",iL[iL.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",iL[iL.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",iL[iL.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",iL[iL.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",iL[iL.SERVER_ERROR=5400]="SERVER_ERROR",iL[iL.NEED_TO_BUY=5401]="NEED_TO_BUY",iL[iL.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",iL[iL.OPERATION_FAILED=5500]="OPERATION_FAILED",iL[iL.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",iL[iL.REJOIN_FAILED=5502]="REJOIN_FAILED",iL[iL.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",iL[iL.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",iL[iL.OPERATION_ABORT=5998]="OPERATION_ABORT",iL[iL.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",iL);var aL=eb(ZC({},zO),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="";return s=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(o,"' must be type of ").concat(s," when calling ").concat(n,"(), received type: ").concat(tO(r),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' cannot be '").concat(r,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:n,value:r}=e,o="".concat(t||i.name),s="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(o,"' must be instanceof ").concat(s," when calling ").concat(n,"(), received type: ").concat(tO(r),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:n,value:r}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:n}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(n,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone is not turned on.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=cL(t),error:n}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(null==i?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((null==i?void 0:i.name)||""," ").concat((null==i?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(null==i?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function cL(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var lL=class extends Error{constructor(e){let{code:t,extraCode:i,message:n="",messageParams:r,fnName:o="",originError:s}=e;var a;let c;c=n||function(e){let t,{code:i,params:n,enableDocLink:r=!1}=e,s="",a=sL[i];try{t=aL[a]}catch(o){t=aL.UNKNOWN_ERROR}return iO(t)?s=t(n):rO(t)&&(s=t),r&&(s+=" doc:"),s}({code:i||t,params:ZC({fnName:o,error:s},r)}),super(c),ob(this,"name","RtcError"),ob(this,"code"),ob(this,"extraCode"),ob(this,"functionName"),ob(this,"message"),ob(this,"handler"),ob(this,"originError"),this.name=sL[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");mk?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):_k&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),e.href.length>0&&e.click()})}static convertFrom(e,t,i){let n=e;if(e instanceof gb){let{stack:r}=e,o={code:oL.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case _b.INVALID_PARAMETER:o.code=oL.INVALID_PARAMETER;break;case _b.INVALID_OPERATION:o.code=oL.INVALID_OPERATION;break;case _b.NOT_SUPPORTED:case _b.NOT_SUPPORTED_H264:o.code=oL.ENV_NOT_SUPPORTED,e.getCode()===_b.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(zO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case _b.DEVICE_NOT_FOUND:case _b.DEVICE_AUTO_RECOVER_FAILED:o.code=oL.DEVICE_ERROR;break;case _b.JOIN_ROOM_FAILED:o.messageParams={fnParams:i};case _b.SERVER_TIMEOUT:case _b.SWITCH_ROLE_FAILED:o.code=oL.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case _b.API_CALL_ABORTED:o.code=oL.OPERATION_ABORT;break;case _b.INITIALIZE_FAILED:o.code=5300,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 _b.UNKNOWN:break;default:o.code=oL.OPERATION_FAILED}n=new lL(o),r&&(n.stack+=r.substr(r.indexOf("\n")))}else{if(e instanceof lL)return e;n=new lL({code:oL.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};var dL=lL,uL={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}}},hL={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}}},pL={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(rO(e)){let n=document.getElementById(e);if(!n)throw new dL({code:oL.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}});if(!(n instanceof HTMLElement))throw new dL({code:oL.INVALID_PARAMETER,extraCode:5010,fnName:i,messageParams:{key:t,type:tO(n)}})}}},mL={name:"userId",required:!0,type:"string"},_L={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function fL(e,t){if(!e)throw new dL({code:oL.INVALID_OPERATION,extraCode:5101,fnName:t})}function gL(e,t,i){if(!e)throw new dL({code:oL.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}var TL={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 dL({code:oL.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(rO(e.roomId))throw new dL({code:oL.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(e.roomId))&&e.roomId<4294967295))throw new dL({code:oL.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:t}})}else{if(!e.strRoomId)throw new dL({code:oL.INVALID_PARAMETER,extraCode:5015,fnName:i});if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e.strRoomId))throw new dL({code:oL.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:t}})}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:pL,publish:{type:"boolean"},option:uL},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&ow())throw new dL({code:oL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:eb(ZC({},pL),{required:!1}),publish:{type:"boolean"},mute:{type:"boolean"},option:uL}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:_L},validate(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&ow())throw new dL({code:oL.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:_L}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:pL,publish:{type:"boolean"},option:hL},validate(e,t,i,n,r){var o;if((null==(o=null==e?void 0:e.option)||!o.videoTrack)&&ow())throw new dL({code:oL.ENV_NOT_SUPPORTED,extraCode:5201});if(!uw())throw new dL({code:oL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:pL,publish:{type:"boolean"},option:hL}},muteRemoteAudio:[mL,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[mL,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:pL,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){fL(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(gL(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new dL({code:oL.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:eb(ZC({},pL),{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){fL(this._room.isJoined,i);let n=this._room.remotePublishedUserMap.get(e.userId);if(gL(!!n,i,e),n&&("main"===e.streamType&&!n.muteState.videoAvailable||"sub"===e.streamType&&!n.muteState.hasAuxiliary))throw new dL({code:oL.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&&nO(e.streamType))throw new dL({code:oL.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){fL(this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,n){if(!Nw)throw new dL({code:oL.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new dL({code:oL.INVALID_OPERATION,messageParams:{key:YO.SEI_DISABLED}});if(e.byteLength>1e3)throw new dL({code:oL.INVALID_PARAMETER,messageParams:{key:YO.SEI_OVERSIZE,data:e.byteLength}});if(0===e.byteLength)throw new dL({code:oL.INVALID_PARAMETER,messageParams:{key:YO.SEI_EMPTY}});if(fL(this._room.isJoined,i),!this._room.isMainStreamPublished)throw new dL({code:oL.INVALID_PARAMETER,messageParams:{key:YO.SEI_BEFORE_PUBLISH}})}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]}}}]},EL={TRTC:TL},SL=class extends Error{};function IL(e,t){let i=CO(e);for(let n=0;n<t.length;n++)RO(i[n],t[n]);return i}function vL(e){this._resolve=Promise.resolve(e)}function yL(e){this._reject=Promise.reject(e)}var AL=class{constructor(e,t){this.instance=e,this.group=t,this.started=!1,this.ops=[],this.startSame=()=>!0,this.mergeUpdate=IL;let i=AL.instances.get(e);i?i.set(t,this):AL.instances.set(e,new Map([[t,this]]))}static get(e,t){let i=AL.instances.get(e);return i&&i.get(t)||new AL(e,t)}action(e,t,i){let n=t=>{var i;return 0===e?this.started=!0:3===e&&(this.started=!1),this.ops.shift(),null==(i=this.currentOp)||i.action(),t},r=t=>{var i,n;throw this.ops.shift(),0===e&&2===(null==(i=this.currentOp)?void 0:i.type)&&this.ops.shift().reject(new SL("start failed")),null==(n=this.currentOp)||n.action(),t},o={type:e,action:()=>t(...o.args).then(n,r),args:i,resolve:vL,reject:yL};try{switch(this.state){case 1:if(0===e)throw new SL("already started");break;case 4:if(2===e)throw new SL("not started");break;default:return this.cacheOp(o)}}catch(s){return Promise.reject(s)}return this.ops.push(o),o.promise=t(...o.args).then(n,r)}cacheOp(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new SL("already start");break;case 3:switch(e.type){case 2:throw new SL("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new SL("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;{let e=new SL("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 SL("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new SL("start not allowed after update");case 0:throw new SL("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new SL("keep start")),new SL("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}},RL=AL;RL.instances=new WeakMap;var CL=new WeakMap,bL=(e,t)=>{if(t instanceof SL){let{stack:i}=t;t=new dL({code:oL.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf("\n")))}throw t};function kL(e,t){return oM(((i,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];let a=RL.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(bL.bind(null,n))}))}function DL(e,t){let{merge:i,debounce:n}=t||{};return oM(((t,r)=>function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];let c=RL.get(this,"string"==typeof e?e:e.call(this,...s));if(i&&(c.mergeUpdate=i.bind(this)),n&&n.isNeedToDebounce.apply(this,s)){let{delay:e,getKey:i}=n;return new Promise(((n,o)=>{var a,l;let d=null==(a=CL.get(this))?void 0:a.get(i(...s));if(d){let{timeoutId:e,resolve:t}=d;clearTimeout(e),t()}let u=setTimeout((()=>{if(3===c.state||4===c.state)return n();c.action(2,t.bind(this),s).catch(bL.bind(null,r)).then(n,o)}),e);CL.has(this)?null==(l=CL.get(this))||l.set(i(...s),{timeoutId:u,resolve:n}):CL.set(this,new Map([[i(...s),{timeoutId:u,resolve:n}]]))}))}return c.action(2,t.bind(this),s).catch(bL.bind(null,r))}))}function NL(e){return oM(((t,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return RL.get(this,"string"==typeof e?e:e.call(this,...r)).action(3,t.bind(this),r).catch(bL.bind(null,i))}))}var OL={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",TRACK:"track"};function wL(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function PL(e){return e===rL.QOS_PREFERENCE_CLEAR?"detail":e===rL.QOS_PREFERENCE_SMOOTH?"motion":""}function ML(e,t){return{room:e,innerEmitter:FO,constants:iD,environment:vb,utils:Ib,eventLogger:$w,log:e.getLogger(),errorModule:t,clearStarted(t,i){let n=t.getAlias(),r=RL.instances.get(e);if(r)if(i){let e=r.get(n+i);if(!e)return;e.started=!1}else r.forEach(((e,t)=>{t.startsWith(n)&&(e.started=!1)}))}}}var LL=new WeakMap;function xL(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return oM(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{UL.call(this,t,r,i,this._name)}catch(aD){return Promise.reject(aD)}return e.apply(this,r)}))}function VL(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return oM(((e,i)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];try{UL.call(this,t,r,i,this._name)}catch(aD){throw aD}return e.apply(this,r)}))}function UL(e,t,i,n){if(cO(e))for(let r=0;r<e.length;r++)FL.call(this,{rule:e[r],value:t[r],key:e[r].name,fnName:i,className:n});else FL.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:n})}function FL(e){let{rule:t,value:i,key:n,fnName:r,className:o}=e;function s(e){return{code:oL.INVALID_PARAMETER,extraCode:e,fnName:r,messageParams:{key:n,rule:t,value:i}}}if(nO(i)){if(t.required)throw new dL(s(5001));if(nO(t.defaultValue))return void(iO(t.validate)&&t.validate.call(this,i,n,r,o,this));i=t.defaultValue}if(Array.isArray(t.type)){let e=!1;for(let n=0;n<t.type.length;n++)null===t.type[n]&&null===i&&(e=!0),iO(t.type[n])&&i instanceof t.type[n]&&(e=!0),rO(t.type[n])&&tO(i)===t.type[n].toLowerCase()&&(e=!0);if(!e)throw new dL({code:oL.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:n,rule:{type:t.type.map((e=>hO(e)?pO(e):rO(e)?e:tO(e)))},value:i}})}else if(!nO(t.type)&&tO(i)!==t.type)throw new dL(s(5002));if(!1===t.allowEmpty){let e=oO(i)&&(0===i||Number.isNaN(i)),t=rO(i)&&""===i.trim();if(e||t)throw new dL(s(5003))}if(t.notLessThanZero&&oO(i)&&i<0)throw new dL(s(5006));if(!nO(t.min)&&oO(i)&&i<t.min)throw new dL(s(5007));if(!nO(t.max)&&oO(i)&&i>t.max)throw new dL(s(5008));if(rO(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new dL(s(5004))}else if(iO(t.instanceOf)&&!(i instanceof t.instanceOf))throw new dL(s(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new dL(s(5005));let{properties:a}=t;$N(a)&&aO(i)&&Object.keys(a).forEach((e=>{FL.call(this,{rule:a[e],value:i&&i[e],key:"".concat(e),fnName:r,className:o})}));let{arrayItem:c}=t;$N(c)&&cO(i)&&i.forEach(((e,t)=>{FL.call(this,{rule:c,value:e,key:"".concat(n,"[").concat(t,"]"),fnName:r,className:o})})),iO(t.validate)&&t.validate.call(this,i,n,r,o,this)}function BL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{namePrefix:t=(()=>""),getRemoteId:i=(()=>"")}=e;return oM(((e,n)=>function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];function a(e,t,i){if(i&&i.includes(e))return"hided";if(t===o||e in o)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(tO(t)):(JSON.stringify(t),t)}catch(n){return"type:".concat(tO(t))}}let c=this._log||GO,l=t.call(this,...o),d=""!==l?"".concat(l,".").concat(n):n;o.length>0?c.info("".concat(d,"() ").concat(JSON.stringify(o,((e,t)=>a(e,t,["userSig","privateMapKey"]))))):c.info("".concat(d,"()"));try{let t=e.apply(this,o),n=fO();return uO(t)?t.then((e=>(c.info("".concat(d,"() success ").concat(i.call(this,...o))),FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),e))).catch((e=>{throw e=dL.convertFrom.call(this,e,d,1===o.length?o[0]:o),c.error("".concat(d,"() failed ").concat(i.call(this,...o)," ").concat(e," params: ").concat(JSON.stringify(o,a))),FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:e}),e})):(FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:d,cost:fO()-n}),t)}catch(u){throw u=dL.convertFrom.call(this,u,d),c.error("".concat(d,"() failed ").concat(u," params: ").concat(JSON.stringify(o,a))),FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:d,error:u}),u}}))}var HL=e=>oM(((t,i)=>function(n,r){return ab(this,null,(function*(){let o=this._plugins.get(n);if(o)return UL.call(this,o.getValidateRule(e),[r],i,"TRTC"),t.call(this,o,r);this._log.warn("plugin ".concat(n," is not found"))}))})),jL=0,GL=class{constructor(e){this.core=e,ob(this,"log"),jL+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(jL)}),this.log.info("[audioMixer] created id=".concat(this.getAlias()).concat(jL)),this.core=e}getName(){return"AudioMixer"}getAlias(){return"ax"}getGroup(e){return null==e?void 0:e.id}getValidateRule(e){switch(e){case"start":return GL.startValidateRule;case"update":return GL.updateValidateRule;case"stop":return GL.stopValidateRule}}start(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.addMusicSource(e)}))}update(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.updateMusicSource(e)}))}stop(e){return ab(this,null,(function*(){let{room:t}=this.core;yield t.audioManager.removeMusicSource(e)}))}},WL=GL;ob(WL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if("*"!==e.url){let t=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],r=t.split(".").pop(),o=n.indexOf(r)>=0,s=t.startsWith("blob"),a=t.startsWith("data");if(!(o||s||a))throw new dL({code:oL.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}}}),ob(WL,"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"]}}}),ob(WL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}});var JL=0,KL=class{constructor(e){this.core=e,ob(this,"log"),JL+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(JL)}),this.log.info("[audioDenoiser] created id=".concat(this.getAlias()).concat(JL))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{assetsPath:{type:"string",required:!0},sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(t,i,n,r){if(!e.room.audioManager.hasAudioTrack)throw new dL({code:oL.INVALID_OPERATION,extraCode:5106,fnName:n})}}}getName(){return"AIDenoiser"}getAlias(){return"ad"}getGroup(e){return"AIDenoiser_".concat(Date.now())}getValidateRule(e){switch(e){case"start":return KL.startValidateRule(this.core);case"update":return KL.updateValidateRule;case"stop":return KL.stopValidateRule}}start(e){return ab(this,null,(function*(){let{room:t}=this.core,{assetsPath:i,sdkAppId:n,userId:r,userSig:o}=e;if(i&&!t.audioManager.isDenoiserInit)try{yield t.audioManager.initDenoiser({assetsPath:i,sdkAppId:n,userId:r,userSig:o})}catch(s){if(s.message)throw new dL({code:oL.INVALID_PARAMETER,message:s.message})}yield t.audioManager.enableDenoiser(e),t.sendAbilityStatus({ai_denoise:1})}))}update(e){return ab(this,null,(function*(){}))}stop(e){return ab(this,null,(function*(){let{room:e}=this.core;yield e.audioManager.disableDenoiser()}))}},YL=KL;ob(YL,"updateValidateRule",{type:"object"}),ob(YL,"stopValidateRule",{type:"object"});var zL=0,qL=new Set,QL=null;oD("5.3.2");var XL=class extends pb.EventEmitter{constructor(e,t){super(),ob(this,"_room"),ob(this,"_eventListened",new Set),ob(this,"_localVideoTrack",null),ob(this,"_localAudioTrack",null),ob(this,"_localScreenTrack",null),ob(this,"_localScreenAudioTrack",null),ob(this,"_localVideoConfig",null),ob(this,"_localScreenConfig",null),ob(this,"_localAudioConfig",null),ob(this,"_remoteVideoConfigMap",new Map),ob(this,"_remoteAudioConfigMap",new Map),ob(this,"_remoteAudioMuteMap",new Map),ob(this,"_mediaTrackMap",new WeakMap),ob(this,"_log",GO.createLogger({id:"t".concat(++zL)})),ob(this,"_plugins",new Map),ob(this,"_networkQuality",null),ob(this,"_speakerId"),this._room=new e(ZC({logger:this._log,frameWorkType:XL.frameWorkType},t)),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(e){return this._room.audioManager.dump(e)}}});let i={RtcError:dL,ErrorCode:oL,ErrorCodeDictionary:sL};t.plugins&&t.plugins.forEach((e=>{let t=new e(ML(this._room,i));this._plugins.set(t.getName(),t)}));let n=new WL(ML(this._room,i));this._plugins.set(n.getName(),n);let r=new YL(ML(this._room,i));this._plugins.set(r.getName(),r),this._room.on("audio-volume",(e=>{!e.find((e=>""===e.userId))&&this._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*this._localAudioTrack.getAudioLevel())}),this.emit(OL.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 dL({code:oL.OPERATION_FAILED,extraCode:5504,messageParams:{reason:t,error:i}}))})),this.on(OL.REMOTE_AUDIO_UNAVAILABLE,(e=>{let{userId:t}=e;this._stopRemoteAudio({userId:t},!1).catch((()=>{}))})),this.on(OL.REMOTE_VIDEO_UNAVAILABLE,(e=>{let{userId:t,streamType:i}=e;this._stopRemoteVideo({userId:t,streamType:i},!1).catch((()=>{}))})),this._listenEvents(),this._initActiveSpeaker(),((e,t)=>{let{emit:n}=e;e.emit=function(){for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];try{return n.apply(e,o)}catch(i){let n=XO({key:YO.CATCH_HANDLER_ERROR,data:{name:t,event:o[0]},addDocLink:!1});return GO.warn("".concat(n,"\n\n").concat(i.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,t){!function(){var e;nL&&(nL=!1,5!==GO.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(TD,"/en/index.html")),console.info("* Changelog: ".concat(TD,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),GO.info("TRTC Web SDK Version:",rD),GO.info("UA:",navigator.userAgent),GO.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),$k().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(","))),GO.info(t)}})))}();let i=new XL(e,t||{});return qL.add(i),i}_listenEvents(){vP(this,this._room).add("peer-join",(e=>{let{userId:t}=e;this.emit(OL.REMOTE_USER_ENTER,{userId:t})})).add("peer-leave",(e=>{this.emit(OL.REMOTE_USER_EXIT,{userId:e})})).add("banned",(e=>{this._exitRoom().then((()=>{this.emit(OL.KICKED_OUT,{reason:e.reason})}))})).add("error",(e=>{this._exitRoom().then((()=>{this.emit(OL.ERROR,dL.convertFrom(e))}))})).add("signal-connection-state-changed",(e=>{this.emit(OL.CONNECTION_STATE_CHANGED,e)})).add("network-quality",(e=>{this._networkQuality=e,this.emit(OL.NETWORK_QUALITY,e)})).add("remote-published",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((t=>{vP(t,t).add("player-state-changed",(i=>{let n=eb(ZC({},i),{userId:e.userId});t.kind===MD.VIDEO&&(n.streamType=wL(t.streamType)),this.emit(t.kind===MD.AUDIO?OL.AUDIO_PLAY_STATE_CHANGED:OL.VIDEO_PLAY_STATE_CHANGED,n)})).add("error",(e=>{e.getCode()===_b.PLAY_NOT_ALLOWED&&this.emit(OL.AUTOPLAY_FAILED,{userId:t.userId})}))}))})).add("remote-unpublished",(e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((e=>{yP(e)}))})).add("remote-publish-state-changed",(e=>{let{prevMuteState:t,muteState:i}=e,{userId:n}=i,r=t.audioAvailable,o=t.videoAvailable,{audioAvailable:s,videoAvailable:a}=i;s||this._remoteAudioConfigMap.delete(n),a||this._remoteVideoConfigMap.delete("".concat(n,"_","main")),i.hasAuxiliary||this._remoteVideoConfigMap.delete("".concat(n,"_","sub")),r!==s&&this.emit(s?OL.REMOTE_AUDIO_AVAILABLE:OL.REMOTE_AUDIO_UNAVAILABLE,{userId:n}),o!==a&&this.emit(a?OL.REMOTE_VIDEO_AVAILABLE:OL.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"}),t.hasAuxiliary!==i.hasAuxiliary&&this.emit(i.hasAuxiliary?OL.REMOTE_VIDEO_AVAILABLE:OL.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"})})).add("firewall-restriction",(()=>{this.emit(OL.ERROR,new dL({code:oL.OPERATION_FAILED,extraCode:5501}))})).add("sei-message",(e=>{this.emit(OL.SEI_MESSAGE,eb(ZC({},e),{streamType:wL(e.streamType)}))})).add("heartbeat-report",(e=>{var t,i,n,r,o,s,a;let c={2:"big",3:"small",7:"sub"},l={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(t=e.msg_down_stream_info[0])?void 0:t.msg_network_status.uint32_rtt)||(null==(i=this._networkQuality)?void 0:i.uplinkRTT)||(null==(n=this._networkQuality)?void 0:n.downlinkRTT)||0,upLoss:(null==(r=this._networkQuality)?void 0:r.uplinkLoss)||0,downLoss:(null==(o=this._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=e.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(a=e.msg_up_stream_info.msg_audio_status)?void 0:a.uint32_audio_level)||0)/VN},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)/VN},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(OL.STATISTICS,l)})),vP(this,WP).add("audioInputAdded",(e=>{this.emit(OL.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})})).add("audioInputRemoved",(e=>{this.emit(OL.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})})).add("videoInputAdded",(e=>{this.emit(OL.DEVICE_CHANGED,{type:"camera",action:"add",device:e})})).add("videoInputRemoved",(e=>{this.emit(OL.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})})).add("audioOutputAdded",(e=>ab(this,null,(function*(){if(this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),QL&&QL.deviceId===CN){let e=(yield qP()).find((e=>e.deviceId===CN));e&&QL.groupId!==e.groupId&&(QL=e,this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"active",device:e}))}})))).add("audioOutputRemoved",(e=>ab(this,null,(function*(){this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield qP())[0];t&&QL&&(QL.deviceId===e.deviceId||QL.deviceId===CN&&QL.groupId!==t.groupId)&&(QL=t,this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))))}enterRoom(e){return ab(this,null,(function*(){var t,i;let{scene:n="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:s=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!rO(e.proxy)&&e.proxy.turnServer&&(null==(i=(t=this._room).setTurnServer)||i.call(t,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=s,sO(e.enableHWEncoder)&&(this._room.enableHWEncoder=e.enableHWEncoder);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId&&(this._room.useStringRoomId=!0),this._handleReceiveMode(),yield this._room.join(a,n,XL.frameWorkType),this._checkTrackToPublish()}))}exitRoom(){return ab(this,null,(function*(){return yield this._exitRoom()}))}switchRole(e,t){return ab(this,null,(function*(){null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),yield this._room.switchRole(e),"anchor"===e&&this._checkTrackToPublish()}))}destroy(){yP(this),this.removeAllListeners(),this._room.destroy(),qL.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:i=!0,mute:n,option:r}=t,o=new hM(e._room.audioManager),s={},a={muted:!0};r&&(nO(r.microphoneId)?nO(r.audioTrack)||(s.customSource=r.audioTrack):s.deviceId=r.microphoneId,r&&oO(r.captureVolume)&&o.setCaptureVolume(r.captureVolume),nO(r.profile)||(rO(r.profile)?OD[r.profile]&&o.setProfile(OD[r.profile]):o.setProfile(r.profile)),oO(r.earMonitorVolume)&&(a.muted=!(r.earMonitorVolume>0),a.volume=r.earMonitorVolume),nO(r.echoCancellation)||(o.profile.echoCancellation=r.echoCancellation),nO(r.noiseSuppression)||(o.profile.noiseSuppression=r.noiseSuppression),nO(r.autoGainControl)||(o.profile.autoGainControl=r.autoGainControl)),o.on("5",(t=>{e.emit(OL.ERROR,new dL({code:oL.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),o.on("2",(t=>{e.emit(OL.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),o.on("4",(t=>{let i;t.error&&(i=dL.convertFrom(t.error)),e.emit(OL.PUBLISH_STATE_CHANGED,eb(ZC({},t),{error:i}))})),e._listenOutputTrackChanged(o),e._speakerId&&o.setAudioOutput(e._speakerId),yield o.capture(s),nO(n)||o.setMute(n),vP(o,o).add("player-state-changed",(t=>{e.emit(OL.AUDIO_PLAY_STATE_CHANGED,eb(ZC({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(o).catch((()=>{})),yield e._updateAudioPlayOption({playOption:a,track:o}),e._localAudioTrack=o,e._localAudioConfig=eb(ZC({},t),{publish:i})}()}))}updateLocalAudio(e){return ab(this,null,(function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:i,option:n}=e,r={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):nO(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),nO(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),nO(n.earMonitorVolume)||(r.muted=!(n.earMonitorVolume>0),r.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!nO(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((()=>{})),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch((()=>{}))),nO(i)||this._localAudioTrack.setMute(i),yield this._updateAudioPlayOption({playOption:r,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),RO(this._localAudioConfig,e)}))}stopLocalAudio(){return ab(this,null,(function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch((()=>{}))),this._localAudioTrack.stop(),this._localAudioTrack.close(),yP(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)}))}startLocalVideo(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:i,publish:n=!0,mute:r,option:o}=t,s=new pM(e._room.videoManager),a={},c={};if(o&&(o.cameraId?a.deviceId=o.cameraId:nO(o.useFrontCamera)?nO(o.videoTrack)||(a.customSource=o.videoTrack):a.facingMode=o.useFrontCamera?MD.FACING_MODE_USER:MD.FACING_MODE_ENVIRONMENT,nO(o.profile)||(rO(o.profile)?wD[o.profile]&&s.setProfile(wD[o.profile]):s.setProfile(o.profile)),nO(o.fillMode)||(c.objectFit=o.fillMode),nO(o.mirror)||(c.mirror=o.mirror),nO(o.small)||(Tw()?rO(o.small)?s.small=wD[o.small]:!0===o.small?s.small=wD["120p"]:s.small=o.small:e._log.warn("small stream is not supported"))),s.on("5",(t=>{e.emit(OL.ERROR,new dL({code:oL.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),s.on("2",(t=>{e.emit(OL.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),s.on("4",(t=>{let i;t.error&&(i=dL.convertFrom(t.error)),e.emit(OL.PUBLISH_STATE_CHANGED,eb(ZC({},t),{error:i}))})),e._listenOutputTrackChanged(s),yield s.capture(a),nO(r)||s.setMute(r),(null==o?void 0:o.qosPreference)&&s.mediaTrack){let e=PL(o.qosPreference);s.mediaTrack.contentHint=e}vP(s,s).add("player-state-changed",(t=>{e.emit(OL.VIDEO_PLAY_STATE_CHANGED,eb(ZC({},t),{userId:"",streamType:"main"}))})),n&&e._room.isJoined&&e._room.publish(s).catch((()=>{})),yield e._updateVideoPlayOption({view:i,playOption:c,track:s}),e._localVideoTrack=s,e._localVideoConfig=eb(ZC({},t),{view:i,publish:n})}()}))}updateLocalVideo(e){return ab(this,null,(function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:i,mute:n,option:r}=e,o={};if(r){if(nO(r.profile)||(rO(r.profile)?wD[r.profile]&&this._localVideoTrack.setProfile(wD[r.profile]):this._localVideoTrack.setProfile(r.profile),(!r.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(r.cameraId))&&nO(r.useFrontCamera)&&this._localVideoTrack.applyProfile()),r.cameraId?yield this._localVideoTrack.switchDevice(r.cameraId):nO(r.useFrontCamera)?nO(r.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(r.videoTrack)):yield this._localVideoTrack.switchDevice(r.useFrontCamera?MD.FACING_MODE_USER:MD.FACING_MODE_ENVIRONMENT),nO(r.fillMode)||(o.objectFit=r.fillMode),nO(r.mirror)||(o.mirror=r.mirror),r.qosPreference&&this._localVideoTrack.mediaTrack){let e=PL(r.qosPreference);this._localVideoTrack.mediaTrack.contentHint=e}if(r.small){let e=!this._localVideoTrack.small;Tw()?(!0===r.small?this._localVideoTrack.small=wD["120p"]:rO(r.small)?this._localVideoTrack.small=wD[r.small]:this._localVideoTrack.small=r.small,this._room.videoManager.update(),e&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else!1===r.small&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!nO(i)&&(i&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch((()=>{})),this._localVideoConfig.publish&&!i&&this._room.unpublish(this._localVideoTrack).catch((()=>{}))),nO(n)||this._localVideoTrack.setMute(n),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),RO(this._localVideoConfig,e)}))}stopLocalVideo(){return ab(this,null,(function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch((()=>{}))),this._localVideoTrack.stop(),this._localVideoTrack.close(),yP(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)}))}startScreenShare(){return ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return function*(){if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:i=null,publish:n=!0,option:r}=t,o=new _M(e._room.videoManager);o.on("4",(t=>{let i;t.error&&(i=dL.convertFrom(t.error)),e.emit(OL.PUBLISH_STATE_CHANGED,eb(ZC({},t),{error:i}))})),e._listenOutputTrackChanged(o);let s=null;o.setMediaType(2);let a={},c={};r&&(nO(r.profile)||(rO(r.profile)?PD[r.profile]&&o.setProfile(PD[r.profile]):o.setProfile(r.profile)),r.systemAudio&&(a.systemAudio=!0,a.echoCancellation=r.echoCancellation,a.noiseSuppression=r.noiseSuppression,a.autoGainControl=r.autoGainControl),nO(r.fillMode)||(c.objectFit=r.fillMode),r.videoTrack&&(a.videoTrack=r.videoTrack),r.audioTrack&&(a.audioTrack=r.audioTrack));let l=yield o.capture(a);if(null!=r&&r.qosPreference){let e=PL(r.qosPreference);o.mediaTrack.contentHint=e}if(o.mediaTrack.addEventListener(MD.ENDED,(()=>{e._stopScreenShare(),e.emit(OL.SCREEN_SHARE_STOPPED)})),l.getAudioTracks()[0]&&(s=new fM(e._room.audioManager),s.setInputMediaStreamTrack(l.getAudioTracks()[0]),e._speakerId&&s.setAudioOutput(e._speakerId)),vP(o,o).add("player-state-changed",(t=>{e.emit(OL.VIDEO_PLAY_STATE_CHANGED,eb(ZC({},t),{userId:"",streamType:"sub"}))})),n&&e._room.isJoined){let t=[o];s&&t.push(s),e._room.publish(...t).catch((()=>{}))}yield e._updateVideoPlayOption({view:i,playOption:c,track:o}),e._localScreenTrack=o,e._localScreenAudioTrack=s,e._localScreenConfig=eb(ZC({},t),{view:i,publish:n})}()}))}updateScreenShare(e){return ab(this,null,(function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:i,option:n}=e,r={};if(n&&(nO(n.fillMode)||(r.objectFit=n.fillMode),n.qosPreference)){let e=PL(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=e}this._room.isJoined&&!nO(i)&&(i&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch((()=>{})),this._localScreenConfig.publish&&!i&&this._room.unpublish(this._localScreenTrack).catch((()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:r,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),RO(this._localScreenConfig,e)}))}stopScreenShare(){return ab(this,null,(function*(){return yield this._stopScreenShare()}))}startRemoteVideo(e){return ab(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(i,", streamType:").concat(n));let s=this._room.remotePublishedUserMap.get(i);if(!s)return;let a={},c="main"===n?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._listenOutputTrackChanged(c),r&&(nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror),"main"===n&&!nO(r.small)&&this._room.changeType(r.small,c.user)),yield this._room.subscribe(c),yield this._updateVideoPlayOption({view:t,playOption:a,track:c}),this._remoteVideoConfigMap.set(o,e),this._emitTrackEvent(c)}))}updateRemoteVideo(e){return ab(this,null,(function*(){let{view:t,userId:i,streamType:n,option:r}=e,o="".concat(i,"_").concat(n),s=this._remoteVideoConfigMap.get(o);if(!s||!this._room.remotePublishedUserMap.has(i))return;let a={};r&&(nO(r.fillMode)||(a.objectFit=r.fillMode),nO(r.mirror)||(a.mirror=r.mirror));let c=null,l=this._room.remotePublishedUserMap.get(i);"main"===n&&(null==l?void 0:l.muteState.hasVideo)&&(c=l.remoteVideoTrack),"sub"===n&&(null==l?void 0:l.muteState.hasAuxiliary)&&(c=l.remoteAuxiliaryTrack),c&&("main"===n&&r&&!nO(r.small)&&this._room.changeType(r.small,c.user),yield this._updateVideoPlayOption({view:t,playOption:a,track:c,prevConfig:s})),RO(s,e)}))}stopRemoteVideo(e){return ab(this,null,(function*(){return this._stopRemoteVideo(e)}))}_stopRemoteVideo(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(this,null,(function*(){let i=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:t,remoteVideoTrack:r,remoteAuxiliaryTrack:o}=n;"main"===e.streamType&&(r.stop(),t.hasVideo&&i.push(r)),"sub"===e.streamType&&(o.stop(),t.hasAuxiliary&&i.push(o))}for(let e of i)t&&(yield this._room.unsubscribe(e),this._mediaTrackMap.get(e.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(e.outMediaTrack));this._remoteVideoConfigMap.delete("".concat(e.userId,"_").concat(e.streamType))}))}muteRemoteAudio(e,t){return ab(this,null,(function*(){if("*"===e)if(t)yield this._stopRemoteAudio({userId:e});else{let e=[...this._room.remotePublishedUserMap.values()];for(let t of e)t.muteState.hasAudio&&(yield this._startRemoteAudio({userId:t.userId}))}else t?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,t)}))}setRemoteAudioVolume(e,t){if("*"===e){let e=[...this._room.remotePublishedUserMap.values()];for(let i of e)this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}else if(e){let i=this._room.remotePublishedUserMap.get(e);i&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}startPlugin(e,t){return ab(this,null,(function*(){return e.start(t)}))}updatePlugin(e,t){return ab(this,null,(function*(){return e.update(t)}))}stopPlugin(e,t){return ab(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 super.on(e,t,i),this._eventListened.add(e),this}off(e,t,i){return"*"===e?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,i),this}getVideoTrack(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},{userId:t="",streamType:i="main"}=e;if(""===t){if("main"===i&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if("sub"===i&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let e=this._room.remotePublishedUserMap.get(t);if(e)return"main"===i?e.remoteVideoTrack.mediaTrack:e.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let t=this._room.remotePublishedUserMap.get(e);if(t)return t.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var t,i;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(i=this._localScreenAudioTrack)||i.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((t=>t.remoteAudioTrack.setAudioOutput(e)))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return ab(this,null,(function*(){let{userId:t,option:i}=e;if(this._remoteAudioConfigMap.has(t))return void this._log.warn("remote audio has already started. userId:".concat(t));let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let r={};i&&(nO(i.volume)||(r.volume=i.volume));let o=n.remoteAudioTrack;this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(o),yield this._updateAudioPlayOption({playOption:r,track:o})}catch(_U){throw this._remoteAudioConfigMap.delete(t),_U}this._emitTrackEvent(o)}))}_stopRemoteAudio(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return ab(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 ab(this,arguments,(function(e){let{view:t,playOption:i,track:n,prevConfig:r}=e;return function*(){if(nO(t)&&r&&r.view&&!SO(i)){let e;e=cO(r.view)?r.view:bO(r.view),e&&(yield n.play(e,i))}if(!nO(t)){let e;e=cO(t)?t:bO(t),e?yield n.play(e,i):n.stop()}}()}))}_updateAudioPlayOption(e){return ab(this,arguments,(function(e){let{playOption:t={},track:i,prevConfig:n}=e;return function*(){if(!i.isPlayCalled)try{yield i.play(null,t)}catch(cD){}nO(t.muted)||i.setPlayerMute(t.muted),nO(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(OL.TRACK,{userId:t,streamType:wL(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var e,t,i;let n=[];if((null==(e=this._localAudioConfig)?void 0:e.publish)&&this._localAudioTrack&&n.push(this._localAudioTrack),(null==(t=this._localVideoConfig)?void 0:t.publish)&&this._localVideoTrack&&n.push(this._localVideoTrack),null!=(i=this._localScreenConfig)&&i.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack)),0!==n.length)return this._room.publish(...n).catch((()=>{}))}_handleReceiveMode(){this._room.autoReceiveAudio&&vP(this,this).add(OL.REMOTE_AUDIO_AVAILABLE,(e=>ab(this,[e],(function(e){var t=this;let{userId:i}=e;return function*(){t._remoteAudioMuteMap.get("*")||t._remoteAudioMuteMap.get(i)||t._doStartRemoteAudio({userId:i}).catch((()=>{}))}()})))),this._room.autoReceiveVideo&&vP(this,this).add(OL.REMOTE_VIDEO_AVAILABLE,(e=>{let{userId:t,streamType:i}=e,n=this._room.remotePublishedUserMap.get(t);if(n){let e="main"===i?n.remoteVideoTrack:n.remoteAuxiliaryTrack;this._room.subscribe(e).then((()=>{this._emitTrackEvent(e)})).catch((()=>{}))}}))}_exitRoom(){return ab(this,null,(function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach((e=>{this._stopRemoteAudio({userId:e}).catch()})),[...this._remoteVideoConfigMap.keys()].forEach((e=>{let t=e.includes("main")?"main":"sub",i=e.split("_".concat(t))[0];i&&this._stopRemoteVideo({userId:i,streamType:t}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach((e=>{yP(e.remoteAudioTrack),yP(e.remoteVideoTrack),yP(e.remoteAuxiliaryTrack)}))}))}_stopScreenShare(){return ab(this,null,(function*(){var e,t,i;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(),null==(t=this._localScreenAudioTrack)||t.stop(),null==(i=this._localScreenAudioTrack)||i.close(),yP(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}}))}_initActiveSpeaker(){return ab(this,null,(function*(){if(QL&&!JP(QL))this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"active",device:QL});else{let e=yield qP();if(e[0]&&!JP(e[0]))QL=e[0],this.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let e=e=>{let{track:t}=e;"audio"===t.kind&&(!QL||JP(QL))&&(this._initActiveSpeaker(),FO.off("102",this._initActiveSpeaker))};FO.on("102",e)}}}))}sendSEIMessage(e,t){this._room.sendSEI(e,t||{seiPayloadType:243})}static setLogLevel(e,t){GO.setLogLevel(e),nO(t)||(t?GO.enableUploadLog():GO.disableUploadLog())}static isSupported(){return lw()}static getCameraList(){return zP(!0)}static getMicrophoneList(){return YP(!0)}static getSpeakerList(){return qP(!0)}static setCurrentSpeaker(e){return ab(this,null,(function*(){(yield qP()).forEach((t=>{t.deviceId===e&&(qL.forEach((i=>{i.setCurrentSpeaker(e),i.emit(OL.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),QL=t)}))}))}},$L=XL;ob($L,"_loggerManager",GO),ob($L,"EVENT",OL),ob($L,"ERROR_CODE",oL),ob($L,"TYPE",rL),ob($L,"frameWorkType",30),rb([xL(EL.TRTC.enterRoom),kL("room",((e,t)=>{let[i]=e,[n]=t;return(i.roomId||i.strRoomId)===(n.roomId||n.strRoomId)&&i.userId===n.userId&&i.sdkAppId===n.sdkAppId})),oM((e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)})),BL()],$L.prototype,"enterRoom",1),rb([BL()],$L.prototype,"exitRoom",1),rb([xL(EL.TRTC.switchRole),DL("room",{merge:(e,t)=>t}),BL()],$L.prototype,"switchRole",1),rb([BL()],$L.prototype,"destroy",1),rb([xL(EL.TRTC.startLocalAudio),kL("audio",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.microphoneId)===(null==(o=null==n?void 0:n.option)?void 0:o.microphoneId)})),BL()],$L.prototype,"startLocalAudio",1),rb([xL(EL.TRTC.updateLocalAudio),DL("audio",{debounce:{delay:200,getKey:()=>"".concat(zL,"-localAudio"),isNeedToDebounce:e=>{var t;return!nO(null==(t=e.option)?void 0:t.captureVolume)}}}),BL()],$L.prototype,"updateLocalAudio",1),rb([NL("audio"),BL()],$L.prototype,"stopLocalAudio",1),rb([xL(EL.TRTC.startLocalVideo),kL("video",((e,t)=>{let[i]=e,[n]=t;var r,o;return(null==(r=null==i?void 0:i.option)?void 0:r.cameraId)===(null==(o=null==n?void 0:n.option)?void 0:o.cameraId)})),BL()],$L.prototype,"startLocalVideo",1),rb([xL(EL.TRTC.updateLocalVideo),DL("video"),BL()],$L.prototype,"updateLocalVideo",1),rb([NL("video"),BL()],$L.prototype,"stopLocalVideo",1),rb([xL(EL.TRTC.startScreenShare),kL("screen",(()=>!0)),BL()],$L.prototype,"startScreenShare",1),rb([xL(EL.TRTC.updateScreenShare),DL("screen"),BL()],$L.prototype,"updateScreenShare",1),rb([BL()],$L.prototype,"stopScreenShare",1),rb([xL(EL.TRTC.startRemoteVideo),kL((e=>"v".concat(e.userId).concat(e.streamType)),(()=>!0)),BL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$L.prototype,"startRemoteVideo",1),rb([xL(EL.TRTC.updateRemoteVideo),DL((e=>"v".concat(e.userId).concat(e.streamType))),BL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$L.prototype,"updateRemoteVideo",1),rb([xL(EL.TRTC.stopRemoteVideo),oM((e=>function(t){return ab(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)}))})),BL({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],$L.prototype,"stopRemoteVideo",1),rb([NL((e=>"v".concat(e.userId).concat(e.streamType)))],$L.prototype,"_stopRemoteVideo",1),rb([xL(...EL.TRTC.muteRemoteAudio),BL({getRemoteId:e=>e})],$L.prototype,"muteRemoteAudio",1),rb([VL(...EL.TRTC.setRemoteAudioVolume),function(e,t){return oM(((i,n)=>function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];var s,a;let c=null==(s=LL.get(this))?void 0:s.get(t(...r));c&&c>0&&clearTimeout(c);let l=window.setTimeout((()=>{i.apply(this,r)}),e);LL.has(this)?null==(a=LL.get(this))||a.set(t(...r),l):LL.set(this,new Map([[t(...r),l]]))}))}(200,(e=>e)),BL({getRemoteId:e=>e})],$L.prototype,"setRemoteAudioVolume",1),rb([HL("start"),kL(((e,t)=>e.getAlias()+e.getGroup(t))),BL({namePrefix:e=>e.getName()})],$L.prototype,"startPlugin",1),rb([HL("update"),DL(((e,t)=>e.getAlias()+e.getGroup(t))),BL({namePrefix:e=>e.getName()})],$L.prototype,"updatePlugin",1),rb([HL("stop"),NL(((e,t)=>e.getAlias()+e.getGroup(t))),BL({namePrefix:e=>e.getName()})],$L.prototype,"stopPlugin",1),rb([VL(...EL.TRTC.enableAudioVolumeEvaluation)],$L.prototype,"enableAudioVolumeEvaluation",1),rb([BL()],$L.prototype,"setCurrentSpeaker",1),rb([kL((e=>"a".concat(e.userId)),(()=>!0))],$L.prototype,"_startRemoteAudio",1),rb([oM((e=>function(t){return ab(this,null,(function*(){return"*"===t.userId?Promise.all([...this._room.remotePublishedUserMap.values()].map((e=>this._stopRemoteAudio(eb(ZC({},t),{userId:e.userId})).catch((()=>{}))))):e.call(this,t)}))})),NL((e=>"a".concat(e.userId)))],$L.prototype,"_stopRemoteAudio",1),rb([NL("room")],$L.prototype,"_exitRoom",1),rb([NL("screen")],$L.prototype,"_stopScreenShare",1),rb([xL(EL.TRTC.sendSEIMessage),function(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:n}=e;return oM(((e,r)=>{let o=new Map;return FO.on(HO.ROOM_DESTROY,(e=>{let{room:t}=e;return o.delete(t)})),function(){let s=o.get(this);for(var a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(s||(s={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,s)),0===s.timestamp?s.timestamp=Date.now():Date.now()-s.timestamp>1e3&&(s.timestamp=Date.now(),s.callCountInSecond=0,s.totalSizeInSecond=0),n&&(s.totalSizeInSecond+=n(...c)),0!==s.timestamp&&Date.now()-s.timestamp<1e3&&(s.callCountInSecond>=t||s.totalSizeInSecond>i))throw new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.CALL_FREQUENCY_LIMIT,data:{isTimes:s.callCountInSecond>=t,isSize:s.totalSizeInSecond>i,name:r,timesInSecond:t,maxSizeInSecond:i}})});s.callCountInSecond++,e.call(this,...c)}}))}({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],$L.prototype,"sendSEIMessage",1),rb([xL(EL.TRTC.create)],$L,"_create",1);var ZL=$L,ex=class{constructor(){this._set=new Set,FO.on(HO.LEAVE_SUCCESS,this.delete,this)}add(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(n)}delete(e){let{room:t,roomId:i}=e;if("rtc"===t.scene)return;let n=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(n)}getKey(e,t,i,n){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(n)}isJoined(e){let{userId:t,roomId:i,sdkAppId:n,room:r}=e;return"rtc"!==r.scene&&this._set.has(this.getKey(t,i,n,r.useStringRoomId))}};function tx(){return ab(this,null,(function*(){let e,t;try{let t=yield YP();e=t&&t.length}catch(u){}try{let e=yield zP();t=e&&e.length}catch(u){}let i={microphone:e,camera:t},{isH264EncodeSupported:n,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:s}=this.checkSystemResult.detail,a=KO.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:n,h264Decode:o,vp8Encode:r,vp8Decode:s},l={browser:a.browser,os:a.os,trtc:c,devices:i},d={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};$w.uploadEvent({log:"trtcstats-".concat(JSON.stringify(l)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(l))),$w.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(d)),userId:this.userId})}))}var ix=nb(cb(),1),nx=Symbol("instance"),rx=Symbol("cacheResult"),ox=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,dx.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},sx=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};var ax=new Map;function cx(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(n,r,o)=>{let s=i.action||r;if(!i.context){let i=ax.get(n)||[];ax.has(n)||ax.set(n,i),i.push({from:e,to:t,action:s})}let a=o.value;o.value=function(){let n=this;for(var r=arguments.length,o=new Array(r),c=0;c<r;c++)o[c]=arguments[c];if(i.context&&(n=ux.get("function"==typeof i.context?i.context.call(this,...o):i.context)),n.state===t)return n[rx];n.state instanceof ox&&n.state.action==i.abortAction&&n.state.abort(n);let l=null;if(Array.isArray(e)?0==e.length?n.state instanceof ox&&n.state.abort(n):("string"!=typeof n.state||!e.includes(n.state))&&(l=new sx(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not in from config"))):e!==n.state&&(l=new sx(n._state,"".concat(n.name," ").concat(s," to ").concat(t," failed: current state ").concat(n._state," not from ").concat(e))),l){if(!i.fail){if(i.ignoreError)return l;throw l}i.fail.call(this,l)}let d=n.state,u=new ox(d,t,s);dx.call(n,u);let h=e=>{var r;return n[rx]=e,u.aborted||(dx.call(n,t),null===(r=i.success)||void 0===r||r.call(this,n[rx])),e},p=e=>{let t=e instanceof Error?e.message:String(e);if(dx.call(n,d,e),!i.fail){if(i.ignoreError)return e;throw e}i.fail.call(this,new sx(n._state,"action '".concat(s,"' failed :").concat(t),e instanceof Error?e:new Error(t)))};try{let e=a.apply(this,o);return function(e){return"object"==typeof e&&e&&"then"in e}(e)?e.then(h).catch(p):h(e)}catch(m){p(m)}}}}var lx="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 dx(e,t){let i=this._state;this._state=e;let n=e.toString();e&&this.emit(n,i),this.emit(ux.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var ux=class extends ix.default{constructor(e,t,i){super(),this.name=e,this.groupName=t,this._state=ux.INIT,e||(e=Date.now().toString(36)),i?Object.setPrototypeOf(this,i):i=Object.getPrototypeOf(this),t||(this.groupName=this.constructor.name);let n=i[nx];n?this.name=n.name+"-"+n.count++:i[nx]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),t=ax.get(e)||[],i=new Set,n=[],r=[],o=new Set,s=Object.getPrototypeOf(e);ax.has(s)&&(s.stateDiagram.forEach((e=>i.add(e))),s.allStates.forEach((e=>o.add(e)))),t.forEach((e=>{let{from:t,to:i,action:o}=e;"string"==typeof t?n.push({from:t,to:i,action:o}):t.length?t.forEach((e=>{n.push({from:e,to:i,action:o})})):r.push({to:i,action:o})})),n.forEach((e=>{let{from:t,to:n,action:r}=e;o.add(t),o.add(n),o.add(r+"ing"),i.add("".concat(t," --\x3e ").concat(r,"ing : ").concat(r)),i.add("".concat(r,"ing --\x3e ").concat(n," : ").concat(r," 🟢")),i.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🔴"))})),r.forEach((e=>{let{to:t,action:n}=e;i.add("".concat(n,"ing --\x3e ").concat(t," : ").concat(n," 🟢")),o.forEach((e=>{e!==t&&i.add("".concat(e," --\x3e ").concat(n,"ing : ").concat(n))}))}));let a=[...i];return Object.defineProperties(e,{stateDiagram:{value:a},allStates:{value:o}}),a}static get(e){let t;return"string"==typeof e?(t=ux.instances.get(e),t||ux.instances.set(e,t=new ux(e,void 0,Object.create(ux.prototype)))):(t=ux.instances2.get(e),t||ux.instances2.set(e,t=new ux(e.constructor.name,void 0,Object.create(ux.prototype)))),t}static getState(e){var t;return null===(t=ux.get(e))||void 0===t?void 0:t.state}updateDevTools(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};lx(ux.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){dx.call(this,e)}};ux.STATECHANGED="stateChanged",ux.UPDATEAFSM="updateAFSM",ux.INIT="[*]",ux.ON="on",ux.OFF="off",ux.instances=new Map,ux.instances2=new WeakMap;var hx=nb(cb()),px="1",mx="5",_x="2",fx="3",gx="4",Tx={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},Ex=[Tx.UPDATE_REMOTE_MUTE_STAT,Tx.UPLINK_NETWORK_STATS,Tx.USER_LIST_RES,Tx.MUTE_RESULT],Sx={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"},Ix="publish_change",vx="join",yx="leave",Ax="quality_report",Rx="mute_uplink",Cx="publish",bx="publish_state_change",kx="unpublish",Dx="subscribe",Nx="unsubscribe",Ox="subscribe_change",wx="start_publishing",Px="stop_publishing",Mx="start_push_user_cdn",Lx="stop_push_user_cdn",xx="start_mcu_mix",Vx="stop_mcu_mix",Ux="get_user_list",Fx="change_role",Bx="update_constraint_config",Hx="rebuild_pc",jx="join/v2",Gx="publish/v2",Wx="subscribe/v3",Jx="ability_status_report",Kx="reconnect",Yx=new WeakMap;function zx(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:r}=e;return function(e,o,s){let a=VO({retryFunction:s.value,settings:t,onError(t){let{error:n,retry:r,reject:s,retryFuncArgs:a}=t;i&&i.call(this,n,(()=>{var t;null!=(t=Yx.get(e))&&t.has(o)?r():s(n)}),s,a)},onRetrying(t,i){var r;iO(n)&&n.call(this,t,i),null!=(r=Yx.get(e))&&r.has(o)&&(Yx.get(e).get(o).stopRetry=i)},onRetryFailed:r});return s.value=function(){let t=Yx.get(e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return t?t.set(o,{args:n}):Yx.set(e,new Map([[o,{args:n}]])),a.apply(this,n).finally((()=>{var t;return null==(t=Yx.get(e))?void 0:t.delete(o)}))},s}}function qx(e){let{fnName:t,callback:i,validateArgs:n=!0}=e;return function(e,r,o){let s=o.value;return o.value=function(){for(var r,o,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];if(null!=(r=Yx.get(e))&&r.has(t)){let{stopRetry:r,args:s}=Yx.get(e).get(t),a=!0;if(n)for(let e of s)if(!c.find((t=>t===e))){a=!1;break}a&&(i&&i.apply(this,c),r&&r(),null==(o=Yx.get(e))||o.delete(t))}return s.apply(this,c)},o}}var Qx=null,Xx=!0;function $x(e){sO(e)&&e!==Xx&&(Xx=e,GO.info("setIsNeedToSchedule ".concat(e)))}function Zx(e){return ab(this,arguments,(function(e){let{userId:t,sdkAppId:i,useStringRoomId:n,roomId:r,userSig:o,version:s,frameWorkType:a}=e;return function*(){if(!Xx&&Qx)return{isCached:!0,result:Qx};let e={delta:0,count:[1,1],msg:[],detail:[]};try{let c=new FormData;c.append("userId",String(t)),c.append("sdkAppId",String(i)),c.append("isStrGroupId",String(n)),c.append("groupId",String(r)),c.append("sdkVersion",s),c.append("userSig",String(o)),a&&c.append("frameWorkType",String(a));let l=fO(),d=yield function(e,t,i){return new Promise(((n,r)=>{let o=null;_O([rV((e=>t.count[0]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[0]=i.message,o||n()}))(iV(i,MD.MAIN),e,{get timeout(){return 1e3*ZN(2+t.count[0])}}),rV((e=>t.count[1]=e+1),(e=>{let{error:i,retry:n}=e;t.msg[1]=i.message,o||n()}))(iV(i,MD.BACKUP),e,{get timeout(){return 1e3*ZN(2+t.count[1])}})]).then((e=>{o=e,n(o)})).catch(r)}))}(c,e,i);d.config&&(d.config.loggerDomain&&pD(d.config.loggerDomain),sO(d.config.scheduleCache)&&$x(!d.config.scheduleCache)),e.delta=fO()-l;let u=function(e,t,i){let n=performance.getEntriesByType("resource"),r=iV(e,MD.MAIN),o=iV(e,MD.BACKUP),s={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};for(let a of n)if(a.startTime>=i&&(a.name===r||a.name===o)&&a.transferSize>0){let e=a.name===r?MD.MAIN:MD.BACKUP,i=Math.round(a.duration),n=Math.round(a.domainLookupStart-a.startTime),o=Math.round(a.domainLookupEnd-a.domainLookupStart),c=Math.round(a.requestStart-a.secureConnectionStart),l=Math.round(a.secureConnectionStart-a.connectStart),d=Math.round(a.responseStart-a.requestStart),u=Math.round(a.responseEnd-a.responseStart),h=[n,o,c,l,d,u];$w.uploadEvent({log:"stat-schedule-net:".concat(i,"(").concat(h.join("->"),") ").concat(e),userId:t}),s=eb(ZC({},s),{totalCost:i,local:n,dns:o,tcp:l,tls:c,request:d,response:u});break}return s}(Number(i),t,l);return Qx=d,{isCached:!1,result:d,detailCost:u}}catch(c){let e=cO(c)?c[0]:c,t=oO(e.code)?e.code:0,i="schedule failed".concat(e.message?": ".concat(e.message):""),n=new gb({code:_b.SCHEDULE_FAILED,extraCode:t,message:XO({key:YO.JOIN_ROOM_FAILED,data:{error:i,code:t}})});throw GO.error(i,t),n}}()}))}document&&document.head.insertAdjacentHTML("beforeend",Object.values(IN).map((e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">'))).join("\r\n")),FO.on("28",(()=>$x(!0))),FO.on("63",(()=>$x(!0))),FO.on("84",(()=>$x(!0))),FO.on("201",(e=>{"RECONNECTING"===e.state&&$x(!0)})),FO.on("202",(e=>{"RECONNECTING"===e.state&&$x(!0)}));var eV={main:"",backup:""};function tV(e){cO(e)?(eV.main=e[0],eV.backup=e[1]):eV.main=e}function iV(e){let t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:MD.MAIN;return t=FN(e)?i===MD.MAIN?IN.MAIN_OVERSEA:IN.BACKUP_OVERSEA:i===MD.MAIN?IN.MAIN:IN.BACKUP,"https://".concat(eV[i]||t,"/api/v1/config")}function nV(e,t,i){return new Promise(((n,r)=>{LO({url:e,body:t,timeout:i.timeout}).then((e=>{0===e.data.code?n(e.data.data):r({code:e.data.code,message:e.data.msg})})).catch(r)}))}var rV=(e,t)=>VO({retryFunction:nV,settings:{retries:3,timeout:0},onError:t,onRetrying:e});var oV=new Set;var sV=class extends hx.default{constructor(e){var t,i;super(),ob(this,"room"),ob(this,"url"),ob(this,"backupUrl"),ob(this,"race"),ob(this,"_socketInUse"),ob(this,"_socket"),ob(this,"_backupSocket"),ob(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0}),ob(this,"_currentState","DISCONNECTED"),ob(this,"_isReconnecting",!1),ob(this,"_seq",0),ob(this,"_log"),ob(this,"_lastMessageTime",-1),ob(this,"_connnectStartTime",-1),ob(this,"_stopConnectRetry"),ob(this,"bytesSent",0),ob(this,"bytesReceived",0),ob(this,"keepAlive",!1),this.room=e.room,this.race=!!nO(e.race)||e.race,((null==(i=null==(t=this.room.scheduleResult)?void 0:t.config)?void 0:i.keepAliveClient)||0)-oV.size>0&&this.room.enableSPC&&(this.keepAlive=!0,oV.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=GO.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 ab(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)));let i=e._urlWithParam,n=e._backupUrlWithParam;e._connnectStartTime=fO(),e._socketInUse=yield _O([e.connectWS({url:i,isMain:!0,timeout:t}),e.connectWS({url:n,isMain:!1,timeout:t})]),e.unbindAndCloseSocket(e._socketInUse===e._socket?MD.BACKUP:MD.MAIN),e.emitConnectionStateChanged("CONNECTED")}()}))}connectWS(e){let{url:t,timeout:i,isMain:n}=e,r=new WebSocket(t);this.bindSocket(r),n?this._socket=r:this._backupSocket=r;let o=-1;return new Promise(((e,t)=>{r.onclose=t,r.onerror=t,r.onopen=()=>e(r),i&&(o=setTimeout((()=>{this.unbindAndCloseSocket(n?MD.MAIN:MD.BACKUP),t(new gb({code:_b.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),i))})).finally((()=>{r.onclose=null,r.onerror=null,r.onopen=null,clearTimeout(o)}))}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===MD.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(sN){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(sN){}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?MD.MAIN:MD.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),e.target===this._socketInUse&&(this.unbindAndCloseSocket(MD.MAIN),this.unbindAndCloseSocket(MD.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=wO(e.data);let t=JSON.parse(e.data),{cmd:i,data:n}=t,r=Object.values(Tx),o=Object.keys(Tx)[r.indexOf(i)],s=Sx[o];switch(Ex.includes(i)||(this._log.debug("received ".concat(i," msg: ").concat(e.data)),s&&this._log.info("Received event: [ ".concat(s," ]"))),i){case Tx.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&function(e){Tb=e-(new Date).getTime();let t=new Date;t.setTime(e),GO.info("baseTime from server: ".concat(t," offset: ").concat(Tb))}(n.svrTime),this._log.info("ChannelSetup Success"),FO.emit(HO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",cost:fO()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(px,{signalInfo:this._signalInfo});else{let e=new gb({code:_b.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:XO({key:YO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),FO.emit(HO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketConnect",error:e}),this.emit(mx,e)}break;case Tx.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(s,{data:t});break;default:this.emit(s,{data:t})}}reGetSignalChannelUrl(){return ab(this,null,(function*(){try{$x(!0),yield this.room.schedule(this.room.roomId);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(sD){}}))}reconnect(){return ab(this,null,(function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:n,relayPort:r}=this._signalInfo,{data:o}=yield this.sendWaitForResponse({command:Kx,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:i,relayPort:r},responseCommand:Sx.CHANNEL_RECONNECT_RESULT});0===o.code?(this._log.warn("reconnect success"),this.stopReconnection(),FO.emit(HO.API_SUCCESS_RATE,{room:this.room,apiName:"WebsocketReconnect",cost:fO()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(this._log.warn("reconnect failed, ".concat(o.code," ").concat(o.message)),this.room.reJoin())}catch(sD){this.room.reJoin()}}}))}send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(i);return this._socketInUse.send(n),this.bytesSent+=wO(n),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:n=5e3,responseCommand:r,commandDesc:o,enableLog:s=!0}=e;return new Promise(((e,a)=>{let c=setTimeout((()=>{this.off(r,l);let e=new gb({code:_b.API_CALL_TIMEOUT,message:XO({key:YO.API_CALL_TIMEOUT,data:{commandDesc:o,command:t}})});s&&this._log.warn(e),a(e)}),n),l=t=>{t.data.seq===d&&(clearTimeout(c),this.off(r,l),e(t))};this.on(r,l);let d=this.send(t,i)}))}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:n=0,retryTimeout:r=0}=e;return VO({retryFunction:this.sendWaitForResponse,onRetrying:e=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(e,"/").concat(n,"]"))},settings:{retries:n,timeout:r},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),oV.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(MD.MAIN),this.unbindAndCloseSocket(MD.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}stopKeepAliveIn(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s"));let t=setTimeout((()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close()}),1e3*e),i=e=>{e instanceof ox&&"join"===e.action&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.room.off(ux.STATECHANGED,i))};this.room.on(ux.STATECHANGED,i)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit(_x,{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e&&this.emit(fx))}};rb([zx({settings:{retries:1/0,timeout:2e3},onError(e,t){this.room.isDestroyed||t()},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,this.room.isDestroyed&&t())}})],sV.prototype,"connect",1);var aV=nb(cb()),cV=class{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[],n=0;for(let o=e;o<=t;o++){let e=this.dataView.getInt8(o);switch(e){case 0:case 1:case 2:case 3:2===n&&(i.push(3),n=0),0==e?n++:n=0,i.push(e);break;default:n=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}removePreventionByte(){let e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[],n=0;for(let o=e;o<=t;o++)switch(this.dataView.getInt8(o)){case 0:n++,i.push(this.dataView.getInt8(o));break;case 3:2!==n&&i.push(this.dataView.getInt8(o)),n=0;break;default:i.push(this.dataView.getInt8(o)),n=0}let r=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=r}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let r=6;r<this.dataView.buffer.byteLength;r++){let i=this.dataView.getUint8(r);if(t++,255!==i){e+=i;break}e+=255}let i=new ArrayBuffer(e),n=new DataView(i);for(let r=0;r<i.byteLength;r++,t++)n.setInt8(r,this.dataView.getInt8(t));return n}},lV=class{constructor(e,t){this._singlePC=e,this._log=t,ob(this,"_seiMessageList",[]),ob(this,"_smallSeiMessageList",[]),ob(this,"_seiPayloadType",243),ob(this,"_seiAbortMap",new Map),ob(this,"_nonSeiAbortMap",new Map),ob(this,"onSEIMessage",null)}isRunning(e){return this._seiAbortMap.has(e)}start(e){let t=e.direction===MD.TRANSCEIVER_DIRECTION_SENDONLY,i=(t?e.sender:e.receiver).createEncodedStreams(),n=i.readable,r=i.writable,o=new TransformStream({transform:t?(t,i)=>this.encodeVideoFrame(t,i,e):(t,i)=>this.decodeVideoFrame(t,i,e)}),s=new AbortController;n.pipeThrough(o).pipeTo(r,s).catch((e=>{this._log.warn(e)})),this._seiAbortMap.set(e,s)}restart(e){this.stop(e),this.start(e)}stop(e){var t;null==(t=this._seiAbortMap.get(e))||t.abort(),this._seiAbortMap.delete(e)}destroy(){this._seiAbortMap.forEach((e=>e.abort())),this._seiAbortMap.clear(),this._nonSeiAbortMap.forEach((e=>e.abort())),this._nonSeiAbortMap.clear(),this.onSEIMessage=null}handleEncodedStreams(){try{this._singlePC.getPeerConnection().getTransceivers().forEach(((e,t)=>{var i,n;if("inactive"!==e.direction&&e.mid)if(t<4)1===t||2===t?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e);else{let r=(t-4)%3==1,o=(t-4)%3==2;(null==(n=null==(i=e.receiver)?void 0:i.track)?void 0:n.kind)===MD.VIDEO&&(r||o)?this.isRunning(e)||this.start(e):this._nonSeiAbortMap.has(e)||this.pipeSenderOrReceiver(e)}}))}catch(QM){this._log.warn(QM)}}pipeSenderOrReceiver(e){let t=e.direction===MD.TRANSCEIVER_DIRECTION_SENDONLY?e.sender:e.receiver,{readable:i,writable:n}=t.createEncodedStreams(),r=new AbortController;this._nonSeiAbortMap.set(e,r),i.pipeTo(n,r).catch((()=>{}))}push(e,t){var i,n;t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==(n=null==(i=this._singlePC.getPeerConnection())?void 0:i.getSenders()[2])?void 0:n.track)&&this._smallSeiMessageList.push(e)}hasSEI(e){let t=new DataView(e);return 1===t.getInt32(0)&&6===t.getInt8(4)}isEmptyFrame(e){return"empty"===e.type||0===e.data.byteLength}getNaluCount(e){let t=0,i=0,n=new DataView(e);for(let r=0;r<e.byteLength;r++)switch(n.getUint8(r)){case 0:t++;break;case 1:(2===t||3===t)&&i++,t=0;break;default:t=0}return i}encodeVideoFrame(e,t,i){try{let t=2===Number(i.mid)?this._smallSeiMessageList:this._seiMessageList;if(this._singlePC.isUsingH264&&t.length>0&&!this.isEmptyFrame(e)){let i=9-this.getNaluCount(e.data);if(i<=0)return;let n=t.splice(0,i).reverse().map(this.encodeSEINalu.bind(this)),r=n.reduce(((e,t)=>e+t.dataView.byteLength),0),o=new ArrayBuffer(r+e.data.byteLength),s=new DataView(o),a=new DataView(e.data),c=0;for(let e=0;e<n.length;e++)for(let t=0;t<n[e].dataView.byteLength;t++)s.setInt8(c++,n[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)s.setInt8(c++,a.getInt8(t));e.data=o,this._log.debug("".concat(n.length," sei sent"))}}catch(aD){this._log.warn(aD)}t.enqueue(e)}decodeVideoFrame(e,t,i){try{if(this._singlePC.isUsingH264&&!this.isEmptyFrame(e)&&this.hasSEI(e.data)){let t=[],n=new DataView(e.data),r=0,o=-1,s=-1;for(let i=0;i<e.data.byteLength;i++){let a=n.getUint8(i);if(0===a)r++;else if(1===a){if(2===r||3===r){let a=i-r;if(-1===o?o=a:-1===s&&(s=a,t.push(new cV(new DataView(n.buffer.slice(o,s)))),o=a,s=-1),6!==n.getUint8(i+1)){e.data=new DataView(n.buffer.slice(a)).buffer;break}}r=0}else r=0}this._log.debug("".concat(t.length," sei received")),iO(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(aD){this._log.warn(aD)}t.enqueue(e)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),n=t%255,r=[];r.push(0,0,0,1,6,this._seiPayloadType);for(let s=0;s<i;s++)r.push(255);r.push(n);let o=new DataView(e);return r.push(...new Uint8Array(o.buffer)),r.push(128),new cV(new DataView(new Uint8Array(r).buffer),!0)}},dV=0,uV=!1,hV=new Set,pV=!1,mV=class{constructor(e){ob(this,"userId"),ob(this,"tinyId"),ob(this,"_sdpSemantics"),ob(this,"_isUplink"),ob(this,"_room"),ob(this,"_log"),ob(this,"_signalChannel"),ob(this,"_isErrorObserved",!1),ob(this,"_waitForPeerConnectionConnectedPromise"),ob(this,"_waitForPeerConnectionConnectedPromiseReject",null),ob(this,"_peerConnection",null),ob(this,"_emitter",new aV.default),ob(this,"_currentState","DISCONNECTED"),ob(this,"_isReconnecting",!1),ob(this,"_reconnectionCount",0),ob(this,"_reconnectionTimer",-1),ob(this,"_isFirstConnection",!0),ob(this,"_prevTime",-1),ob(this,"_enableSEI"),ob(this,"_sei"),ob(this,"_localAddress"),ob(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=GO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Nw&&(this._sei=new lV(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=fO())}afterConnect(e){return ab(this,null,(function*(){try{yield e,this._isFirstConnection?(this._isFirstConnection=!1,FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(fO()-this._prevTime,3e4)})):this._isReconnecting&&FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:fO()-this._prevTime}),this._prevTime=-1}catch(sD){throw this._isFirstConnection?(this._isFirstConnection=!1,FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:sD})):this._isReconnecting&&this._reconnectionCount>=3&&FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:sD}),sD}}))}initialize(){let e={encodedInsertableStreams:this._enableSEI&&Nw,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),hV.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 gb({code:_b.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return tN;let e=null;if(this._isUplink){if(!Iw()||0===this._peerConnection.getSenders().length)return tN;e=this._peerConnection.getSenders()[0].transport}else{if(!Sw()||0===this._peerConnection.getReceivers().length)return tN;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:tN}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===iN.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===iN.FAILED||e.target.connectionState===iN.CLOSED){let n="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),r=new gb({message:n,code:_b.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",r)}(e.target.connectionState===iN.CONNECTED||e.target.connectionState===iN.COMPLETED)&&(this.logSelectedCandidate(),$w.logSuccessEvent({userId:this._room.userId,eventType:cN.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&("CONNECTED"===e?(dV=0,uV=!1,pV=!0,hV.add(this)):hV.delete(this),FO.emit(HO.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 ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(pw(t)){let i=e.get(t.localCandidateId),n=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat("relay"===i.candidateType?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}}))}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this._currentState)return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{FO.off(HO.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",i,this)},o=setTimeout((()=>{r();let e=new gb({code:_b.API_CALL_TIMEOUT,message:"connection timeout"});dV+=1,(e=>dV>2&&!uV&&0===hV.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),uV=!0,this._emitter.emit("firewall-restriction")),t(e)}),SN);FO.on(HO.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",i,this)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(fx,this.reconnect,this)}beforeReconnect(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=oN()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new gb({code:this._isUplink?_b.UPLINK_RECONNECTION_FAILED:_b.DOWNLINK_RECONNECTION_FAILED,message:XO({key:this._isUplink?YO.UPLINK_RECONNECTION_FAILED:YO.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(fx,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"))}},_V=nb(hb()),fV=function(e){return _V.default.parse(e)},gV=function(e){return _V.default.write(e)};function TV(e){return Object.keys(e).filter((t=>e[t]))}var EV=class extends mV{constructor(e){super(eb(ZC({},e),{isUplink:!1})),ob(this,"_flag",0),ob(this,"role","anchor"),ob(this,"remoteAudioTrack"),ob(this,"remoteVideoTrack"),ob(this,"remoteAuxiliaryTrack"),ob(this,"ssrc",{audio:0,video:0,auxiliary:0}),ob(this,"_isSDPExchanging",!1),this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new MM(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new LM(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new xM(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 IO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===MD.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e,n=t.id===WD?MD.MAIN:MD.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=MD.AUDIO;i.kind===MD.VIDEO&&(r=n===MD.MAIN?MD.VIDEO:MD.AUXILIARY);let o=this.remoteAudioTrack;r===MD.VIDEO?o=this.remoteVideoTrack:r===MD.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}addRRTRLine(e){let t=e.split("\r\n"),i=new Map;t.forEach(((e,n)=>{/^a=rtcp-fb:/.test(e)&&t[n+1]&&!/^a=rtcp-fb:/.test(t[n+1])&&i.set(n+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));let n=[...i];for(let r=0;r<n.length;r++){let[e,i]=n[r];t.splice(e+r,0,i)}return t.join("\r\n")}addSPSDescription(e){let t=fV(e);return t.media.forEach((e=>{e.type===MD.VIDEO&&e.fmtp.forEach((e=>{e.config+=";sps-pps-idr-in-keyframe=1"}))})),gV(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=fV(e);return i.media.forEach((e=>{!e.ext||(e.ext=e.ext.filter((e=>!t.includes(e.uri))))})),gV(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ab(this,null,(function*(){var i,n;try{if(((null==(i=this._peerConnection)?void 0:i.connectionState)===iN.NEW||(null==(n=this._peerConnection)?void 0:n.connectionState)===iN.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(cD){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(cD.message," ").concat(JSON.stringify(this.muteState))),new gb({code:_b.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):cD}}))}unsubscribe(e){return ab(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){if("CONNECTED"===t._currentState&&("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed))return void t._log.info("".concat(n," stream already unsubscribed"));let e=ZC({},t.subscribeState);i.forEach((t=>{switch(t.mediaType){case 1:e.audio=!1;break;case 4:e.video=!1;break;case 8:e.smallVideo=!1;break;case 2:e.auxiliary=!1}}));let r="subscribe_change";Object.values(e).find((e=>!0===e))||(r="unsubscribe"),t._log.info("".concat("unsubscribe"===r?r:"subscribe"," ").concat(n," [").concat(TV(e),"]")),yield t.sendSubscription(r,e),"unsubscribe"===r&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"))}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Nx,r=Sx.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Ox,r=Sx.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:XO({key:YO.ERROR_MESSAGE,data:{type:e,message:i.message}})});throw this._log.error(t),t}}))}connect(){return ab(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(sN){throw e.closePeerConnection(!0),sN}}()}))}exchangeSDP(e){return ab(this,null,(function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:i}=this._peerConnection.localDescription,n={type:t,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},r=yield this._signalChannel.sendWaitForResponse({command:Dx,commandDesc:"exchange sdp",data:n,responseCommand:Sx.SUBSCRIBE_RESULT,timeout:uN});if(!this._peerConnection){let e=new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.CONNECTION_CLOSED})});throw this._log.warn(e),e}yield this.onSubscribeResult(r),this._isSDPExchanging=!1}catch(sN){throw this._isSDPExchanging=!1,sN}}))}createOffer(){return ab(this,null,(function*(){let e={voiceActivityDetection:!1};yw()&&this._sdpSemantics===hN?(this._peerConnection.addTransceiver(MD.AUDIO,{direction:LD.RECVONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:LD.RECVONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:LD.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:e}=yield cw();e||(this._log.warn("remove h264 desc from sdp"),t.sdp=function(e){let t=fV(e);return t.media.forEach((e=>{var t,i;if(e.type===MD.VIDEO){let n=new Set;e.rtp.forEach((e=>{let{payload:t,codec:i}=e;return"H264"===i&&n.add(t)})),e.fmtp.forEach((e=>{let{payload:t,config:i}=e,r=i.match(/apt=(\d+)/);r&&r[1]&&n.has(Number(r[1]))&&n.add(t)}));let r=e=>{let{payload:t}=e;return!n.has(t)};e.rtp=e.rtp.filter(r),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(r),e.fmtp=e.fmtp.filter(r),e.payloads=null==(i=e.payloads)?void 0:i.split(" ").filter((e=>!n.has(Number(e)))).join(" ")}})),gV(t)}(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=function(e){let t=fV(e);return t.media.forEach((e=>{e.type===MD.AUDIO&&e.fmtp.forEach((e=>{e.config+=";sprop-stereo=1;stereo=1"}))})),gV(t)}(t.sdp),this._sdpSemantics===hN&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)}))}onSubscribeResult(e){return ab(this,null,(function*(){let{code:t,message:i=""}=e&&e.data||{},{type:n,sdp:r}=e&&e.data&&e.data.data||{};if(t===mN)throw new gb({code:_b.NOT_SUPPORTED_H264,message:XO({key:YO.NOT_SUPPORTED_H264DECODE})});try{if(0!==t)throw new gb({code:t,message:XO({key:YO.EXCHANGE_SDP_FAILED,data:{errMsg:i}})});this._log.debug("accept remote answer: ".concat(r)),yield this._peerConnection.setRemoteDescription({type:n,sdp:r}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=e=>{this._emitter.emit("sei-message",eb(ZC({},e),{userId:this.userId}))}),this.updateSSRC(r)}catch(o){throw this._log.error(o),o}}))}updateSSRC(e){try{fV(e).media.forEach((e=>{if(e.ssrcs)if(e.type===MD.AUDIO){let t=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(WD)}));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(WD)})),i=e.ssrcs.find((e=>{var t;return null==(t=e.value)?void 0:t.includes(JD)}));t&&(this.ssrc.video=Number(t.id)),i&&(this.ssrc.auxiliary=Number(i.id))}}))}catch(sN){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return ab(this,null,(function*(){if(!(sb(EV.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(sN){let t=eO(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}},SV=EV;rb([oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],SV.prototype,"subscribe",1),rb([rM(mV.prototype.afterConnect),nM(mV.prototype.beforeConnect)],SV.prototype,"connect",1);var IV=SV,vV={voiceActivityDetection:!1},yV=class extends mV{constructor(e){super(eb(ZC({},e),{isUplink:!0})),ob(this,"localMainAudioTrack",null),ob(this,"localMainVideoTrack",null),ob(this,"localAuxAudioTrack",null),ob(this,"localAuxVideoTrack",null),ob(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),ob(this,"_isPublishingAux",!1),ob(this,"_publishingLocalAudioTrack"),ob(this,"_publishingLocalVideoTrack"),ob(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}),ob(this,"_audioManager"),this._audioManager=e.audioManager}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(vw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===MD.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e;let o;t._peerConnection||t.initialize(),i&&(t._publishingLocalAudioTrack=i),n&&(t._publishingLocalVideoTrack=n),t._isPublishingAux=r,n&&!r&&n.small&&(o=t._room.videoManager.smallTrack),t.sendMediaSettings(),yw()?yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:o,isAuxiliary:r}):yield t.publishByAddTrack({localAudioTrack:i,localVideoTrack:n,smallTrack:o}),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r?(n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i)):(n&&(t.localMainVideoTrack=n),i&&(t.localMainAudioTrack=i)),null==(e=t._sei)||e.handleEncodedStreams(),t.installTrackMuteEvents(i,n),t.sendMutedFlag()}()}))}publishByTransceiver(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r,isAuxiliary:o}=e;return function*(){t._log.info("publish by transceiver");let e=new MediaStream,s=null==n?void 0:n.outMediaTrack,a=t._audioManager.mixedAudioTrack;a&&e.addTrack(a),s&&e.addTrack(s);let c=t._peerConnection.getTransceivers();if(0===c.length)t._peerConnection.addTransceiver(a||MD.AUDIO,{direction:LD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o?MD.VIDEO:s||MD.VIDEO,{direction:LD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(r||MD.VIDEO,{direction:LD.SENDONLY,streams:[e]}),t._peerConnection.addTransceiver(o&&s||MD.VIDEO,{direction:LD.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:MD.AUDIO})),s){let i=o?3:1;yield c[i].sender.replaceTrack(s),yield t.setBandwidth({bandwidth:n.profile.bitrate,type:MD.VIDEO,videoType:o?MD.AUXILIARY:MD.BIG}),e.push(i),r&&(yield c[2].sender.replaceTrack(r),yield t.setBandwidth({bandwidth:n.small.bitrate,type:MD.VIDEO,videoType:MD.SMALL}),e.push(2))}yield t.setTransceiverDirection(LD.SENDONLY,e),yield t.doPublishChange(),null==n||n.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==n||n.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()}))}publishByAddTrack(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,smallTrack:r}=e;return function*(){t._log.info("publish by addtrack");let e=null==n?void 0:n.outMediaTrack,o=t._audioManager.mixedAudioTrack;if(t._peerConnection&&"new"!==t._peerConnection.connectionState)return o&&(yield t.addTrack(i)),void(e&&(yield t.addTrack(n)));let s=new MediaStream;if(o&&s.addTrack(o),e&&s.addTrack(e),o&&t._peerConnection.addTrack(o,s),e&&(t._peerConnection.addTrack(e,s),r)){let e=new MediaStream;e.addTrack(r),t._peerConnection.addTrack(r,e)}yield t.connect()}()}))}enableSmall(e){return ab(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(LD.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(LD.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 ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){if(!vw())return i&&i.outMediaTrack&&!n&&t.localMainVideoTrack?(yield t.removeTrack(i),void(t.localMainAudioTrack=null)):n&&n.outMediaTrack&&!i&&t.localMainAudioTrack?(yield t.removeTrack(n),void(t.localMainVideoTrack=null)):(yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),void t.emitConnectionStateChangedEvent("DISCONNECTED",n));let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb(ZC({},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=eb(ZC({},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(LD.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:bx,data:t,responseCommand:Sx.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:kx,commandDesc:"unpublish",responseCommand:Sx.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===_b.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),kw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Bx,data:this._mediaSettings,responseCommand:Sx.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ab(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?MD.AUXILIARY:MD.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),yw()?yield this.addTrackByTransceiver(e,i):yield this.addTrackBySender(e)}))}addTrackByTransceiver(e,t){return ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===MD.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===LD.INACTIVE&&(yield this.setTransceiverDirection(LD.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}addTrackBySender(e){return ab(this,null,(function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;vw()&&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)}let n=t.kind===MD.VIDEO?t:this._audioManager.mixedAudioTrack;if(n&&this._peerConnection.addTrack(t,new MediaStream([n])),t.kind===MD.VIDEO&&e instanceof pM&&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===pN||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=fV(e);for(let i=0;i<t.media.length;i++)if(0===Number(t.media[i].mid)&&t.media[i].type===MD.VIDEO)return!0;return!1}removeSender(e){let t=null;vw()&&(t=this._peerConnection.getTransceivers().find((t=>t.sender&&t.sender.track===e.track))),this._peerConnection.removeTrack(e),t&&iO(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return ab(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?MD.AUXILIARY:MD.MAIN," stream")),yw()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)}))}removeTrackByTransceiver(e,t){return ab(this,null,(function*(){if(!e.outMediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===MD.AUDIO)this._audioManager.mixedAudioTrack||(yield i[0].sender.replaceTrack(null));else{let n=t?3:1;yield i[n].sender.replaceTrack(null),1===n&&e.small&&(yield i[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(LD.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ab(this,null,(function*(){if(!Ub)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(LD.INACTIVE,"|").concat(LD.RECVONLY,"|").concat(LD.SENDONLY,")")))&&o++,t.includes(o)){if(e===LD.INACTIVE&&i.includes("a=".concat(LD.RECVONLY)))return n=!0,"a=".concat(e);if(e===LD.SENDONLY&&i.includes("a=".concat(LD.INACTIVE)))return n=!0,"a=".concat(LD.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}removeTrackBySender(e){return ab(this,null,(function*(){if(!e.outMediaTrack)return;if(e.kind===MD.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===MD.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((e=>{e.track&&e.track.kind===MD.VIDEO&&this.removeSender(e)}))),yield this.updateOffer("remove",e.outMediaTrack)}))}replaceTrack(e){return ab(this,null,(function*(){var t;let i,n=null==(t=this._peerConnection)?void 0:t.getSenders();if(!n||0===n.length||!e.mediaTrack)return;if(i=yw()?e.kind===MD.AUDIO?n[0]:n[1]:n.find((t=>t.track&&t.track.kind===e.kind)),!i)return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(e.kind," track on ").concat(r?MD.AUXILIARY:MD.MAIN," stream")),e.kind===MD.AUDIO?yield i.replaceTrack(this._audioManager.mixedAudioTrack):e.kind===MD.VIDEO&&(r?n[3]&&(yield n[3].replaceTrack(e.outMediaTrack)):yield i.replaceTrack(e.outMediaTrack))}))}updateOffer(e,t){return ab(this,null,(function*(){try{let i=yield this._peerConnection.createOffer(vV);Ub&&i.sdp&&(i.sdp=this.setSDPDirection(i.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(i);let n=this.updateMediaSettings(),r={action:e,trackId:t.id,kind:t.kind===MD.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(r.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:Ix,data:r,responseCommand:Sx.UPDATE_OFFER_RESULT,timeout:dN,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(aD){throw this._log.error(aD),aD}}))}setBandwidth(e){return ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r,sdp:o}=e;return function*(){if(!bw())return o?n===MD.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i):void 0;let e,s=t._peerConnection.getSenders();if(yw()){let t=0;n===MD.VIDEO&&(t=r===MD.SMALL?2:r===MD.AUXILIARY?3:1),e=s[t]}else e=s.find((e=>e.track&&e.track.kind===n));if(e){let s=e.getParameters();(!s.encodings||0===s.encodings.length)&&(s.encodings=[{}]),s.encodings[0].maxBitrate=1e3*i;try{return yield e.setParameters(s),t._log.info("".concat(r||"").concat(n," bandwidth ").concat(i," kbps")),o}catch(a){if(t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(a)),o)return n===MD.VIDEO?t.updateVideoBandwidthRestriction(o,i,r):t.updateAudioBandwidthRestriction(o,i)}}return o}()}))}updateVideoBandwidthRestriction(e,t,i){let n="AS";Ub&&(n="TIAS",t*=1e3);let r=0,o=-1;return i===MD.SMALL?r=1:i===MD.AUXILIARY&&(r=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(e=>(o+=1,o===r?"".concat(e,"b=").concat(n,":").concat(t,"\r\n"):e)))}updateAudioBandwidthRestriction(e,t){let i="AS";return Ub&&(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 ab(this,null,(function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(sD){throw this.closePeerConnection(!0),this.uninstallEvents(),sD}}))}exchangeSDP(){return ab(this,null,(function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(sD){throw sD}}))}createOffer(){return ab(this,null,(function*(){try{let e=yield this._peerConnection.createOffer(vV);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(sD){throw sD}}))}doExchangeSDP(){let e={command:Cx,responseCommand:Sx.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof _M||this.localAuxVideoTrack instanceof _M,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then((e=>{let{code:t,message:i,data:n}=e.data;return 0===t?this.acceptAnswer(n):this.checkPublishResultCode(t,i)}))}setSDPDirection(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",n=fV(e);return n.media.forEach((e=>{("all"===i||e.type===i)&&(e.direction=t)})),gV(n)}acceptAnswer(e){return ab(this,null,(function*(){var t,i,n,r,o;try{let s;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let e=(null==(t=this._publishingLocalVideoTrack)?void 0:t.profile.bitrate)||(null==(i=this.localMainVideoTrack)?void 0:i.profile.bitrate),o=(null==(n=this._publishingLocalAudioTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainAudioTrack)?void 0:r.profile.bitrate);if(e){let t=this._isPublishingAux?MD.AUXILIARY:MD.BIG;s=yield this.setBandwidth({bandwidth:e,type:MD.VIDEO,sdp:s,videoType:t})}o&&(s=yield this.setBandwidth({bandwidth:o,type:MD.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:MD.VIDEO,videoType:MD.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,n;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(i=this.localMainVideoTrack)||!i.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)};this._log.info("send muted state: ".concat(JSON.stringify(r))),this._signalChannel.send(Rx,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return ab(this,null,(function*(){if(!(sb(yV.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:kx,responseCommand:Sx.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(sN){let t=eO(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)&&FO.emit(HO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{fV(e).media.forEach(((e,t)=>{if(e.type===MD.AUDIO){let t=e.ssrcs&&e.ssrcs[0];t&&(this.ssrc.audio=Number(t.id))}else{if(this._sdpSemantics===pN&&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(sN){}}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MD.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===MD.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===MD.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===MD.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===MD.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===mN?(this._log.error(zO.NOT_SUPPORTED_H264ENCODE),new gb({code:_b.NOT_SUPPORTED_H264,message:XO({key:YO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:_b.UNKNOWN,message:XO({key:YO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Sx.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}},AV=yV;rb([oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this._emitter.off("closed",r),n(new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.CONNECTION_ABORTED,data:e})}))};this._emitter.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this._emitter.off("closed",r)}))}))}))],AV.prototype,"publish",1),rb([rM(mV.prototype.afterConnect),nM(mV.prototype.beforeConnect)],AV.prototype,"connect",1);var RV=AV,CV=class{constructor(e,t){this.room=e,ob(this,"_log"),ob(this,"_prevReportTime"),ob(this,"_prevReport",{}),ob(this,"_prevEncoderImplementation"),ob(this,"_prevQualityLimitationReason"),ob(this,"_prevAuxQualityLimitationReason"),ob(this,"_prevDecoderImplementationMap",new Map),ob(this,"totalBytesSent",0),ob(this,"totalBytesReceived",0),ob(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 ab(this,null,(function*(){let t={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),n=e.getSSRC();if(i)try{if((this._spcStats||(yield i.getStats())).forEach((i=>{var r;if("outbound-rtp"===i.type)if((i.mediaType||i.kind)===MD.VIDEO){let r,o;if(i.ssrc===n.video?(r=MD.VIDEO,o=e.localMainVideoTrack):i.ssrc===n.small?r=MD.SMALL:i.ssrc===n.auxiliary&&(o=e.localAuxVideoTrack,r=MD.AUXILIARY),!r)return;t[r].bytesSent=i.bytesSent,t[r].packetsSent=i.packetsSent,t[r].framesEncoded=i.framesEncoded,nO(i.keyFramesEncoded)||(t[r].keyFramesEncoded=i.keyFramesEncoded),nO(i.nackCount)||(t[r].nackCount=i.nackCount),nO(i.pliCount)||(t[r].pliCount=i.pliCount),nO(i.retransmittedPacketsSent)||(t[r].retransmittedPacketsSent=i.retransmittedPacketsSent),nO(i.totalEncodeTime)||(t[r].totalEncodeTime=i.totalEncodeTime),nO(i.totalPacketSendDelay)||(t[r].totalPacketSendDelay=i.totalPacketSendDelay),i.ssrc===n.video?(!nO(i.encoderImplementation)&&this._prevEncoderImplementation!==i.encoderImplementation&&(this._log.info("encoderImplementation change to ".concat(i.encoderImplementation)),this._prevEncoderImplementation=i.encoderImplementation),!nO(i.qualityLimitationReason)&&0!==i.bytesSent&&this._prevQualityLimitationReason!==i.qualityLimitationReason&&(this._log.info("qualityLimitationReason change to ".concat(i.qualityLimitationReason)),this._prevQualityLimitationReason=i.qualityLimitationReason)):i.ssrc===n.auxiliary&&!nO(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?pw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesSent=i.bytesSent):"media-source"===i.type&&(i.kind===MD.AUDIO?(t.audio.audioLevel=i.audioLevel||0,t.audio.totalAudioEnergy=i.totalAudioEnergy||0):i.kind===MD.VIDEO&&(i.trackIdentifier===e.getVideoTrackId(MD.VIDEO)?t.video.fpsCapture=i.framesPerSecond:i.trackIdentifier===e.getVideoTrackId(MD.AUXILIARY)?t.auxiliary.fpsCapture=i.framesPerSecond:t.small.fpsCapture=i.framesPerSecond));if(!nO(i.audioLevel)&&(null==(r=e.localMainAudioTrack)?void 0:r.mediaTrack)&&i.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(t.audio.audioLevel=i.audioLevel||0),!nO(i.frameWidth)){let r=MD.SMALL;i.trackIdentifier===e.getVideoTrackId(MD.VIDEO)||i.ssrc===n.video?r=MD.VIDEO:(i.trackIdentifier===e.getVideoTrackId(MD.AUXILIARY)||i.ssrc===n.auxiliary)&&(r=MD.AUXILIARY),t[r].frameWidth=i.frameWidth,t[r].frameHeight=i.frameHeight,t[r].framesSent=i.framesSent}})),e.localMainAudioTrack){let i=e.localMainAudioTrack.getInternalAudioLevel();t.audio.micAudioLevel=i,0===t.audio.audioLevel&&(t.audio.audioLevel=i)}this.totalBytesSent||(this.totalBytesSent+=t.audio.bytesSent+t.video.bytesSent+t.auxiliary.bytesSent)}catch(r){this._log.warn("failed to getStats on sender connection ".concat(r))}return t}))}getReceiverStats(e){return ab(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,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},i=e.getPeerConnection();if(i)try{let{ssrc:n}=e,{muteState:r,subscribeState:o}=e;(this._spcStats||(yield i.getStats())).forEach((i=>{if("inbound-rtp"===i.type)if((i.mediaType||i.kind)===MD.AUDIO){if(i.ssrc!==n.audio||!r.hasAudio)return;t.audio.packetsReceived=i.packetsReceived,t.audio.bytesReceived=i.bytesReceived,t.audio.packetsLost=i.packetsLost,i.insertedSamplesForDeceleration&&(t.audio.insertedSamplesForDeceleration=i.insertedSamplesForDeceleration),i.removedSamplesForAcceleration&&(t.audio.removedSamplesForAcceleration=i.removedSamplesForAcceleration);let{remoteAudioTrack:o}=e;o.stat.packetsReceived=i.packetsReceived,o.stat.bytesReceived=i.bytesReceived,o.stat.packetsLost=i.packetsLost,i.jitterBufferDelay&&(o.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)),t.hasAudio=!0}else{if(Ub&&0===i.bytesReceived)return;let s;i.ssrc===n.video&&r.hasVideo&&(t.video.packetsReceived=i.packetsReceived,t.video.bytesReceived=i.bytesReceived,t.video.packetsLost=i.packetsLost,t.video.framesReceived=i.framesReceived,t.video.framesDecoded=i.framesDecoded,t.video.fpsDecoded=i.framesPerSecond,t.hasVideo=!0,s=e.remoteVideoTrack,r.hasSmall&&o.smallVideo&&(t.isSmallSubscribed=!0),i.decoderImplementation&&(!this._prevDecoderImplementationMap.has(t.userId)||this._prevDecoderImplementationMap.get(t.userId)!==i.decoderImplementation)&&(this._log.info("".concat(t.userId," decoderImplementation change to ").concat(i.decoderImplementation)),this._prevDecoderImplementationMap.set(t.userId,i.decoderImplementation))),i.ssrc===n.auxiliary&&r.hasAuxiliary&&(t.auxiliary.packetsReceived=i.packetsReceived,t.auxiliary.bytesReceived=i.bytesReceived,t.auxiliary.packetsLost=i.packetsLost,t.auxiliary.framesReceived=i.framesReceived,t.auxiliary.framesDecoded=i.framesDecoded,t.auxiliary.fpsDecoded=i.framesPerSecond,s=e.remoteAuxiliaryTrack,t.hasAuxiliary=!0),s&&(s.stat.packetsReceived=i.packetsReceived,s.stat.bytesReceived=i.bytesReceived,s.stat.packetsLost=i.packetsLost,s.stat.framesReceived=i.framesReceived,s.stat.framesDecoded=i.framesDecoded,i.jitterBufferDelay&&(s.stat.jitterBufferDelay=Math.floor(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3)))}else"candidate-pair"===i.type&&pw(i)&&oO(i.currentRoundTripTime)&&(t.rtt=Math.floor(1e3*i.currentRoundTripTime),this.totalBytesReceived=i.bytesReceived);nO(i.frameWidth)||((i.trackIdentifier===e.getMainStreamVideoTrackId()||i.ssrc===n.video)&&(t.video.frameWidth=i.frameWidth,t.video.frameHeight=i.frameHeight,e.remoteVideoTrack.stat.frameWidth=i.frameWidth,e.remoteVideoTrack.stat.frameHeight=i.frameHeight),(i.trackIdentifier===e.getAuxStreamVideoTrackId()||i.ssrc===n.auxiliary)&&(t.auxiliary.frameWidth=i.frameWidth,t.auxiliary.frameHeight=i.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=i.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=i.frameHeight)),!nO(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(aD){this._log.warn("failed to getStats on receiver connection ".concat(aD))}return t}))}getStats(e,t){return ab(this,null,(function*(){let i={},n=[];if(this.room.singlePC){let e=this.room.singlePC.getPeerConnection();if(!e)return{senderStats:i,receiverStats:n};let t=yield e.getStats(),r=[],o=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);t.forEach((e=>o.has(e.type)&&r.push(e))),this._spcStats=r}e&&(i=yield this.getSenderStats(e));for(let[e,r]of t){let e=yield this.getReceiverStats(r);n.push(e)}return{senderStats:i,receiverStats:n}}))}getDifferenceValue(e,t){if(FP(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:n}=e;if(!FP(t.senderStats)){let e={uint32_audio_level:t.senderStats.audio.audioLevel*VN,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*VN);let n=[];if(t.senderStats.video.bytesSent){let e={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};n.push(e)}if(t.senderStats.small.bytesSent){let e={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};n.push(e)}if(t.senderStats.auxiliary.bytesSent){let e={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};n.push(e)}let r={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:e,msg_video_status:n,msg_network_status:r}}let{statInterval:r}=this;i.msg_down_stream_info=[],t.receiverStats.forEach((e=>{let t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){let i={uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=i}if(e.hasVideo){let i=n.get("".concat(e.userId,"_").concat(KD)),r=i?i.duration:0,o={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.video.framesDecoded};t.msg_video_status.push(o)}if(e.hasAuxiliary){let i=n.get("".concat(e.userId,"_").concat(YD)),r=i?i.duration:0,o={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:r,uint32_video_dec_fps:e.auxiliary.framesDecoded};t.msg_video_status.push(o)}i.msg_down_stream_info.push(t)}));let o=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(i)),i.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let e=o.msg_up_stream_info.msg_audio_status,t=i.msg_up_stream_info.msg_audio_status;if(0===e.uint32_audio_codec_bitrate)t.uint32_audio_codec_bitrate=0;else{let n=this.getDifferenceValue(e.uint32_audio_codec_bitrate,t.uint32_audio_codec_bitrate);t.uint32_audio_codec_bitrate=Math.round(8*n/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=t.uint32_audio_codec_bitrate}}let s=o.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach((e=>{let t=s.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);let n=0,o=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,o=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);let c=this.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*c/r),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(this.getDifferenceValue(o,e.uint32_video_enc_fps)/r),e.uint32_video_codec_fps=Math.round(this.getDifferenceValue(a,e.uint32_video_codec_fps)/r),mk&&115===wk()&&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),nO(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(this.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),nO(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(this.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),nO(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(this.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),nO(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(this.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),nO(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(this.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/r)),nO(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(this.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/r))}));let a=i.msg_down_stream_info,c=o.msg_down_stream_info;return a.forEach((e=>{let t=c.find((t=>t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid));if(t){if(FP(e.msg_audio_status)||FP(t.msg_audio_status))e.msg_audio_status={};else{let i=e.msg_audio_status,n=t.msg_audio_status;i.uint32_audio_origin_lost=this.getDifferenceValue(n.uint32_audio_origin_lost,i.uint32_audio_origin_lost),i.uint32_audio_receive=this.getDifferenceValue(n.uint32_audio_receive,i.uint32_audio_receive),i.uint32_audio_receive+=i.uint32_audio_origin_lost;let o=this.getDifferenceValue(n.uint32_audio_codec_bitrate,i.uint32_audio_codec_bitrate);i.uint32_audio_codec_bitrate=Math.round(8*o/r),i.uint32_audio_total_bitrate=Math.round(8*o/r)}if(e.msg_video_status&&t.msg_video_status){let i=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((e=>i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)))),e.msg_video_status.forEach((e=>{let t=i.find((t=>t.uint32_video_stream_type===e.uint32_video_stream_type)),n=t.uint32_video_receive,o=t.uint32_video_origin_lost,s=t.uint32_video_codec_bitrate,a=t.uint32_video_receive_fps,c=t.uint32_video_dec_fps;e.uint32_video_origin_lost=this.getDifferenceValue(o,e.uint32_video_origin_lost),e.uint32_video_receive=this.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;let l=this.getDifferenceValue(s,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*l/r);let d=this.getDifferenceValue(a,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(d/r),e.uint32_video_dec_fps=Math.round(this.getDifferenceValue(c,e.uint32_video_dec_fps)/r)}))}}})),i}getStatsReport(e){return ab(this,arguments,(function(e){var t=this;let{uplinkConnection:i,downlinkConnections:n,freezeMap:r}=e;return function*(){let e={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield t.getStats(i,n);return"{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(e))),t.prepareReport({stats:o,report:e,freezeMap:r}),t._prevReportTime=Date.now(),e}()}))}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}},bV=nb(cb()),kV=class extends bV.default{constructor(e){let{signalChannel:t,room:i}=e;super(),ob(this,"_room"),ob(this,"_signalChannel"),ob(this,"_log"),ob(this,"_uplinkRTT",0),ob(this,"_uplinkLoss",0),ob(this,"_downlinkRTT",0),ob(this,"_downlinkLoss",0),ob(this,"_downlinkPrevStatMap",new Map),ob(this,"_downlinkLossAndRTTMap",new Map),ob(this,"_interval",-1),ob(this,"_uplinkNetworkQuality",0),ob(this,"_downlinkNetworkQuality",0),this._room=i,this._signalChannel=t,this._log=GO.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(Sx.UPLINK_NETWORK_STATS,(e=>{this.handleUplinkNetworkQuality(e)})),this._signalChannel.on(_x,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var t,i;if(0!==e.data.code)return;let n=e.data.data;if(n.delay&&this.updateDelay(n.delay),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this._uplinkLoss=0,void(this._uplinkRTT=0);let r=null==(i=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:i.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r))return this.uplinkNetworkQuality=6,this._uplinkLoss=0,void(this._uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,s=n.recvAudPkg+n.recvVidPkg,a=o-s;0===o&&0===s||(this._uplinkLoss=a<=0?0:Math.round(a/o*100),this._uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return ab(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)===iN.CONNECTED}));if(e.filter((e=>this.isPeerConnectionDisconnected(e.getPeerConnection()))).length===e.length)return void(this.downlinkNetworkQuality=6);for(let r=0;r<t.length;r++){let e=t[r].getPeerConnection();if(!e)return;let{rtt:i,totalPacketsLost:n,totalPacketsReceived:o}=yield this.getStat(e);if(!this._downlinkPrevStatMap.has(e)){this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o});continue}let s=0,a=this._downlinkPrevStatMap.get(e),c=n-a.totalPacketsLost,l=o-a.totalPacketsReceived;s=c<=0||l<0?0:Math.round(c/(c+l)*100),this._downlinkPrevStatMap.set(e,{totalPacketsLost:n,totalPacketsReceived:o}),this._downlinkLossAndRTTMap.set(e,{rtt:i,loss:s,userId:t[r].getUserId(),audioDelay:t[r].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[r].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach((e=>{this.isPeerConnectionDisconnected(e)&&(this._downlinkPrevStatMap.delete(e),this._downlinkLossAndRTTMap.delete(e))})),0===this._downlinkLossAndRTTMap.size)return;let{rtt:i,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=i,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,i)}))}getStat(e){return ab(this,null,(function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Sw())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&&oO(e.currentRoundTripTime)&&(t.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===MD.AUDIO||e.mediaType===MD.VIDEO)&&(t.totalPacketsLost+=e.packetsLost,t.totalPacketsReceived+=e.packetsReceived)}));return t}catch(n){return t}}))}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((e=>{t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((i=>{t[i]=Math.round(t[i]/e.length)}))),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){"DISCONNECTED"===e.state?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(e){let{state:t}=e;"DISCONNECTED"===t?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==iN.DISCONNECTED&&e.connectionState!==iN.FAILED&&e.connectionState!==iN.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=Qw.run(wN,(()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];FO.emit(HO.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(kV.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&&(Qw.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach((e=>{let{srcTinyId:i,videoDelay:n,audioDelay:r}=e,o=t.get(i);if(o){let e=this._room.remotePublishedUserMap.get(o);null==e||e.setDelay({videoDelay:n,audioDelay:r})}}))}},DV=kV;ob(DV,"EVENT_NETWORK_QUALITY","0");var NV=class{constructor(e){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._apiSuccessRateMap=new Map,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=GO.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((e=>{e.startsWith("handle")&&iO(this[e])&&(this[e]=function(e){let{fn:t,context:i}=e;return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];let o=t.apply(i,n);return uO(o)?o.catch((e=>GO.error("".concat(t.name,"() error observed ").concat(e)))):o}catch(sN){GO.error("".concat(t.name,"() error observed ").concat(sN))}}}({fn:this[e],context:this}))})),this.initData(),this.installEvents(),this._intervalId=Qw.run(wN,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:rD,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:kD[GN()],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,this._apiSuccessRateMap.clear(),$k().then((e=>{this._basicInfo.string_os_version=tD(),e&&(this._basicInfo.string_device_name=e.model)}))}addEvent(e,t){return this._eventMap.set(e,t),FO.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(HO.JOIN_START,this.handleJoinStart).addEvent(HO.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(HO.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(HO.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(HO.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(HO.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(HO.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(HO.JOIN_FAILED,this.handleJoinFailed).addEvent(HO.LEAVE_START,this.handleLeaveStart).addEvent(HO.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(HO.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(HO.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(HO.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(HO.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(HO.PUBLISH_START,this.handlePublishStart).addEvent(HO.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(HO.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(HO.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(HO.PLAY_TRACK_START,this.handlePlayStart).addEvent(HO.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(HO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,type:n}=e;!dO(t)||!this.hitTest(t.room)||"PLAYING"===i&&(n===MD.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))})).addEvent(HO.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(HO.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(HO.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(HO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let r=i.hasAudio||i.hasVideo||i.hasSmall,o=i.hasAuxiliary,s=n.hasAudio||n.hasVideo||n.hasSmall,a=n.hasAuxiliary;!r&&s&&this.handleRemoteStreamAdded(n.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(n.userId,"auxiliary")})).addEvent(HO.API_SUCCESS_RATE,this.handleAPISuccessRate).addEvent(HO.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)=>FO.off(t,e))),this._eventMap.clear()}destroy(){this.uninstallEvents(),Qw.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&&(nO(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),nO(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),nO(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(e){let{room:t,detailCost:i}=e;if(this.hitTest(t)&&i){let{totalCost:e,local:t,dns:n,tcp:r,tls:o,request:s,response:a}=i;this._pathJoinRoom.int32_schedule_cost=e,this._pathJoinRoom.int32_schedule_local=t,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=r,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=s,this._pathJoinRoom.int32_schedule_response=a}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof gb?Number(i.getExtraCode()||i.getCode()):_b.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}handleJoinFailed(e){let{room:t,error:i}=e;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=i.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((()=>{this.report()})))}handleReceivedPublishUserList(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;!this.hitTest(t)||0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(e,t){var i;let n="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(n)){let r={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:eb(ZC({},PV),{msg_user_info:new MV({userId:e,tinyId:null==(i=this._room.remotePublishedUserMap.get(e))?void 0:i.tinyId,role:20})})};r.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(n,r)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:n,subscribeState:r}=e;if(!this.hitTest(t))return;let{userId:o,tinyId:s,role:a}=i,c=new MV({userId:o,tinyId:s,role:"anchor"===a?20:21}),l=Date.now(),d="".concat(o,"_").concat(n),u=this._remoteStreamStatMap.get(d);u&&0===u.subscribeStartTime&&(u.subscribeStartTime=l),"main"===n?(i.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),i.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):i.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:l})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:n}=e;if(this.hitTest(t)){let e="".concat(i.userId,"_").concat(n),t=this._remoteStreamStatMap.get(e);t&&0===t.subscribedTime&&(t.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._remoteStreamStatMap.get(i);0===(null==n?void 0:n.playStreamTime)&&(n.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),n=this._pathMainVideoMap.get(i);n&&0===n.statsToReport.uint64_combine_first_frame_time&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),n=this._pathMainVideoMap.get(t),r=this._remoteStreamStatMap.get(t);if(n&&(0===n.statsToReport.uint64_render_first_frame_time&&(n.statsToReport.uint64_render_first_frame_time=i),r)){let{statsToReport:e,playStreamTime:t,subscribedTime:o}=r;0===e.uint32_video_render_first&&t-o<=100&&(e.uint32_video_render_first=i-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(t);if(o&&r){let{statsToReport:e,playStreamTime:t,subscribedTime:n}=r;0===e.uint32_video_render_first&&t-n<=100&&(e.uint32_video_render_first=i-o.sendSubscribeCMDTime)}}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&0===i.statsToReport.uint64_play_first_frame_time&&(i.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(e){this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((e=>{let{rtt:t,loss:i,userId:n,videoDelay:r,audioDelay:o}=e,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(s)s.totalRTT+=t,s.totalLoss+=i,r&&(s.totalVideoDelay=(s.totalVideoDelay||0)+r,s.videoDelayCount=(s.videoDelayCount||0)+1),o&&(s.totalAudioDelay=(s.totalAudioDelay||0)+o,s.audioDelayCount=(s.audioDelayCount||0)+1),s.count++;else{let e,s,a,c;r&&(s=r,a=1),o&&(e=o,c=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:t,totalLoss:i,count:1,totalAudioDelay:e,totalVideoDelay:s,audioDelayCount:c,videoDelayCount:a})}})))}handleHeartbeatStats(e){if(this.hitTest(e.room)){let{msg_up_stream_info:t,msg_down_stream_info:i}=e.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:e,uint32_video_enc_fps:i,uint32_video_width:n,uint32_video_height:r}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=e,this._localStreamStat.totalVideoFPS+=i,this._localStreamStat.totalVideoWidth+=n,this._localStreamStat.totalVideoHeight+=r,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:e}=t.msg_audio_status;Math.floor(e/VN*100)>0&&(this._localStreamStat.totalAudioLevel+=e/VN,this._localStreamStat.audioLevelCount++)}i.forEach((e=>{let{msg_user_info:t,msg_audio_status:i,msg_video_status:n}=e,r=t.str_identifier,o=this._room.remotePublishedUserMap.get(r);if(n.forEach((e=>{let t=2===e.uint32_video_stream_type,i=7===e.uint32_video_stream_type,n="".concat(r,"_").concat(t?"main":"auxiliary"),s=this._remoteStreamStatMap.get(n);if(s&&(t&&(null==o?void 0:o.remoteVideoTrack.isSubscribed)||i&&(null==o?void 0:o.remoteAuxiliaryTrack))){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);let i=t?o.remoteVideoTrack:o.remoteAuxiliaryTrack;i.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=i.stat.jitterBufferDelay),i.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(i.stat.framesDecoded/i.stat.framesReceived*XC(10,6)))}})),i){let e="".concat(r,"_","main"),t=this._remoteStreamStatMap.get(e);this._remoteStreamStatMap.has(e)&&t&&(null==o?void 0:o.remoteAudioTrack.isSubscribed)&&(t.totalAudioBitrate+=i.uint32_audio_codec_bitrate,t.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(t.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(i.uint32_audio_level/VN*100)>0&&(t.totalAudioLevel+=i.uint32_audio_level/VN,t.audioLevelCount++))}}))}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof gb?i.getExtraCode()||i.getCode():_b.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate(e){let{room:t,apiName:i,error:n,cost:r}=e;if(!this.hitTest(t))return;let o=LV[i],s={uint32_function_request_type:o,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(n){let e=n.extraCode||n.code||_b.UNKNOWN;$w.logFailedEvent({eventType:i,code:e,userId:this._room.userId,error:n});let t={int32_error_code:e,error_count:1};s.msg_error_code.push(t)}else oO(r)&&($w.logSuccessEvent({eventType:i,userId:this._room.userId}),s.uint32_avg_value=r,s.uint32_max_value=r,s.uint32_success_count=1);let a=this._apiSuccessRateMap.get(o);a?(a.uint32_success_count+s.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+s.uint32_avg_value)/(a.uint32_success_count+s.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,s.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+s.uint32_success_count,s.msg_error_code.forEach((e=>{let t=a.msg_error_code.find((t=>t.int32_error_code===e.int32_error_code));t?t.error_count+=1:a.msg_error_code.push(e)}))):this._apiSuccessRateMap.set(o,s)}hasVideoFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&UD))>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&HD))>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex((t=>t.userId===e&&t.flag&BD))>=0}hitTest(e){return e===this._room}checkStorage(){return ab(this,null,(function*(){try{let e=JO.getItem(this._storageKey);e&&(yield this.upload(e),JO.deleteItem(this._storageKey))}catch(QM){this._log.warn(QM)}}))}setStorage(){this.prepareReport();let e=this.getReportData();0!==e.msg_path_enter_room.uint64_start_time&&JO.setItem(this._storageKey,e)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach(((e,t)=>{let{userId:i}=e,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(n){let{totalLoss:t,count:i,audioDelayCount:r,videoDelayCount:o,totalAudioDelay:s,totalVideoDelay:a}=n;e.statsToReport.uint32_avg_down_loss=Math.floor(t/i),r&&s&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(s/r),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),o&&a&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(a/o))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:r}=this._room;r&&(e.statsToReport.uint32_audio_play_time=r.getDuration(t,MD.AUDIO),e.statsToReport.uint32_video_play_time=r.getDuration(t,MD.VIDEO)),e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,wV);let{badCaseDetector:o}=this._room,{dataFreeze:s,count:a}=o.getDataFreezeDuration(t),{renderFreeze:c}=o.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=a,e.statsToReport.uint32_video_block_time=Math.min(s,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),o.isBlackStream(t)&&0===e.statsToReport.uint32_video_avg_fps?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0,(0===e.subscribeStartTime||e.subscribeStartTime-e.streamAddedTime>100||0===e.playStreamTime)&&(this._pathMainAudioMap.delete(t),this._pathMainVideoMap.delete(t),e.statsToReport.uint32_video_render_first=0)})),this._pathMainAudioMap.forEach(((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>wV&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+wV):this._pathMainAudioMap.delete(t)})),this._pathMainVideoMap.forEach(((e,t)=>{this.hasVideoFlag(e.userId)?e.statsToReport.uint64_render_first_frame_time-e.statsToReport.uint64_start_enter_time>wV&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+wV):this._pathMainVideoMap.delete(t)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>wV&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+wV)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new MV({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:AO(this._signalInfo.relayIp),uint32_client_ip:AO(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(2147483648*Math.random()),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:AO(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){try{this.prepareReport();let e=this.getReportData();this.upload(e),JO.deleteItem(this._storageKey),this.initData()}catch(QM){this._log.warn(QM)}}upload(e){if(Yk&&!Sk||0===e.msg_path_enter_room.uint64_start_time||[mD,_D,fD].findIndex((e=>e===location.host))>=0)return;let t=Number(this._room.sdkAppId),i=BN(t,yD.KEY_POINT),n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(i,JSON.stringify(e))),n||LO({url:i,body:JSON.stringify(e)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}};rb([zx({settings:{timeout:500,retries:3}})],NV.prototype,"upload",1);var OV,wV=5e3,PV={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},MV=class{constructor(e){this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},LV=((OV=LV||{})[OV.enterRoom=50001]="enterRoom",OV[OV.exitRoom=50002]="exitRoom",OV[OV.switchRole=50003]="switchRole",OV[OV.destroy=50004]="destroy",OV[OV.startLocalAudio=50005]="startLocalAudio",OV[OV.updateLocalAudio=50006]="updateLocalAudio",OV[OV.stopLocalAudio=50007]="stopLocalAudio",OV[OV.startLocalVideo=50008]="startLocalVideo",OV[OV.updateLocalVideo=50009]="updateLocalVideo",OV[OV.stopLocalVideo=50010]="stopLocalVideo",OV[OV.startScreenShare=50011]="startScreenShare",OV[OV.updateScreenShare=50012]="updateScreenShare",OV[OV.stopScreenShare=50013]="stopScreenShare",OV[OV.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",OV[OV.startRemoteVideo=50015]="startRemoteVideo",OV[OV.updateRemoteVideo=50016]="updateRemoteVideo",OV[OV.stopRemoteVideo=50017]="stopRemoteVideo",OV[OV.muteRemoteAudio=50018]="muteRemoteAudio",OV[OV.setRemoteAudioVolume=50019]="setRemoteAudioVolume",OV[OV.startMixTranscode=50020]="startMixTranscode",OV[OV.stopMixTranscode=50021]="stopMixTranscode",OV[OV.startPublishCDNStream=50022]="startPublishCDNStream",OV[OV.stopPublishCDNStream=50023]="stopPublishCDNStream",OV[OV.PeerConnectionConnect=50024]="PeerConnectionConnect",OV[OV.PeerConnectionReconnect=50025]="PeerConnectionReconnect",OV[OV.WebsocketConnect=50026]="WebsocketConnect",OV[OV.WebsocketReconnect=50027]="WebsocketReconnect",OV[OV.schedule=50028]="schedule",OV[OV.SPCConnect=50029]="SPCConnect",OV[OV.SPCReconnect=50030]="SPCReconnect",OV[OV.videoCtxGl=50031]="videoCtxGl",OV[OV.videoCtxGlRecover=50032]="videoCtxGlRecover",OV[OV.videoCtx2d=50033]="videoCtx2d",OV[OV["CDNStreaming.startPlugin"]=50034]="CDNStreaming.startPlugin",OV[OV["CDNStreaming.updatePlugin"]=50035]="CDNStreaming.updatePlugin",OV[OV["CDNStreaming.stopPlugin"]=50036]="CDNStreaming.stopPlugin",OV[OV["AIDenoiser.startPlugin"]=50037]="AIDenoiser.startPlugin",OV[OV["AIDenoiser.updatePlugin"]=50038]="AIDenoiser.updatePlugin",OV[OV["AIDenoiser.stopPlugin"]=50039]="AIDenoiser.stopPlugin",OV[OV["AudioMixer.startPlugin"]=50040]="AudioMixer.startPlugin",OV[OV["AudioMixer.updatePlugin"]=50041]="AudioMixer.updatePlugin",OV[OV["AudioMixer.stopPlugin"]=50042]="AudioMixer.stopPlugin",OV),xV=NV,VV=class{constructor(){ob(this,"_startTime"),ob(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){0===this._startTime&&(this._startTime=fO())}stop(){0===this._endTime&&(this._endTime=fO())}getDuration(){return 0===this._endTime?fO()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},UV=class{constructor(e){ob(this,"_room",null),ob(this,"_durationMap"),ob(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(HO.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(HO.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(HO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;var r;let{userId:o}=n;if(!this.hitTest(t))return;i.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(o,"_","main"),MD.AUDIO),i.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(o,"_","main"),MD.VIDEO),i.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(o,"_","auxiliary"),MD.VIDEO);let s=null==(r=this._room)?void 0:r.remotePublishedUserMap.get(o);!s||(!i.hasAudio&&n.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,MD.AUDIO,"main"),!i.hasVideo&&n.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,MD.VIDEO,"main"),!i.hasAuxiliary&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,MD.VIDEO,"auxiliary"))})),this._eventMap.forEach(((e,t)=>FO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>FO.off(t,e,this))),this._eventMap.clear()}handleSubscribed(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);if(n.muteState.hasAudio&&"main"===i)if(n.remoteAudioTrack.isSubscribed){let e=new VV,t=this._durationMap.get(o);t?this.isRecording(t.audio)||t.audio.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[e],video:[]})}else this.stopDurationItem(o,MD.AUDIO);if(n.muteState.hasVideo||n.muteState.hasAuxiliary)if(n.remoteVideoTrack.isSubscribed||n.remoteAuxiliaryTrack.isSubscribed){let e=new VV,t=this._durationMap.get(o);t?this.isRecording(t.video)||t.video.push(e):this._durationMap.set(o,{userId:r,type:i,audio:[],video:[e]})}else this.stopDurationItem(o,MD.VIDEO)}handleStreamStopped(e){let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDurationItem(o,MD.AUDIO),this.stopDurationItem(o,MD.VIDEO)}isRecording(e){return e.findIndex((e=>0===e.endTime))>=0}addDuractionItem(e,t,i){let n="".concat(e,"_").concat(i),r=new VV,o=this._durationMap.get(n);o?this.isRecording(o[t])||o[t].push(r):this._durationMap.set(n,{userId:e,type:i,audio:t===MD.AUDIO?[r]:[],video:t===MD.AUDIO?[]:[r]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find((e=>0===e.endTime));i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce(((e,t)=>e+t.getDuration()),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},FV=class{constructor(e){ob(this,"_room"),ob(this,"_renderFreezeMap",new Map),ob(this,"_isVideoPlayingEventFiredMap",new Map),ob(this,"_dataFreezeMap",new Map),ob(this,"_monitorFreezeData",new Map),ob(this,"_eventMap",new Map),this._room=e.room,this.installEvents()}installEvents(){this._eventMap.set(HO.LEAVE_SUCCESS,(e=>{let{room:t}=e;this.hitTest(t)&&this.stop()})).set(HO.PLAY_TRACK_START,this.onPlayTrackStart).set(HO.UNSUBSCRIBE_SUCCESS,(e=>{let{room:t,streamType:i,remotePublishedUser:n}=e;if(!this.hitTest(t))return;let{userId:r}=n,o="".concat(r,"_").concat(i);this.stopDataFreeze({key:o,userId:r,type:i})})).set(HO.REMOTE_PUBLISH_STATE_CHANGED,(e=>{let{room:t,prevMuteState:i,muteState:n}=e;if(!this.hitTest(t))return;let{userId:r}=n;if(i.hasVideo&&!n.hasVideo){let e="main",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}if(i.hasAuxiliary&&!n.hasAuxiliary){let e="auxiliary",t="".concat(n.userId,"_").concat(e);this.stopDataFreeze({key:t,userId:r,type:e})}})).set(HO.PLAYER_STATE_CHANGED,(e=>{let{track:t,state:i,reason:n,type:r}=e;if(dO(t)&&this.hitTest(t.room)&&r===MD.VIDEO){if("PLAYING"===i){let e="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(e,!0)}n===MD.MUTE?this.onVideoTrackMuted(t):n===MD.UNMUTE&&this.onVideoTrackUnmuted(t)}})).set(HO.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach(((e,t)=>FO.on(t,e,this)))}uninstallEvents(){this._eventMap.forEach(((e,t)=>FO.off(t,e,this))),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i),r=this._dataFreezeMap.get(n),o=new VV;r?r.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:t,type:i,durationItemList:[o],isFreezing(){let e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,n="".concat(t,"_").concat(i);this.stopDataFreeze({key:n,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;!this.hitTest(t)||i.msg_down_stream_info.forEach((e=>{let t=this._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(!t)return;let{userId:i,muteState:n}=t;e.msg_video_status.forEach((e=>{2===e.uint32_video_stream_type&&n.hasVideo&&!n.videoMuted&&t.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&n.hasAuxiliary&&t.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:i,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}))}stopDataFreeze(e){let{key:t,userId:i,type:n}=e,r=this._dataFreezeMap.get(t);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let s=o.getDuration();s>fN?this._monitorFreezeData.set(t,{userId:i,type:n,duration:s}):r.durationItemList.pop()}getTotalDuration(e){return e.reduce(((e,t)=>{let i=t.getDuration();return e+Math.min(i,5e3)}),0)}handleRenderFreeze(e){return ab(this,arguments,(function(e){var t=this;let{userId:i,fps:n,type:r}=e;return function*(){let e="".concat(i,"_").concat(r),o=t._renderFreezeMap.get(e);if(n<=2){let n=fO();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:n,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(e,{userId:i,type:r,isFreeze:!0,freezeTimeline:[{startTime:n,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let e=o.freezeTimeline.pop();if(e){e.endTime=fO();let t=e.endTime-e.startTime;o.freezeTimeline.push(e),o.renderFreezeTotal+=Math.min(5e3,t)}}}()}))}onPlayTrackStart(e){let{track:t}=e;if(!dO(t)||!this.hitTest(t.room)||t.kind!==MD.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()<fN&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t=this._renderFreezeMap.get(e),i=0,n=0;if(t)if(t.isFreeze){let e=fO()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;i=t.renderFreezeTotal+Math.min(e,5e3),n=t.freezeTimeline.length}else i=t.renderFreezeTotal;return{renderFreeze:i,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},BV=nb(cb(),1),HV=[-1,-1,1,-1,-1,1,1,1],jV=[0,0,1,0,0,1,1,1],GV=class extends Jw{constructor(e,t){if(super(),this.context=e,ob(this,"name"),ob(this,"input"),ob(this,"output"),ob(this,"texture"),ob(this,"image"),ob(this,"ctx2d",null),ob(this,"fbo"),ob(this,"width",0),ob(this,"height",0),ob(this,"x",0),ob(this,"y",0),ob(this,"program"),ob(this,"vertexShader"),ob(this,"fragmentShader"),ob(this,"totalFrames",0),ob(this,"dropFrames",0),ob(this,"matchInputSize",!0),ob(this,"texCoordBuffer"),ob(this,"positionBuffer"),ob(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),ob(this,"cost",0),ob(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 eU){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(jV),this.positionBuffer=this.createBuffer(HV),!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(aD){this.context.destroy(aD)}}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return e.addInput(this,...i),this.output=e,e}addInput(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();return!!(this.context instanceof ZV&&this.render(e)||this.context instanceof eU&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}disconnect(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];null==(e=this.output)||e.removeInput(this,...i),delete this.output}removeInput(e){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof ZV){let e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}useTextures(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{t&&(e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,t))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach(((t,i)=>{e.enableVertexAttribArray(i),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)}))}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,n,r){return!(!this.ctx2d||!e)&&(e instanceof ImageData?this.ctx2d.putImageData(e,t,i):this.ctx2d.drawImage(e,t,i,n,r),!0)}getInfo(){var e;let{totalFrames:t,x:i,y:n,width:r,height:o,name:s,cost:a}=this,c=Date.now(),l=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:t,x:i,y:n,width:r,height:o,timestamp:c,fps:l,name:s,cost:a},ZC({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}};rb([jw(Jw.INIT,"connected",{sync:!0})],GV.prototype,"connect",1),rb([jw("connected",Jw.INIT,{ignoreError:!0,sync:!0})],GV.prototype,"disconnect",1),rb([jw([],"closed",{sync:!0})],GV.prototype,"close",1);var WV=[0,1,1,1,0,0,1,0],JV=class extends GV{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),ob(this,"_intervalId",0),ob(this,"_sequence",0),ob(this,"checkGLError",!1),e instanceof eU?this.ctx2d=e.ctx:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(WV)}start(e){this._intervalId=Qw.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(Qw.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ZV){let e=this.context.ctx.getError();e&&this.context.destroy(new Error("".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)))}}),{fps:this.context.frameRate})}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];super.addInput(e,...i),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),Qw.clearTask(this._intervalId)}},KV=class extends JV{constructor(e,t){super(e,t),ob(this,"_videoTrack"),[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let i=e=>{var t;let i=()=>{var t;return null==(t=this._videoTrack)?void 0:t.removeEventListener(e,n)},n=()=>{i(),this.context.destroy(new Error("video track ".concat(e)))};this.once("closed",i),null==(t=this._videoTrack)||t.addEventListener(e,n)};e instanceof ZV&&i("mute"),i("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},YV=class extends KV{render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}},zV=class extends KV{constructor(e,t){super(e,{name:"smallDestination"}),this.resolution=t}resize(e,t){let i,n=e*t,r=this.resolution.width*this.resolution.height;GO.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>r?i=n/r:(GO.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=n/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},qV=class extends GV{constructor(e,t,i){super(e,ZC({name:"imageSource"},i)),this.image=t,ob(this,"_image"),ob(this,"_totalFrames",0),ob(this,"_autoResize",!1),this._autoResize=!1!==(null==i?void 0:i.autoResize)}_render(e,t){let{width:i,height:n}=this;if(this.image instanceof HTMLVideoElement){if(iO(this.image.getVideoPlaybackQuality)&&!Fk){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}({videoWidth:i,videoHeight:n}=this.image),this.image.width=i,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if(({width:i,height:n}=this.image),this.image!==this._image)this._image=this.image;else if(i===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&(({width:i,height:n}=this.image),this._image=this.image);if(!this._autoResize)return!0;if(this.width===i&&this.height===n&&this.totalFrames){if(t){this.useTexture();let e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}this.resize(i,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},QV=class extends qV{constructor(e,t,i){super(e,document.createElement("video"),i),this._videoTrack=t,ob(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}},XV=class extends Jw{constructor(e){super(),ob(this,"frameRate"),ob(this,"_canvas"),ob(this,"log"),ob(this,"hasAlpha",!1),ob(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 QV(this,e)}createVideoTrackDestination(e){return new KV(this,e)}createVideoImageSource(e,t){return new qV(this,e,t)}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}},$V={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ZV=class extends XV{constructor(){super(...arguments),ob(this,"defaultProgam"),ob(this,"defaultVShader"),ob(this,"defaultFShader"),ob(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",$V),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new Error("webgl context lost"))})),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let i=this.ctx,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}createProgram(e,t){let i=this.ctx,n=i.createProgram();return i.attachShader(n,e),i.attachShader(n,t),i.linkProgram(n),i.getProgramParameter(n,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(n)),n}};rb([jw(Jw.INIT,"created",{sync:!0})],ZV.prototype,"create",1),rb([jw("created",Jw.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit("unavailable",e),this.removeAllListeners()}})],ZV.prototype,"destroy",1);var eU=class extends XV{constructor(){super(...arguments),ob(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()}};rb([jw(Jw.INIT,"created",{sync:!0})],eU.prototype,"create",1),rb([jw("created",Jw.INIT,{ignoreError:!0,sync:!0})],eU.prototype,"destroy",1);var tU=[1,0,0,0,1,1,0,1],iU=class extends GV{constructor(e){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),e instanceof ZV)try{this.setTexBuffer(tU)}catch(sD){e.destroy(sD)}else this.ctx2d&&setTimeout((e=>{e.scale(-1,1),e.translate(-this.width,0)}),0,this.ctx2d)}render(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}},nU=class{constructor(e,t){this.node=e,this.layout=t,ob(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}},rU=class extends GV{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0}),ob(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let i=new nU(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 ZV&&this.inputs.forEach((e=>{if(e){let t=this.layout2texCoords(e);e.positionBuffer?this.changeBufferData(e.positionBuffer,t):e.positionBuffer=this.createBuffer(t)}}))}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return super.connect(e,...i),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex((t=>(null==t?void 0:t.node)===e))]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&(t.node.useTexture(),this.draw(t.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce(((t,i)=>(!i||!i.node.requestFrame(e))&&t),!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let e=0;e<this.inputs.length;e++){let t=this.inputs[e];t&&this.draw2d(t.node.image,t.x,t.y,t.width,t.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:i,width:n,height:r,name:o}=this,s=Date.now(),a=(e-this.lastInfo.totalFrames)/((s-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:i,width:n,height:r,timestamp:s,fps:a,name:o},ZC({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 ZV))try{null==(i=this.context.ctx)||i.deleteBuffer(e.positionBuffer)}catch(n){}}))}},oU=class{constructor(e,t){this.createMediapipeSolutionsWasm=t,ob(this,"canvas"),ob(this,"locateFile"),ob(this,"_glName"),ob(this,"_solutionWasm"),ob(this,"ctx"),ob(this,"pl",{onResults:e=>this.onResults(e.get(0).glName)}),this.locateFile=t=>"".concat(e,"/").concat(t)}bindTexture(){var e;null==(e=this.ctx)||e.activeTexture(this.ctx.TEXTURE0),this.bindTexture2d(this._glName)}initialize(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"selfie_segmentation_landscape.tflite";return ab(this,null,(function*(){yield this.createMediapipeSolutionsWasm(this),this.canvas=e,this.createContext(e,!0,!0,{}),this._glName=this.createTexture(),this._solutionWasm=new this.SolutionWasm;let i=new this.StringList;i.push_back("segmentation_mask");let n=this.PacketListener.implement(this.pl);this._solutionWasm.attachMultiListener(i,n),i.delete(),this._solutionWasm.loadGraph(yield fetch(this.locateFile("selfie_segmentation.binarypb")).then((e=>e.arrayBuffer()))),this._solutionWasm.overrideFile("third_party/mediapipe/modules/selfie_segmentation/selfie_segmentation_landscape.tflite",yield fetch(this.locateFile(t)).then((e=>e.arrayBuffer())));let r=new this.GraphOptionChangeRequestList;return r.push_back({calculatorIndex:1,calculatorName:"",calculatorType:"GlScalerCalculator",fieldName:"flip_horizontal",valueBoolean:!1,valueNumber:0,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"ConstantSidePacketCalculator",calculatorName:"ConstantSidePacketCalculatorModelSelection",fieldName:"int_value",valueBoolean:!1,valueNumber:1,valueString:""}),r.push_back({calculatorIndex:0,calculatorType:"InferenceCalculator",calculatorName:"",fieldName:"use_cpu_inference",valueBoolean:!1,valueNumber:0,valueString:""}),this._solutionWasm.changeOptions(r),this}))}send(e,t){let i=new this.PacketDataList;i.pushTexture2d({stream:"input_frames_gpu",timestamp:1e3*performance.now(),glName:this._glName,width:e,height:t}),this._solutionWasm.send(i),i.delete()}close(){var e,t,i;null==(e=this.canvas)||delete e.getContext,delete this.readyPromiseResolve,delete this.readyPromiseReject,this.pl.onResults=null,delete this.onResults,null==(t=this.deleteTexture)||t.call(this,this._glName),null==(i=this._solutionWasm)||i.delete();for(let n of Object.keys(this))delete this[n]}},sU=class extends QV{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0}),ob(this,"ready",!1),ob(this,"_bgTexture"),ob(this,"_waterMarkTexture"),ob(this,"_lastMaskTexture"),ob(this,"_textureValid",!1),ob(this,"_selfieTextureValid",!1),ob(this,"_selfieSegmentation"),ob(this,"wasm"),this.init(t).catch((()=>this.context.destroy(new Error("selfie_segmentation init faild"))))}init(e){return ab(this,null,(function*(){let t=yield e.Wasm(),i=this.context.ctx;if(this.wasm=new t.AllIn1(i),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,e.waterMark){let{x:t,y:i,width:n,height:r}=e.waterMark;this.wasm.setWaterMark(t,i,n,r)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),i.uniform1i(i.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(i.uniform1i(i.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(i.uniform1i(i.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),i.uniform1i(i.getUniformLocation(this.program,"lastMask"),4),this._selfieSegmentation=yield e.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this),this.ready=!0}))}onPredict(e){let t=this.context.ctx;this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image)),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,0==(1&this.totalFrames)?this._lastMaskTexture:this.texture),t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,this.width,this.height),this.useProgram(),this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),this._selfieSegmentation.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.activeTexture(t.TEXTURE4),t.bindTexture(t.TEXTURE_2D,0!=(1&this.totalFrames)?this._lastMaskTexture:this.texture),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.totalFrames++}render(e){let t=this.context.ctx;if("function"==typeof this.image.getVideoPlaybackQuality){let e=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===e)return!1;this._totalFrames=e,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:i,videoHeight:n}=this.image;this.image.width=i,this.image.height=n;let r=!1;if(this.totalFrames)this._selfieSegmentation.bindTexture(),r=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),r=this._textureValid,this._textureValid=!0}return this.width===i&&this.height===n&&r?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image):(this.resize(i,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)),this.ready&&this._selfieSegmentation.send(i,n),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),null==(e=this.wasm)||e.close()}},aU=class extends BV.EventEmitter{constructor(e){let{room:t}=e;super(),ob(this,"videoContext"),ob(this,"_glVideoContext"),ob(this,"_2dVideoContext"),ob(this,"destination"),ob(this,"smallVideoContext"),ob(this,"smallDestination"),ob(this,"smallTrackSource"),ob(this,"smallImageSource"),ob(this,"_isMirror",!1),ob(this,"cameraTrack"),ob(this,"cameraNode"),ob(this,"waterMarkNode"),ob(this,"mirrorNode"),ob(this,"mixNode"),ob(this,"screenTrack"),ob(this,"screenNode"),ob(this,"selfModel",!1),ob(this,"blurRadius",3),ob(this,"Wasm"),ob(this,"_isMixScreen",!1),ob(this,"_hasWaterMark",!1),ob(this,"_virualBackground"),ob(this,"_bgAssetPath"),ob(this,"_log"),ob(this,"_checkId",0),ob(this,"_room"),ob(this,"_use2d",!1),ob(this,"_autoSwitchRenderMode",!0),ob(this,"_waterMarkOption"),ob(this,"_selfieSegmentation"),this._room=t,this._log=GO.createLogger({id:"vm",userId:t.userId,sdkAppId:t.sdkAppId}),this.smallVideoContext=new eU({frameRate:15,logger:this._log,name:"s"}),this.enablePrintDetail()}get _hasVirualBg(){return!!this._virualBackground}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 eU({frameRate:15,logger:this._log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new ZV({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),FO.emit("262",{room:this._room,apiName:"videoCtxGl",error:t||new Error(e)}),this.update()}))}catch(sD){this.emit("error",{reason:"create",error:sD}),this.sendCreateResult("videoCtxGl",sD)}return this._glVideoContext}enablePrintDetail(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=Qw.run(MN,(()=>{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(),Qw.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirualBg}get active(){return(Jk&&Wk||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirualBg)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl",t=arguments.length>1?arguments[1]:void 0;FO.emit("262",{room:this._room,apiName:e,error:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}initVirtualBackground(e){if(!this._selfieSegmentation){let t=new oU(e.assetPath||"./selfie_segmentation",e.createMediapipeSolutionsWasm),i=this.getGlVideoContext();return i.available?this._selfieSegmentation=t.initialize(i._canvas,"selfie_segmentation_landscape.tflite"):Promise.reject(new Error("init virtual background failed, reason: video context unavailable"))}return this._selfieSegmentation}_setMainOutput(e){var t;let i=this.cameraTrack,{small:n,settings:r}=i;return n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new zV(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack),this.smallTrackSource.width=r.width,this.smallTrackSource.height=r.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),i.setOutputMediaStreamTrack(e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack)}update(){return ab(this,null,(function*(){var e,t;if(this.cameraTrack&&this.cameraTrack.mediaTrack){if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();{let{settings:e,profile:t}=this.cameraTrack;this._use2d||!this._selfieSegmentation?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination"})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new YV(this.videoContext,{name:"mainDestination"})),this.cameraNode=new sU(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate}if(this._use2d){let i=this.cameraNode;i.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new iU(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 rU(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.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack)),null==(t=this.screenNode)||t.connect(this.mixNode,{zIndex:0}),i=this.mixNode,this._log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))),i.connect(this.destination)}return this._setMainOutput(this.videoContext._canvas)}}))}changeInput(e,t){return this._log.info("change input"),e instanceof _M?this.setScreenTrack(e):e instanceof pM?this.setCameraTrack(e):e instanceof LM?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}removeInput(e){var t;e instanceof _M?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof pM&&(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource))}setCameraTrack(e){return ab(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)}loadImage(e){return new Promise(((t,i)=>{let n=new Image;n.crossOrigin="anonymous",n.src=e,n.onload=()=>t(n),n.onerror=i}))}setWatermark(e){return ab(this,null,(function*(){let t=(null==e?void 0:e.imageElement)||(yield this.loadImage(e.imageUrl)),{x:i=0,y:n=0,width:r=t.width,height:o=t.height}=e;this._hasWaterMark=!0,this._waterMarkOption={x:i,y:n,width:r,height:o,image:t},this._log.info("start watermark",JSON.stringify({x:i,y:n,width:r,height:o})),this.update()}))}stopWatermark(){var e;!this._hasWaterMark||(this._hasWaterMark=!1,this._log.info("stop watermark"),null==(e=this.waterMarkNode)||e.close(),delete this.waterMarkNode,delete this._waterMarkOption,this.update())}setVirtualBackground(e){return ab(this,null,(function*(){if(e){if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,"image"===e.type?this._virualBackground=yield this.loadImage(e.imageUrl):(this.blurRadius=e.blurRadius||3,this._virualBackground=e.type)}else this._virualBackground=void 0;this._log.info("".concat(this._virualBackground?"start":"stop"," visual background, ").concat((null==e?void 0:e.type)||"")),this.update()}))}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||(null==(t=this.mirrorNode)||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}clear(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}},cU=0,lU=class extends Jw{constructor(e){super("room"),this.seq=++cU,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=GO.createLogger({id:"r".concat(this.seq)}),this._joinedTimestamp=0,this.isDestroyed=!1,this.useStringRoomId=!!e.useStringRoomId,sO(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),sO(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),sO(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new xV({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new UV({room:this}),this.badCaseDetector=new FV({room:this}),this.audioManager=new OM({room:this}),this.videoManager=new aU({room: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 isJoined(){return"joined"===this.state}get isLeft(){return"left"===this.state}addTrack(e){return ab(this,null,(function*(){return this.publish(e)}))}removeTrack(e){return ab(this,null,(function*(){return this.unpublish(e)}))}replaceTrack(e){return ab(this,null,(function*(){}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(rO(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if($N(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:n,scheduleProxy:r,unifiedProxy:o}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=o,o?(tV([o,o]),pD("https://".concat(o))):(n&&pD(n),r&&tV(r))}FO.once(HO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({sched_domain:eV.main,sched_back_domain:eV.backup,signal_domain:this.proxy_ws||this.proxy_wt||""})))}getRemoteAudioStats(){return ab(this,null,(function*(){let e={};return this.remotePublishedUserMap.forEach((t=>{e[t.userId]=t.remoteAudioTrack.stat})),e}))}getTransportStats(){return ab(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 ab(this,arguments,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return function*(){let i={};return e.remotePublishedUserMap.forEach((e=>{let n="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;i[e.userId]=n.stat})),i}()}))}checkDestroy(){if(this.isDestroyed)throw new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(zO.INVALID_DESTROY),new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.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,FO.emit(HO.ROOM_DESTROY,{room:this})}schedule(e,t){return ab(this,null,(function*(){var i,n;let r=fO();try{let{isCached:o,result:s,detailCost:a}=yield Zx({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:rD,userSig:this.userSig,frameWorkType:t});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(NO(s,{keysToExclude:["username","credential"]}))),o&&FO.once(HO.JOIN_RECEIVED_CMD_RES,(()=>this.sendAbilityStatus({scheduleCache:1}))),this.scheduleResult=ZC(ZC({},this.scheduleResult),s),oO(null==(i=s.config)?void 0:i.retryCount)&&rN(s.config.retryCount),rO(null==(n=s.config)?void 0:n.loggerDomain)&&pD(s.config.loggerDomain),FO.emit(HO.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:a}),FO.emit(HO.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:fO()-r})}catch(o){throw FO.emit(HO.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:o}),o}}))}},dU=nb(cb()),uU=nb(hb()),hU=e=>{let{serverAbility:t,clientAbility:i,offerSDP:n,enableCustomMessage:r}=e,o=fV(n),s={extmapAllowMixed:"extmap-allow-mixed",groups:o.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},a={candidates:t.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:MD.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:MD.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(pU({mid:e,serverAbility:t,clientAbility:i,parsedOffer:o}))})),r&&s.media.push(o.media.find((e=>"dc"===e.mid))),gV(s)},pU=e=>{let{mid:t,serverAbility:i,clientAbility:n,parsedOffer:r,useAllCodec:o=!1}=e,s={candidates:i.candidates.map((e=>({component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}))),connection:{version:4,ip:"0.0.0.0"},direction:MD.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map((e=>({value:e.id,uri:e.uri}))),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:r.media[0].port,protocol:r.media[0].protocol,type:MD.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++)mU(s,i.video.codecs[a]);else{let e=i.video.codecs.findIndex((e=>e.codec.toLowerCase()===(i.useVp8?"vp8":"h264")));mU(s,i.video.codecs[e])}else if(o)for(let a=0;a<n.video.codecs.length;a++)mU(s,n.video.codecs[a]);else mU(s,n.video.codecs[0]);return s.payloads=s.payloads.trim(),s},mU=(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,fU=e=>{let t=uU.default.parse(e);return t.media.forEach((e=>{var i;(e.type===MD.AUDIO||e.type===MD.VIDEO)&&(function(e){if(!e.rtcpFb)return;let t=[];e.rtcpFb.forEach(((i,n)=>{var r;t.push(i),e.rtcpFb&&(null==(r=e.rtcpFb[n+1])?void 0:r.payload)!==i.payload&&"rrtr"!==i.type&&t.push({payload:i.payload,type:"rrtr"})})),e.rtcpFb=t}(e),function(e){e.type===MD.VIDEO&&e.fmtp&&e.fmtp.forEach((e=>{e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===MD.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")})),uU.default.write(t)},gU=((_U=gU||{}).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),TU=0,EU=!1,SU=new Set,IU=1,vU=class extends dU.default{constructor(e){let{signalChannel:t,room:i,enableCustomMessage:n}=e;super(),ob(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),ob(this,"currentState","DISCONNECTED"),ob(this,"_room"),ob(this,"_signalChannel"),ob(this,"_peerConnection",null),ob(this,"_datachannel",null),ob(this,"_enableCustomMessage"),ob(this,"_log"),ob(this,"_downlinkMIDMap",new Map),ob(this,"_downlinkMIDUserIDMap",new Map),ob(this,"_reconnectionTimer",-1),ob(this,"reconnectionCount",0),ob(this,"_clientAbility",null),ob(this,"_serverAbility",null),ob(this,"addDownlinkQueue",new Set),ob(this,"removeDownlinkQueue",new Set),ob(this,"_parsedAnswer",null),ob(this,"_updateSDPPromise",null),ob(this,"_waitForPCConnectedPromise"),ob(this,"_waitForPCConnectedPromiseReject",null),ob(this,"_isSDPLogged",!1),ob(this,"seiCodec",null),this._room=i,this._enableCustomMessage=n,this._signalChannel=t,this._log=GO.createLogger({id:"spc".concat(IU++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Nw&&(this.seiCodec=new lV(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 isUsingH264(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=fV(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach(((e,t)=>{var n;if(e.ssrcs&&!nO(e.ssrcs[0].id)){let r=Number(e.ssrcs[0].id),o=Number(null==(n=e.ssrcs.filter((e=>"cname"===e.attribute))[1])?void 0:n.id);switch(t){case 0:i.audioSsrc=r;break;case 1:i.bigVideoSsrc=r,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=r,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=r,i.auxVideoRtxSsrc=o}}})),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}initialize(){return ab(this,null,(function*(){try{this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this._room.enableSEI&&Nw,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 AU(e.data);this.emit("data_channel_msg",{data:t})},this._datachannel.onerror=e=>{this._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(MD.AUDIO,{direction:MD.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:MD.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:MD.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:MD.TRANSCEIVER_DIRECTION_SENDONLY});let e=yield this._peerConnection.createOffer();return yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:e}=this;!e||(this._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===this.stat.dtlsStartTime?this.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===this.stat.dtlsEndTime&&(this.stat.dtlsEndTime=Date.now()))}),this._clientAbility=((e,t)=>{var i,n;let r=fV(e),o={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],extensions:[]},useDataChannel:t};o.ice.ufrag=String(r.media[0].iceUfrag),o.ice.password=r.media[0].icePwd||"",r.fingerprint&&(o.dtls.hash=r.fingerprint.type,o.dtls.fingerprint=r.fingerprint.hash,o.dtls.setup=r.setup||""),r.media[0].fingerprint&&(o.dtls.hash=r.media[0].fingerprint.type,o.dtls.fingerprint=r.media[0].fingerprint.hash),o.dtls.setup=r.media[0].setup||"";let s=r.media[0],a=r.media[1];s.ext&&(o.audio.extensions=s.ext.map((e=>({id:e.value,uri:e.uri})))),a.ext&&(o.video.extensions=a.ext.map((e=>({id:e.value,uri:e.uri}))));let c={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};null==(i=s.rtcpFb)||i.forEach((e=>{let{payload:t,type:i,subtype:n}=e;if(t===c.payload){let e={id:i,params:[]};n&&e.params.push(n),c.rtcpFb.push(e)}})),o.audio.codecs.push(c);for(let l=0;l<a.rtp.length;l++){if(["rtx","red","ulpfec"].includes(a.rtp[l].codec))continue;let e=a.fmtp.filter((e=>e.payload===a.rtp[l].payload))[0];o.video.codecs.push({payload:a.rtp[l].payload,codec:a.rtp[l].codec,fmtp:e?e.config:"",rate:a.rtp[l].rate,rtx:"rtx"===(null==(n=a.rtp[l+1])?void 0:n.codec)?a.rtp[l+1].payload:0,rtcpFb:((null==a?void 0:a.rtcpFb)||[]).filter((e=>e.payload===a.rtp[l].payload)).map((e=>{let{type:t,subtype:i}=e;return{id:t,params:i?[i]:[]}}))})}return o})(e.sdp,this._enableCustomMessage),this._clientAbility}catch(sD){throw this._log.error("initialize failed ".concat(sD)),sD}}))}connect(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return ab(this,null,(function*(){var i;try{if("CONNECTED"===this.currentState)return;let n=fO(),r={type:"answer",sdp:hU({serverAbility:e,clientAbility:this._clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(r),yield this.waitForPeerConnectionConnected(),t||FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",cost:Math.min(fO()-n,3e4)}),null==(i=this.seiCodec)||i.handleEncodedStreams()}catch(n){let t=n instanceof gb&&n.code===_b.API_CALL_ABORTED;throw t||this._log.error("connect failed: ".concat(n),e),this.reset(),!t&&!this.isReconnecting&&(FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCConnect",error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}}))}reconnect(){return ab(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(fx,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:Hx,responseCommand:Sx.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(0!==t.data.code)throw new gb({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),this._log.warn("reconnect() success"),this.stopReconnection(),this.emit("spc-reconnected")}catch(sD){if(!this.isReconnecting)return;if(null!=sD&&sD.message.includes("timeout")){let e=eO(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==sD?void 0:sD.code," ").concat(sD)),FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",error:sD}),this.reconnectionCount>=oN()&&this._log.warn("SDK has tried reconnect for ".concat(oN()," 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 ab(this,null,(function*(){this._log.warn("start reconnect"),this.emitConnectionStateChangedEvent("RECONNECTING");let e=fO();yield this.reconnect(),FO.emit(HO.API_SUCCESS_RATE,{room:this._room,apiName:"SPCReconnect",cost:Math.min(fO()-e,3e4)})}))}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(fx,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===iN.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===iN.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===iN.FAILED||e.target.connectionState===iN.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===iN.CONNECTED||e.target.connectionState===iN.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),FO.emit(HO.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 tN;let e=null;return Iw()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,Sw()&&0!==this._peerConnection.getReceivers().length&&e?e.state:tN):tN}emitConnectionStateChangedEvent(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(gU.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return ab(this,null,(function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(pw(i)){let t=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);t&&this._log.info("local candidate: ".concat(t.candidateType," ").concat(t.protocol,":").concat(t.ip||t.address,":").concat(t.port," ").concat(t.networkType||""," ").concat("relay"===t.candidateType?"relayProtocol:".concat(t.relayProtocol):"")),n&&this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port));break}}))}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise(((e,t)=>{if("CONNECTED"===this.currentState)return e();this._waitForPCConnectedPromiseReject=t;let i=t=>{"CONNECTED"===t.state&&(clearTimeout(o),r(),e())},n=e=>{let{room:i}=e;i===this._room&&(clearTimeout(o),r(),t(new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.CONNECTION_ABORTED,data:"leave room"})})))},r=()=>{FO.off(HO.LEAVE_SUCCESS,n,this),this.off(gU.CONNECTION_STATE_CHANGED,i,this)},o=setTimeout((()=>{r();let e=new gb({code:_b.API_CALL_TIMEOUT,message:"connection timeout"});TU+=1,(e=>TU>2&&!EU&&0===SU.size&&e)(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),EU=!0,this.emit(gU.FIREWALL_RESTRICTION)),t(e)}),SN);FO.on(HO.LEAVE_SUCCESS,n,this),this.on(gU.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 ab(this,null,(function*(){var t;if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this.updateLocalAndRemoteSDPConfig(e),0===this.addDownlinkQueue.size)try{yield this.updateSDP({isNeedToCreateOffer:!0}),null==(t=this.seiCodec)||t.handleEncodedStreams(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(aD){this._log.info("addDownlink(".concat(e.userId,") failed")),yield this.startReconnection()}}))}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:n}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let r,o,s,a=this._peerConnection.getTransceivers().filter((e=>"inactive"===e.direction)).slice(0,3).map((e=>(e.direction=MD.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid))));if(0===a.length&&(this._peerConnection.addTransceiver(MD.AUDIO,{direction:MD.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:MD.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(MD.VIDEO,{direction:MD.TRANSCEIVER_DIRECTION_RECVONLY})),this._parsedAnswer||(this._parsedAnswer=fV(this._peerConnection.remoteDescription.sdp)),3===a.length)r=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[0]))),o=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[1]))),s=this._parsedAnswer.media.find((e=>Number(e.mid)===Number(a[2])));else{r=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let e=pU({mid:1,serverAbility:this._serverAbility,clientAbility:this._clientAbility,parsedOffer:fV(this._peerConnection.localDescription.sdp),useAllCodec:!0});o=JSON.parse(JSON.stringify(e)),s=JSON.parse(JSON.stringify(e)),r.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(r),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}r.direction=MD.TRANSCEIVER_DIRECTION_SENDONLY,r.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(n)},{id:t.audio,attribute:"msid",value:"".concat(n,"-").concat(MD.MAIN," ").concat(n,"-audio")}],o.direction=MD.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(n)},{id:t.video,attribute:"msid",value:"".concat(n,"-").concat(MD.MAIN," ").concat(n,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(n)},{id:t.videoRtx,attribute:"msid",value:"".concat(n,"-").concat(MD.MAIN," ").concat(n,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],s.direction=MD.TRANSCEIVER_DIRECTION_SENDONLY;let c="".concat(n,"-aux");s.ssrcs=[{id:t.auxiliary,attribute:"cname",value:c},{id:t.auxiliary,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(MD.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(c," ").concat(n,"-aux").concat(MD.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(c," ").concat(n,"-aux").concat(MD.VIDEO)}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((e=>e.mid)).join(" ")),this._downlinkMIDMap.set(i,[r.mid,o.mid,s.mid]),this._downlinkMIDUserIDMap.set(r.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(s.mid,i)}removeDownlink(e,t){return ab(this,null,(function*(){if(!this._downlinkMIDMap.has(t)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(t,") trying")),this.isReconnecting&&(yield this.waitForReconnected());let i=this._downlinkMIDMap.get(t),n=!1;this._peerConnection.getTransceivers().forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=fV(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((e=>{null!=i&&i.includes(Number(e.mid))&&(n=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),0===this.removeDownlinkQueue.size&&n&&(yield this.updateSDP({isNeedToCreateOffer:!0,tinyIdRemoving:e})),this._downlinkMIDMap.delete(t),null==i||i.forEach((e=>this._downlinkMIDUserIDMap.delete(e))),this._log.info("removeDownlink(".concat(t,") done"))}))}setBandwidth(e){return ab(this,null,(function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;try{if(bw()){let e=this._peerConnection.getSenders().slice(0,4);for(let s=0;s<e.length;s++){let o,a=e[s];0===s&&t?o=t:1===s&&i?o=i:2===s&&n?o=n:3===s&&r&&(o=r),o&&(yield this.setSenderMaxBitrate(a,o))}let o=!1;i&&e[1].track&&(o=this.setStartBitrate(1,i)),r&&e[3].track&&(o=this.setStartBitrate(3,r)||o),o&&(yield this.updateSDP({localDescription:this._peerConnection.localDescription}))}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(o){this._log.error("failed to set bandwidth".concat(o))}}))}setStartBitrate(e,t){var i,n;return!(null==(i=this._peerConnection)||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=fV(this._peerConnection.remoteDescription.sdp)),null==(n=this._parsedAnswer.media[e])||!n.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();return(!i.encodings||0===i.encodings.length)&&(i.encodings=[{}]),"unlimited"===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:n,auxVideo:r}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=fV(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=fV(this._peerConnection.remoteDescription.sdp));let s=Ub?"TIAS":"AS";t&&(o.media[0].bandwidth=[{type:s,limit:Ub?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:s,limit:Ub?1e3*t:t}]),i&&(o.media[1].bandwidth=[{type:s,limit:Ub?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:s,limit:Ub?1e3*i:i}]),n&&(o.media[2].bandwidth=[{type:s,limit:Ub?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:s,limit:Ub?1e3*n:n}]),r&&(o.media[3].bandwidth=[{type:s,limit:Ub?1e3*r:r}],this._parsedAnswer.media[3].bandwidth=[{type:s,limit:Ub?1e3*r:r}]);let a={type:"offer",sdp:gV(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(e){let{isNeedToCreateOffer:t=!1,localDescription:i,tinyIdRemoving:n}=e;if(!this._parsedAnswer)return;let r=gV(this._parsedAnswer);return this._updateSDPPromise=new Promise(((e,n)=>ab(this,null,(function*(){var o,s;try{t&&this._peerConnection&&(this._log.info("creating offer"),i=yield this._peerConnection.createOffer()),i&&(yield this.setOffer(i)),yield this.setAnswer({type:"answer",sdp:r}),this._updateSDPPromise=null,e()}catch(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((e=>{let{mid:t,currentDirection:i,direction:n,stopped:r}=e;return{mid:t,currentDirection:i,direction:n,stopped:r}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._log.warn("local sdp: ".concat(null==i?void 0:i.sdp)||(null==(o=this._peerConnection.localDescription)?void 0:o.sdp)),this._log.warn("remote sdp: ".concat(r)||(null==(s=this._peerConnection.remoteDescription)?void 0:s.sdp)),this._isSDPLogged=!0),this._updateSDPPromise=null,n(a)}})))),this._updateSDPPromise}setOffer(e){return this._log.info("setting offer"),this._peerConnection.setLocalDescription({type:"offer",sdp:fU(e.sdp)})}setAnswer(e){return this._log.info("setting answer"),this._room.enableHWEncoder&&e.sdp&&(e.sdp=e.sdp.replaceAll("42e01f","42001f")),this._peerConnection.setRemoteDescription(e)}sendDataChannelMessage(e){var t;null==(t=this._datachannel)||t.send(e)}reset(){var e;null==(e=this._peerConnection)||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}sendSEI(e,t){var i;null==(i=this.seiCodec)||i.push(e,t)}};rb([cM()],vU.prototype,"updateSDP",1);var yU=class{constructor(e){ob(this,"tag"),ob(this,"len"),ob(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}},AU=class{constructor(e){ob(this,"tinyId"),ob(this,"data");let t=new DataView(e),i=0,n=[];for(;i<t.byteLength;){let r=t.getUint16(i+2),o=new yU(new Uint8Array(e).slice(i,i+2+2+r).buffer);n.push(o),i+=4+r}n.forEach((e=>{1===e.tag?this.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(this.data=e.data)}))}},RU=new Set;function CU(){let e=Math.floor(4294967296*Math.random());return RU.has(e)?CU():(RU.add(e),e)}var bU=nb(cb()),kU=class extends bU.default{constructor(e){super(),ob(this,"userId"),ob(this,"tinyId"),ob(this,"_sdpSemantics"),ob(this,"_isUplink"),ob(this,"_room"),ob(this,"_log"),ob(this,"_signalChannel"),ob(this,"_currentState","DISCONNECTED"),ob(this,"_prevTime",-1),ob(this,"_enableSEI"),ob(this,"_sei"),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=GO.createLogger({id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel,this._enableSEI=e.enableSEI,this._enableSEI&&Nw&&(this._sei=new lV(this,this._log,this._isUplink))}get _peerConnection(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}close(e){this._log.info("close connection"),this.emit("closed",e),this._sei&&(this._sei.destroy(),this._sei=null)}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(FO.emit(HO.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"))}},DU=class extends kU{constructor(e){super(eb(ZC({},e),{isUplink:!0})),ob(this,"localMainAudioTrack",null),ob(this,"localMainVideoTrack",null),ob(this,"localAuxAudioTrack",null),ob(this,"localAuxVideoTrack",null),ob(this,"_isPublishingAux",!1),ob(this,"_publishingLocalAudioTrack"),ob(this,"_publishingLocalVideoTrack"),ob(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}),ob(this,"_audioManager"),this._audioManager=e.audioManager,this.initialize()}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:n,smallVideoRtxSsrc:r,auxVideoSsrc:o,auxVideoRtxSsrc:s}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:n||0,smallRtx:r||0,auxiliary:o||0,auxiliaryRtx:s||0}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get publishState(){var e,t,i,n;let r={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let o=this._peerConnection.getSenders();o&&(vw()?(r.audio=!(null==(e=o[0])||!e.track),r.bigVideo=!(null==(t=o[1])||!t.track),r.smallVideo=!(null==(i=o[2])||!i.track),r.auxVideo=!(null==(n=o[3])||!n.track)):o.forEach((e=>{e.track&&(e.track.kind===MD.AUDIO?r.audio=!0:(r.bigVideo=!0,this._room.videoManager.hasSmall&&(r.smallVideo=!0)))})))}return r}get muteState(){var e,t,i;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(i=this.localAuxVideoTrack)||!i.muted)}}initialize(){this.installEvents()}reset(){this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(e=this.singlePC)||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var i,n,r;let o=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(i=this.localMainVideoTrack)||i.emit("connection-state-changed",{prevState:o,state:e}),null==(n=this.localAuxVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this._publishingLocalVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}))),s}publish(e){return ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n,isAuxiliary:r}=e;return function*(){var e,o,s,a,c,l,d;if(!t.singlePC)return;if(yield t.singlePC.waitForPeerConnectionConnected(),i&&(t._publishingLocalAudioTrack=i),n){if(!t.singlePC.isH264EncodeSupported&&!t.singlePC.isVP8EncodeSupported)throw new gb({code:_b.NOT_SUPPORTED_H264,message:XO({key:YO.NOT_SUPPORTED_H264ENCODE})});Mb&&115===wk()&&n.profile.width*n.profile.height<=230400&&(t._log.warn("fallback video to 480p"),n.setProfile(wD["480p_2"]),yield n.applyProfile()),t._publishingLocalVideoTrack=n}let u;if(t._isPublishingAux=r,n&&!r&&n.small&&(u=t._room.videoManager.smallTrack),yw()&&(yield t.publishByTransceiver({localAudioTrack:i,localVideoTrack:n,smallTrack:u,isAuxiliary:r})),null==(e=t.singlePC.seiCodec)||e.handleEncodedStreams(),t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,r)n&&(t.localAuxVideoTrack=n),i&&(t.localAuxAudioTrack=i);else{if(n){t.localMainVideoTrack=n;let{scaleResolutionDownBy:e}=n;e>1&&(t._log.warn("setScaleResolutionDownBy main ".concat(e)),yield t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[1],e))}i&&(t.localMainAudioTrack=i)}yield t.singlePC.setBandwidth({audio:(null==(o=t.localMainAudioTrack)?void 0:o.profile.bitrate)||(null==(s=t.localAuxAudioTrack)?void 0:s.profile.bitrate),bigVideo:null==(a=t.localMainVideoTrack)?void 0:a.profile.bitrate,smallVideo:null==(l=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:l.bitrate,auxVideo:null==(d=t.localAuxVideoTrack)?void 0:d.profile.bitrate}),yield t._signalChannel.sendWaitForResponse({command:Gx,responseCommand:Sx.SPC_PUBLISH_RESULT,data:eb(ZC({},t.singlePC.uplinkSSRC),{state:t.publishState,muteState:t.muteState})}),t.sendMediaSettings(),t.installTrackMuteEvents(i,n)}()}))}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:n,isAuxiliary:r}=e;this._log.info("publish by transceiver");let o=null==i?void 0:i.outMediaTrack,s=this._audioManager.mixedAudioTrack,a=this._peerConnection.getTransceivers(),c=[],l=[];if(s){let e=a[0].sender.replaceTrack(s);l.push(0),c.push(e)}if(o)if(r){let e=a[3].sender.replaceTrack(o);l.push(3),c.push(e)}else{let e=a[1].sender.replaceTrack(o);l.push(1),c.push(e)}if(n){let e=a[2].sender.replaceTrack(n);l.push(2),c.push(e)}let d=this.setTransceiverDirection(LD.SENDONLY,l);return c.push(d),Promise.all(c)}enableSmall(e){return ab(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(LD.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(LD.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 ab(this,arguments,(function(e){var t=this;let{localAudioTrack:i,localVideoTrack:n}=e;return function*(){let e=n&&n===t.localAuxVideoTrack,r=null==n?void 0:n.outMediaTrack,o=t._peerConnection.getSenders(),s=[];i&&(t._audioManager.mixedAudioTrack||(yield o[0].replaceTrack(null),s.push(0)),e?t.localAuxAudioTrack=null:t.localMainAudioTrack=null),r&&(e?(yield o[3].replaceTrack(null),t.localAuxVideoTrack=null,t._mediaSettings=eb(ZC({},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=eb(ZC({},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(LD.INACTIVE,s),yield t.doPublishChange(!1)):yield t.doUnpublish(),t.uninstallTrackMuteEvents(i,n),null==n||n.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"})}()}))}doPublishChange(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,(function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponse({command:bx,data:t,responseCommand:Sx.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:kx,commandDesc:"unpublish",responseCommand:Sx.UNPUBLISH_RESULT,enableLog:e}).catch((e=>{if(e.getCode()===_b.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),kw){if(i&&i.outMediaTrack){let e=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=e.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=e.sampleRate||0}if(n&&n.outMediaTrack){let e=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=e.width||0,this._mediaSettings.videoHeight=e.height||0,this._mediaSettings.videoFps=e.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){let e=r.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=e.width||0,this._mediaSettings.auxVideoHeight=e.height||0,this._mediaSettings.auxVideoFps=e.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Bx,data:this._mediaSettings,responseCommand:Sx.UPDATE_CONSTRAINT_CONFIG_RES}).then((e=>{0!==e.data.code&&this._log.warn(e.data.message)})).catch((()=>{}))}addTrack(e){return ab(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?MD.AUXILIARY:MD.MAIN," stream")),null==(t=this._sei)||t.handleEncodedStreams(),vw()&&(yield this.addTrackByTransceiver(e,i))}))}addTrackByTransceiver(e,t){return ab(this,null,(function*(){var i;if(!e.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===MD.AUDIO)yield n[0].sender.replaceTrack(this._audioManager.mixedAudioTrack);else{let r=t?3:1;yield n[r].sender.replaceTrack(e.outMediaTrack),1===r&&(null==(i=this.localMainVideoTrack)?void 0:i.small)&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[r].direction===LD.INACTIVE&&(yield this.setTransceiverDirection(LD.SENDONLY,[r]))}this.updateMediaSettings(),yield this.doPublishChange()}))}removeTrack(e){return ab(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?MD.AUXILIARY:MD.MAIN," stream")),vw()&&(yield this.removeTrackByTransceiver(e,t))}))}removeTrackByTransceiver(e,t){return ab(this,null,(function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===MD.AUDIO)this._audioManager.mixedAudioTrack||(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(LD.INACTIVE,[e])}this.updateMediaSettings(),yield this.doPublishChange()}))}setTransceiverDirection(e,t){return ab(this,null,(function*(){if(!Ub)return;let i=!1,n=!1;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let r=this._peerConnection.getTransceivers();if(t.forEach((t=>{r[t].direction!==e&&(r[t].direction=e,i=!0)})),i){this._log.info("updating offer");let e=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(e)}let o=-1,s=this._peerConnection.remoteDescription.sdp.split("\r\n").map((i=>{if(i.match(new RegExp("a=(".concat(LD.INACTIVE,"|").concat(LD.RECVONLY,"|").concat(LD.SENDONLY,")")))&&o++,t.includes(o)){if(e===LD.INACTIVE&&i.includes("a=".concat(LD.RECVONLY)))return n=!0,"a=".concat(e);if(e===LD.SENDONLY&&i.includes("a=".concat(LD.INACTIVE)))return n=!0,"a=".concat(LD.RECVONLY)}return i})).join("\r\n");n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:s}))}))}replaceTrack(e){return ab(this,null,(function*(){var t;let i=null==(t=this._peerConnection)?void 0:t.getSenders(),n=e.outMediaTrack||e.mediaTrack;if(!i||0===i.length||!n||i.find((e=>e.track===n)))return;let r=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is replacing ".concat(n.kind," track on ").concat(r?MD.AUXILIARY:MD.MAIN," stream")),n.kind===MD.AUDIO&&i[0]&&(yield i[0].replaceTrack(this._audioManager.mixedAudioTrack)),n.kind===MD.VIDEO&&(!r&&i[1]&&(yield i[1].replaceTrack(n)),r&&i[3]&&(yield i[3].replaceTrack(n)))}))}setBandwidth(e){return ab(this,arguments,(function(e){var t=this;let{bandwidth:i,type:n,videoType:r}=e;return function*(){if(t.singlePC){let e={};n===MD.AUDIO?e.audio=i:"big"===r?e.bigVideo=i:"small"===r?e.smallVideo=i:e.auxVideo=i,yield t.singlePC.setBandwidth(e)}}()}))}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.send(Rx,this.muteState))}handleConnectionStateChange(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&FO.emit(HO.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:MD.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===MD.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===MD.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===MD.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&e===MD.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(0!==e)throw e===mN?(this._log.error(zO.NOT_SUPPORTED_H264ENCODE),new gb({code:_b.NOT_SUPPORTED_H264,message:XO({key:YO.NOT_SUPPORTED_H264ENCODE})})):new gb({code:_b.UNKNOWN,message:XO({key:YO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Sx.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var i;null==(i=this._sei)||i.push(e,t)}onSinglePCReconnected(){return ab(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 NU(e){return Object.keys(e).filter((t=>e[t]))}var OU=class extends kU{constructor(e){super(eb(ZC({},e),{isUplink:!1})),ob(this,"_flag",0),ob(this,"role","anchor"),ob(this,"remoteAudioTrack"),ob(this,"remoteVideoTrack"),ob(this,"remoteAuxiliaryTrack"),ob(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),this.flag=e.flag,this.remoteAudioTrack=new MM(this._room,this),this.remoteVideoTrack=new LM(this._room,this),this.remoteAuxiliaryTrack=new xM(this._room,this),this.initialize()}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 IO(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,n;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(i=this.remoteVideoTrack)||i.onFlagChanged(),null==(n=this.remoteAuxiliaryTrack)||n.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===MD.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){!this.singlePC||(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var t,i;let n=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&n!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:n,state:e}),null==(i=this.remoteAuxiliaryTrack)||i.emit("connection-state-changed",{prevState:n,state:e})),r}onTrack(e){let t=e.streams[0],{track:i}=e;if(t.id.split("-")[0]!==this.tinyId)return;let n=t.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(n," ").concat(i.kind));let r=MD.AUDIO;i.kind===MD.VIDEO&&(r=n===MD.MAIN?MD.VIDEO:MD.AUXILIARY);let o=this.remoteAudioTrack;r===MD.VIDEO?o=this.remoteVideoTrack:r===MD.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(i)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return ab(this,null,(function*(){try{if(this.isSubscriptionStateNotChanged(e))return;if(this._log.info("subscribe ".concat(t," ").concat(NU(e))),this.hasSSRC){let t="subscribe_change";Object.values(e).find((e=>!0===e))||(t="unsubscribe"),yield this.sendSubscription(t,e)}else yield this.doSubscribe(e)}catch(aD){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(aD.message," ").concat(JSON.stringify(this.muteState))),new gb({code:_b.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):aD}}))}unsubscribe(e){return ab(this,arguments,(function(e){var t=this;let{remoteTracks:i,streamType:n}=e;return function*(){var e;if("main"===n&&!t.isMainStreamSubscribed||"auxiliary"===n&&!t.isAuxStreamSubscribed)return void t._log.info("".concat(n," stream already unsubscribed"));let r=ZC({},t.subscribeState);i.forEach((e=>{switch(e.mediaType){case 1:r.audio=!1;break;case 4:r.video=!1;break;case 8:r.smallVideo=!1;break;case 2:r.auxiliary=!1}}));let o="subscribe_change";Object.values(r).find((e=>!0===e))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(n," [").concat(NU(r),"]")),"unsubscribe"===o&&(null==(e=t.singlePC)||e.removeDownlinkQueue.add(t.tinyId)),yield t.sendSubscription(o,r),"unsubscribe"===o&&(yield t.removeDownlink())}()}))}sendSubscription(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},n=Nx,r=Sx.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=Ox,r=Sx.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:i,responseCommand:r,timeout:1e4}).then((t=>{let{data:i}=t;if(0!==i.code){let t=new gb({code:i.code,message:XO({key:YO.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,!1))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return ab(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:CU(),bigVideoSsrc:CU(),bigVideoRtxSsrc:CU(),auxVideoSsrc:CU(),auxVideoRtxSsrc:CU()},{audioSsrc:r,bigVideoSsrc:o,bigVideoRtxSsrc:s,auxVideoSsrc:a,auxVideoRtxSsrc:c}=i;e.ssrc={audio:r,video:o,videoRtx:s,auxiliary:a,auxiliaryRtx:c},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let n=yield e._signalChannel.sendWaitForResponseWithRetry({command:Wx,responseCommand:Sx.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});if(0!==n.data.code)throw new gb({code:n.data.code,message:n.data.message})}catch(n){throw yield e.removeDownlink(),n}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}}()}))}removeDownlink(){return ab(this,null,(function*(){!this.singlePC||(this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),yield this.singlePC.removeDownlink(this.tinyId,this.userId))}))}};rb([oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return new Promise(((t,n)=>{let r=e=>{this.off("closed",r),n(new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.CONNECTION_ABORTED,data:e})}))};this.on("closed",r),e.apply(this,i).then(t,n).finally((()=>{this.off("closed",r)}))}))}))],OU.prototype,"subscribe",1);var wU=OU;var{isString:PU,isPlainObject:MU,isUndefined:LU,getNetworkType:xU,getTerminalType:VU,isEmpty:UU}=Ib,FU=class extends lU{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=Aw,this._changeBigSmallRecords=new Map,this._networkQuality=null,this._networkType=xU(),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 CV(this,this._log),this.userManager=new tL(this.userId,this._log),this._version=rD,this.sdpSemantics=pN,LU(e.sdpSemantics)?KO.isUnifiedPlanDefault()&&(this.sdpSemantics=hN):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(this._networkType)),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!LU(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI,!LU(e.enableSPC)&&Aw&&(this.enableSPC=e.enableSPC),this.enableHWEncoder=e.enableHWEncoder||!1,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex((e=>e.muteState.hasAuxiliary))>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map((e=>[e.tinyId,e.userId])))}join(e,t,i){return ab(this,null,(function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",(e=>{this.emit("peer-join",e)})),this.userManager.on("2",(e=>{this.closeDownLinkConnection(e,"remote user exitRoom"),this.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(e=>{var t=((e,t)=>{var i={};for(var n in e)zC.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&KC)for(var n of KC(e))t.indexOf(n)<0&&qC.call(e,n)&&(i[n]=e[n]);return i})(e,[]);FO.emit(HO.REMOTE_PUBLISH_STATE_CHANGED,ZC({room:this},t)),this.emit("remote-publish-state-changed",ZC({},t))})),this._joinOptions=e,new Promise(((t,i)=>ab(this,null,(function*(){this._joinReject=i;try{this.checkDestroy();let i=yield this.initialize();yield this.doJoin(e,i),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(n){i(n)}this._joinReject=null}))))}))}doJoin(e){return new Promise(((t,i)=>ab(this,null,(function*(){var n,r,o;let s;if(e.privateMapKey&&(this.privateMapKey=e.privateMapKey),this._signalChannel.once(mx,(e=>{this.clearJoinTimeout(),FO.emit(HO.JOIN_SIGNAL_CONNECTION_END,{room:this,error:e}),i(e)})),sO(null==(r=null==(n=this.scheduleResult)?void 0:n.config)?void 0:r.singlePC)&&Aw&&(this.enableSPC=this.scheduleResult.config.singlePC),this.enableSPC&&!this.singlePC){this.singlePC=new vU({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{s=yield this.singlePC.initialize()}catch(l){this.fallbackToMPC()}}this.keyPointManager.setConnectionType(this.singlePC?1:2);let a={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:VU(),netType:kD[this._networkType],bussinessInfo:this._businessInfo,ability:s,sdkType:this._sdkType,userSig:this.userSig};this._log.debug("join room signal data: ".concat(JSON.stringify(a)));let c=5e3;(null==(o=this.scheduleResult.config)?void 0:o.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((()=>{i(new gb({code:_b.JOIN_ROOM_FAILED,message:XO({key:YO.JOIN_ROOM_TIMEOUT})}))}),c),FO.emit(HO.JOIN_SEND_CMD,{room:this}),this._signalChannel.send(this.singlePC?jx:vx,a),this._signalChannel.once(Sx.JOIN_ROOM_RESULT,(e=>{this.clearJoinTimeout();let{code:n,message:r,data:o,tinyId:s}=e.data;FO.emit(HO.JOIN_RECEIVED_CMD_RES,{room:this,code:n}),0===n?(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((()=>{})),t()):(this._log.error("Join room failed result: ".concat(n," error: ").concat(r)),i(new gb({code:_b.JOIN_ROOM_FAILED,extraCode:n,message:XO({key:YO.JOIN_ROOM_FAILED,data:{error:r,code:n}})})))}))}))))}reJoin(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ab(this,null,(function*(){if(this.isJoined)try{if(this._log.warn("reJoin pending: ".concat(this._joinOptions.roomId)),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this._signalChannel&&(this._signalChannel.race=e,this._signalChannel.close(),yield this._signalChannel.connect()),yield this.doJoin(eb(ZC({},this._joinOptions),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),$w.logSuccessEvent({userId:this.userId,eventType:cN.REJOIN}),this.singlePC){let e=t=>{var i;"CONNECTED"===t.state&&(null==(i=this.singlePC)||i.off(gU.CONNECTION_STATE_CHANGED,e),this.uplinkConnection instanceof DU&&this.uplinkConnection.onSinglePCReconnected(),this.remotePublishedUserMap.forEach((e=>{e.installEvents(),e.doSubscribe()})))};this.singlePC.on(gU.CONNECTION_STATE_CHANGED,e),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof RV&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(sN){this._log.warn("reJoin fail ".concat(sN)),this.reset(),$w.logFailedEvent({userId:this.userId,eventType:cN.REJOIN,error:sN}),this.emit("error",new gb({code:_b.JOIN_ROOM_FAILED,message:XO({key:YO.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}else this._log.warn("reJoin abort")}))}initialize(){return ab(this,null,(function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),i=this._signalChannel||function(e){let t=[...oV.values()].find((t=>t.room.userId===e&&!t.room.isJoined));return t||null}(this.userId),n=!!(i&&i.isConnected&&i.keepAlive);return this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(i.url=e,i.backupUrl=t,i.room=this,this._signalChannel=i):this._signalChannel=new sV({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC,room:this}),this._networkQuality||(this._networkQuality=new DV({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(DV.EVENT_NETWORK_QUALITY,(e=>{this.emit("network-quality",e)}))),vP(this,this._signalChannel).add(_x,(e=>{FO.emit(HO.SIGNAL_CONNECTION_STATE_CHANGED,ZC({room:this},e)),this.emit("signal-connection-state-changed",e)})).add(gx,(e=>{this.reset(),this.emit("error",e)})).add(Sx.PEER_JOIN,(e=>{let{srcTinyId:t,userId:i,role:n}=e.data.data;this.userManager.addUser({userId:i,tinyId:t,role:n})})).add(Sx.PEER_LEAVE,(e=>{let{userId:t,reason:i=0}=e.data.data;this.userManager.deleteUser(t,i)})).add(Sx.UPDATE_REMOTE_MUTE_STAT,(e=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(e.data)})).add(Sx.CLIENT_BANNED,(e=>{let t=e.data.data,{reason:i}=t;if($w.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(px,(e=>{this.tinyId=e.signalInfo.tinyId,FO.emit(HO.JOIN_SIGNAL_CONNECTION_END,{room:this})})),FO.emit(HO.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this._signalChannel.connect(),n}))}setSignalChannel(e){this._signalChannel=e,e||yP(this)}leave(){return ab(this,null,(function*(){var e;try{yield this.doHeartbeat()}catch(sN){}this._log.info("leave() => leaving room"),FO.emit(HO.LEAVE_SEND_CMD,{room:this}),null==(e=this._signalChannel)||e.send(yx)}))}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=Qw.run(wN,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),Qw.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return ab(this,null,(function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});if(this.badCaseDetector.resetMonitor(),null==(e=this._signalChannel)||!e.isConnected)return;let n=this._signalChannel.isConnected?function(e){if($M.has(e)){let t=$M.get(e).map((e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc})));return $M.delete(e),t}return[]}(this.userId):[],r=ZC({str_sdk_version:nD,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:kD[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i);FO.emit(HO.HEARTBEAT_REPORT,{room:this,report:r}),this._signalChannel.send(Ax,r),this.emit("heartbeat-report",eb(ZC({},r),{bytes_sent:this._stats.totalBytesSent+this._signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this._signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)}))}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map((e=>{let{userId:t,srcTinyId:i,flag:n}=e,r=this.remotePublishedUserMap.get(t);return r&&this.checkSubscribeBigSmallVideo(r),{userId:t,tinyId:i,flag:n}}));FO.emit(HO.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection=null),this.localTracks.forEach((e=>e.unpublish())),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:n}=e,r=new(this.singlePC?wU:IV)({userId:t,tinyId:i,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(r),this.installDownlinkEvents(r,t),this.emit("remote-published",r)}closeDownLinkConnection(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",(e=>{let i=e.getCode();i!==_b.ICE_TRANSPORT_ERROR&&(i===_b.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",e))})),e.on("connection-state-changed",(t=>{this.emit("media-connection-state-changed",eb(ZC({},t),{userId:e.userId}))})),e.on("firewall-restriction",(()=>{this.emit("firewall-restriction")}))}startSyncUserListInterval(){-1===this._syncUserListInterval&&(this._syncUserListInterval=Qw.run(wN,this.syncUserList.bind(this)))}stopSyncUserListInterval(){Qw.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:Ux,responseCommand:Sx.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((e=>{let{data:t}=e,{code:i,message:n}=t;if(0===i)return(t.data&&t.data.userList||[]).map((e=>{let{userId:t,srcTinyId:i,role:n}=e;return{userId:t,tinyId:i,role:n}}));throw XO({key:YO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Sx.USER_LIST_RES,code:i,message:n}})})):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this._signalChannel&&!this._signalChannel.isOnline||!pV)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(){this.singlePC||this.getAllConnections().forEach((e=>{if(e instanceof mV&&!e.getIsReconnecting()){let t=e.getPeerConnection();t&&t.connectionState===iN.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}fallbackToMPC(){return ab(this,null,(function*(){var e;if(this._log.warn("fallback to multi pc"),$w.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(e=this.singlePC)||e.close(),this.singlePC=null,yield this.reJoin(!1),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new RV({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0}))}this.remotePublishedUserMap.forEach((e=>{let t=new IV({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 gb({code:_b.INVALID_OPERATION,message:XO({key:YO.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return ab(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:Fx,data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey},responseCommand:Sx.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this._signalChannel.sendWaitForResponseWithRetry(t).then((t=>{let{code:i,message:n}=t.data;if(0!==i)throw new gb({code:_b.SWITCH_ROLE_FAILED,message:XO({key:YO.SWITCH_ROLE_FAILED,data:{message:n,code:i}})});this.role=e})).catch((e=>{throw e instanceof gb&&e.getCode()===_b.API_CALL_TIMEOUT&&(e=new gb({code:_b.SWITCH_ROLE_FAILED,message:XO({key:YO.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 ab(this,null,(function*(){let e={},i={};t.forEach((t=>{t instanceof hM&&(t instanceof fM?i.audio=t:e.audio=t),t instanceof pM&&(t instanceof _M&&2===t.mediaType?i.video=t:e.video=t)}));let n=UU(e),r=UU(i);(!n||!r)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new DU({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}):this.uplinkConnection=new RV({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",eb(ZC({},e),{userId:this.userId}))})),this.uplinkConnection.on("firewall-restriction",(()=>{this.emit("firewall-restriction")})),this.uplinkConnection.on("error",(e=>{let t=e.getCode();t!==_b.ICE_TRANSPORT_ERROR&&(t===_b.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})));let o=t.map((e=>e.kind)).join(",");n||(this._log.info("publish() => main ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:e.audio,localVideoTrack:e.video,isAuxiliary:!1}),this._log.info("main is published")),r||(this._log.info("publish() => aux ".concat(o)),yield this.uplinkConnection.publish({localAudioTrack:i.audio,localVideoTrack:i.video,isAuxiliary:!0}),this._log.info("aux is published"))}))}unpublish(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ab(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 hM&&(t instanceof fM?i.audio=t:e.audio=t),t instanceof pM&&(t instanceof _M&&2===t.mediaType?i.video=t:e.video=t))}));try{let n=t.map((e=>e.kind)).join(",");UU(e)||(this._log.info("unpublish() => main ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:e.audio,localVideoTrack:e.video})),UU(i)||(this._log.info("unpublish() => aux ".concat(n)),yield this.uplinkConnection.unpublish({localAudioTrack:i.audio,localVideoTrack:i.video}))}catch(n){}0===this.localTracks.size&&!this.audioManager.mixedAudioTrack&&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?this.uplinkConnection.replaceTrack(e).then((t=>{FO.emit(HO.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}setBandWidth(e){return ab(this,null,(function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())}))}enableSmall(e){return ab(this,null,(function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:MD.VIDEO,videoType:MD.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 ab(this,null,(function*(){if(t=t.filter((e=>!e.isSubscribed)),0===t.length)return;let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";try{let r=ZC({},i.subscribeState);t.forEach((e=>{switch(e.mediaType){case 1:r.audio=!0;break;case 4:r.video=!0;break;case 2:r.auxiliary=!0}}));let o=this._changeBigSmallRecords.get(e);o&&o.options.smallVideo&&i.muteState.hasSmall&&r.video&&(r.video=!1,r.smallVideo=!0),FO.emit(HO.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:i,subscribeState:r}),this._log.info("subscribe() => ".concat(e," ").concat(n," [").concat(TV(r),"] prev: [").concat(TV(i.subscribeState),"]")),yield i.subscribe(r,n);for(let e of t)e.mediaTrack||(yield e.waitHasMediaTrack());i.remoteVideoTrack.setMediaType(r.smallVideo?8:4),FO.emit(HO.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}catch(cD){let i=cD instanceof gb?cD.getCode():_b.UNKNOWN,r=cD;throw cD instanceof gb?i===_b.REMOTE_STREAM_NOT_EXIST&&(r=new gb({code:_b.API_CALL_ABORTED,message:XO({key:YO.API_CALL_ABORTED,data:{message:cD.message,userId:e,streamType:n}})}),this._log.warn(r)):(r=new gb({code:i,message:XO({key:YO.SUBSCRIBE_FAILED,data:{message:cD.message,userId:e,streamType:n}})}),this._log.error(r)),r}}))}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ab(this,null,(function*(){let{userId:e}=t[0],i=this.remotePublishedUserMap.get(e);if(!i)return;let n=t.find((e=>2===e.mediaType))?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(e," ").concat(n));try{yield i.unsubscribe({remoteTracks:t,streamType:n})}catch(cD){this._log.warn("unsubscribe() => failed ".concat(cD))}t.forEach((e=>{e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),FO.emit(HO.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:i})}))}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void Qw.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),FO.emit(HO.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&Qw.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Qw.run(PN,(()=>{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 ab(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 ab(this,null,(function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:i,framesEncoded:n,framesSent:r,frameWidth:o,frameHeight:s}}return e}))}getTransportStats(){return ab(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 ab(this,null,(function*(){let t={};for(let[i,n]of this.remotePublishedUserMap)"main"===e&&n.muteState.hasVideo&&(t[i]=n.remoteVideoTrack.stat),"auxiliary"===e&&n.muteState.hasAuxiliary&&(t[i]=n.remoteAuxiliaryTrack.stat);return t}))}getRemoteAudioStats(){return ab(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(Ib.getTurnServer(e)))):Ib.isPlainObject(e)&&i.push(Ib.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:xx,data:e,timeout:5e3,responseCommand:Sx.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:Vx,data:e,timeout:5e3,responseCommand:Sx.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?wx:Mx,data:e,timeout:5e3,responseCommand:t?Sx.START_PUBLISH_TENCENT_CDN_RES:Sx.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?Px:Lx,data:e,timeout:5e3,responseCommand:t?Sx.STOP_PUBLISH_TENCENT_CDN_RES:Sx.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;null==(t=this._signalChannel)||t.sendWaitForResponse({command:Jx,data:e,timeout:5e3,responseCommand:Sx.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=Ib.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 ab(this,null,(function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:n,hasVideo:r}}=e;if(!n&&!r||!t.video&&!t.smallVideo)return;let o=this._changeBigSmallRecords.get(i);if(!o||o.isSubscribing||o.reSubscribeCount<=0)return;let{options:s,reSubscribeCount:a}=o;if(s.video&&t.video||s.smallVideo&&t.smallVideo&&n)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:s.video,smallVideo:s.smallVideo};try{if(!n&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;o.isSubscribing=!0,o.reSubscribeCount=a-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(NN-o.reSubscribeCount,".")),o.isSubscribing=!1,o.reSubscribeCount=NN}catch(l){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(NN-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:NN};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(PU(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!LU(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new gb({code:_b.INVALID_PARAMETER,message:XO({key:YO.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(!LU(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(null===e.userDefineRecordId.match(i))throw new gb({code:_b.INVALID_PARAMETER,message:XO({key:YO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!LU(e.userDefinePushArgs)){if(!(PU(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new gb({code:_b.INVALID_PARAMETER,message:XO({key:YO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}UU(t)||(this._businessInfo=JSON.stringify(t))}sendSEI(e,t){this.singlePC&&this.singlePC.sendSEI(e,t)}};return rb([cx(["left",ux.INIT],"joined"),zx({settings:{retries:1,timeout:0},onError(e,t,i){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),$x(!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))}}),oM((e=>{let t=new ex;return function(i,n,r){return ab(this,null,(function*(){let o=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=n,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new gb({code:_b.INVALID_OPERATION,message:XO({key:YO.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)),FO.emit(HO.JOIN_START,{room:this,roomId:o,params:i}),this.checkSystemResult=yield KO.checkSystemRequirementsInternal(),this.checkDestroy();let s=Ib.getEnv();s||(s=AD.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(xD.OLD_CLOUD_LADDER)?s=AD.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(xD.WEBRTC)&&(s=AD.WEBRTC))),$w.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),tx.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!KO.isWebRTCSupported()||!a&&!c)throw new gb({code:_b.NOT_SUPPORTED,message:XO({key:YO.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ib.getEnv()&&(yield this.schedule(o,r));let t=yield e.call(this,i,n,r);return this.roomId=o,this._joinedTimestamp=Ib.performanceNow(),FO.emit(HO.JOIN_SUCCESS,{room:this}),$w.uploadEvent({log:"stat-conv-".concat(Number(Yk),"-").concat(location.hostname),userId:this.userId}),t}catch(l){throw t.delete({room:this,roomId:o}),FO.emit(HO.JOIN_FAILED,{room:this,error:l}),l}}))}}))],FU.prototype,"join",1),rb([cx("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),oM((e=>function(){return ab(this,null,(function*(){FO.emit(HO.LEAVE_START,{room:this}),yield e.call(this),FO.emit(HO.LEAVE_SUCCESS,{room:this,roomId:this.roomId})}))})),function(e){return function(t,i,n){let r=n.value;return n.value=function(){var t,i;let n=[];for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return null==(t=sM.get(this))||t.forEach((e=>n.push(e))),null==(i=aM.get(this))||i.forEach((e=>e.forEach((e=>n.push(e))))),n.forEach((t=>{t.reject(new gb({code:_b.API_CALL_ABORTED,message:e}))})),sM.delete(this),aM.delete(this),r.apply(this,s)},n}}("leave room"),qx({fnName:"publish",validateArgs:!1}),qx({fnName:"unsubscribe",validateArgs:!1})],FU.prototype,"leave",1),rb([cM(),oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return ab(this,null,(function*(){if("live"===this.scene&&"anchor"!==this.role||(i=i.filter((e=>e.outMediaTrack&&"capture"===e.state)),!i.length))return;FO.emit("61",{room:this});for(let e of i)"audio"===e.kind&&(yield this.audioManager.addAudioTrack(e));let t=e.apply(this,i);return i.forEach((e=>{var i;e.publish(this,t),"audio"===e.kind&&(null==(i=this.audioManager.localMixAudioTrack)||i.publish(this,t))})),t}))})),zx({settings:{retries:oN,timeout:e=>eO(e)},onError(e,t,i){var n;null!=(n=e.message)&&n.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),i(e),FO.emit(HO.PUBLISH_FAILED,{room:this}))}})],FU.prototype,"publish",1),rb([qx({fnName:"publish",callback(){for(var e,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];0===this.localTracks.size&&(null==(e=this.uplinkConnection)||e.close("you unpublished"),this.uplinkConnection=null,i.forEach((e=>e.unpublish())))}}),function(e){return function(t,i,n){let r=n.value;return n.value=function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let o=sM.get(this);if(o){let t=o.filter(((t,n)=>{if(0===n)return!0;let r=!0;return t.args.forEach((e=>{i.find((t=>t===e))||(r=!1)})),!r||(t.reject(new gb({code:_b.API_CALL_ABORTED,message:e})),!1)}));sM.set(this,t)}return r.apply(this,i)},n}}("api-call"),cM(),oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((e=>{"audio"===e.kind&&this.audioManager.removeAudioTrack(e)}));let r=e.apply(this,i);return i.forEach((e=>e.unpublish())),r}))],FU.prototype,"unpublish",1),rb([lM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId})),oM((e=>function(){for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];let r=e.apply(this,i);return i.forEach((e=>!e.isSubscribed&&e.subscribe(r))),r})),zx({settings:{retries:oN,timeout:e=>eO(e)},onError(e,t,i,n){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),i(e),FO.emit(HO.SUBSCRIBE_FAILED,{room:this,remoteTracks:n}))}})],FU.prototype,"subscribe",1),rb([qx({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")}))}}),lM((function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId}))],FU.prototype,"unsubscribe",1),ZL.create=ZL._create.bind(ZL,FU),ZL}));
|